title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
HTTP headers | Access-Control-Max-Age - GeeksforGeeks
07 Nov, 2019 The Access-Control-Max-Age HTTP header is a response header that gives the time for which results of a CORS preflight request that checks to see if the CORS protocol is understood and a server is aware using specific methods and headers, can be cached. The CORS preflight request contained in the Access-Control-Allow-Methods and Access-Control-Allow-Headers headers. Syntax: Access-Control-Max-Age: <delta-seconds> Directives: This header accepts a single directive mentioned above and described below: <delta-seconds>: It specifies how many maximum seconds can the result be cached. Note: If -1 is present then caching is disabled. Examples: In this example, the results of a preflight request get cached for 200 seconds.Access-Control-Max-Age: 200 Access-Control-Max-Age: 200 In this example, the results are not allowed to be cached.Access-Control-Max-Age: -1 Access-Control-Max-Age: -1 To check this Access-Control-Max-Age in action, go to Inspect Element -> Network check the response header for Access-Control-Max-Age like below, Access-Control-Max-Age is highlighted you can see. Supported Browsers: The browsers are compatible with HTTP Access-Control-Max-Age header are listed below: Google Chrome 4.0 Internet Explorer 10.0 Opera 12.0 Firefox 3.5 Safari 4.0 HTTP-headers Picked Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Roadmap to Become a Web Developer in 2022 How to fetch data from an API in ReactJS ? Convert a string to an integer in JavaScript Top 10 Angular Libraries For Web Developers Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to Insert Form Data into Database using PHP ? How to redirect to another page in ReactJS ? Set the value of an input field in JavaScript How to execute PHP code using command line ?
[ { "code": null, "e": 24836, "s": 24808, "text": "\n07 Nov, 2019" }, { "code": null, "e": 25204, "s": 24836, "text": "The Access-Control-Max-Age HTTP header is a response header that gives the time for which results of a CORS preflight request that checks to see if the CORS protocol is understood and a server is aware using specific methods and headers, can be cached. The CORS preflight request contained in the Access-Control-Allow-Methods and Access-Control-Allow-Headers headers." }, { "code": null, "e": 25212, "s": 25204, "text": "Syntax:" }, { "code": null, "e": 25252, "s": 25212, "text": "Access-Control-Max-Age: <delta-seconds>" }, { "code": null, "e": 25340, "s": 25252, "text": "Directives: This header accepts a single directive mentioned above and described below:" }, { "code": null, "e": 25421, "s": 25340, "text": "<delta-seconds>: It specifies how many maximum seconds can the result be cached." }, { "code": null, "e": 25470, "s": 25421, "text": "Note: If -1 is present then caching is disabled." }, { "code": null, "e": 25480, "s": 25470, "text": "Examples:" }, { "code": null, "e": 25587, "s": 25480, "text": "In this example, the results of a preflight request get cached for 200 seconds.Access-Control-Max-Age: 200" }, { "code": null, "e": 25615, "s": 25587, "text": "Access-Control-Max-Age: 200" }, { "code": null, "e": 25700, "s": 25615, "text": "In this example, the results are not allowed to be cached.Access-Control-Max-Age: -1" }, { "code": null, "e": 25727, "s": 25700, "text": "Access-Control-Max-Age: -1" }, { "code": null, "e": 25924, "s": 25727, "text": "To check this Access-Control-Max-Age in action, go to Inspect Element -> Network check the response header for Access-Control-Max-Age like below, Access-Control-Max-Age is highlighted you can see." }, { "code": null, "e": 26030, "s": 25924, "text": "Supported Browsers: The browsers are compatible with HTTP Access-Control-Max-Age header are listed below:" }, { "code": null, "e": 26048, "s": 26030, "text": "Google Chrome 4.0" }, { "code": null, "e": 26071, "s": 26048, "text": "Internet Explorer 10.0" }, { "code": null, "e": 26082, "s": 26071, "text": "Opera 12.0" }, { "code": null, "e": 26094, "s": 26082, "text": "Firefox 3.5" }, { "code": null, "e": 26105, "s": 26094, "text": "Safari 4.0" }, { "code": null, "e": 26118, "s": 26105, "text": "HTTP-headers" }, { "code": null, "e": 26125, "s": 26118, "text": "Picked" }, { "code": null, "e": 26142, "s": 26125, "text": "Web Technologies" }, { "code": null, "e": 26240, "s": 26142, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26249, "s": 26240, "text": "Comments" }, { "code": null, "e": 26262, "s": 26249, "text": "Old Comments" }, { "code": null, "e": 26304, "s": 26262, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 26347, "s": 26304, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 26392, "s": 26347, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 26436, "s": 26392, "text": "Top 10 Angular Libraries For Web Developers" }, { "code": null, "e": 26497, "s": 26436, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 26569, "s": 26497, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 26619, "s": 26569, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 26664, "s": 26619, "text": "How to redirect to another page in ReactJS ?" }, { "code": null, "e": 26710, "s": 26664, "text": "Set the value of an input field in JavaScript" } ]
ASP.NET - Multi Threading
A thread is defined as the execution path of a program. Each thread defines a unique flow of control. If your application involves complicated and time consuming operations such as database access or some intense I/O operations, then it is often helpful to set different execution paths or threads, with each thread performing a particular job. Threads are lightweight processes. One common example of use of thread is implementation of concurrent programming by modern operating systems. Use of threads saves wastage of CPU cycle and increases efficiency of an application. So far we compiled programs where a single thread runs as a single process which is the running instance of the application. However, this way the application can perform one job at a time. To make it execute multiple tasks at a time, it could be divided into smaller threads. In .Net, the threading is handled through the 'System.Threading' namespace. Creating a variable of the System.Threading.Thread type allows you to create a new thread to start working with. It allows you to create and access individual threads in a program. A thread is created by creating a Thread object, giving its constructor a ThreadStart reference. ThreadStart childthreat = new ThreadStart(childthreadcall); The life cycle of a thread starts when an object of the System.Threading.Thread class is created and ends when the thread is terminated or completes execution. Following are the various states in the life cycle of a thread: The Unstarted State : It is the situation when the instance of the thread is created but the Start method is not called. The Unstarted State : It is the situation when the instance of the thread is created but the Start method is not called. The Ready State : It is the situation when the thread is ready to execute and waiting CPU cycle. The Ready State : It is the situation when the thread is ready to execute and waiting CPU cycle. The Not Runnable State : a thread is not runnable, when: Sleep method has been called Wait method has been called Blocked by I/O operations The Not Runnable State : a thread is not runnable, when: Sleep method has been called Wait method has been called Blocked by I/O operations The Dead State : It is the situation when the thread has completed execution or has been aborted. The Dead State : It is the situation when the thread has completed execution or has been aborted. The Priority property of the Thread class specifies the priority of one thread with respect to other. The .Net runtime selects the ready thread with the highest priority. The priorities could be categorized as: Above normal Below normal Highest Lowest Normal Once a thread is created, its priority is set using the Priority property of the thread class. NewThread.Priority = ThreadPriority.Highest; The Thread class has the following important properties: The Thread class has the following important methods: The following example illustrates the uses of the Thread class. The page has a label control for displaying messages from the child thread. The messages from the main program are directly displayed using the Response.Write() method. Hence they appear on the top of the page. The source file is as follows: <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="threaddemo._Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title> Untitled Page </title> </head> <body> <form id="form1" runat="server"> <div> <h3>Thread Example</h3> </div> <asp:Label ID="lblmessage" runat="server" Text="Label"> </asp:Label> </form> </body> </html> The code behind file is as follows: using System; using System.Collections; using System.Configuration; using System.Data; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; using System.Threading; namespace threaddemo { public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { ThreadStart childthreat = new ThreadStart(childthreadcall); Response.Write("Child Thread Started <br/>"); Thread child = new Thread(childthreat); child.Start(); Response.Write("Main sleeping for 2 seconds.......<br/>"); Thread.Sleep(2000); Response.Write("<br/>Main aborting child thread<br/>"); child.Abort(); } public void childthreadcall() { try{ lblmessage.Text = "<br />Child thread started <br/>"; lblmessage.Text += "Child Thread: Coiunting to 10"; for( int i =0; i<10; i++) { Thread.Sleep(500); lblmessage.Text += "<br/> in Child thread </br>"; } lblmessage.Text += "<br/> child thread finished"; }catch(ThreadAbortException e){ lblmessage.Text += "<br /> child thread - exception"; }finally{ lblmessage.Text += "<br /> child thread - unable to catch the exception"; } } } } When the page is loaded, a new thread is started with the reference of the method childthreadcall(). The main thread activities are displayed directly on the web page. When the page is loaded, a new thread is started with the reference of the method childthreadcall(). The main thread activities are displayed directly on the web page. The second thread runs and sends messages to the label control. The second thread runs and sends messages to the label control. The main thread sleeps for 2000 ms, during which the child thread executes. The main thread sleeps for 2000 ms, during which the child thread executes. The child thread runs till it is aborted by the main thread. It raises the ThreadAbortException and is terminated. The child thread runs till it is aborted by the main thread. It raises the ThreadAbortException and is terminated. Control returns to the main thread. Control returns to the main thread. When executed the program sends the following messages: 51 Lectures 5.5 hours Anadi Sharma 44 Lectures 4.5 hours Kaushik Roy Chowdhury 42 Lectures 18 hours SHIVPRASAD KOIRALA 57 Lectures 3.5 hours University Code 40 Lectures 2.5 hours University Code 138 Lectures 9 hours Bhrugen Patel Print Add Notes Bookmark this page
[ { "code": null, "e": 2692, "s": 2347, "text": "A thread is defined as the execution path of a program. Each thread defines a unique flow of control. If your application involves complicated and time consuming operations such as database access or some intense I/O operations, then it is often helpful to set different execution paths or threads, with each thread performing a particular job." }, { "code": null, "e": 2922, "s": 2692, "text": "Threads are lightweight processes. One common example of use of thread is implementation of concurrent programming by modern operating systems. Use of threads saves wastage of CPU cycle and increases efficiency of an application." }, { "code": null, "e": 3199, "s": 2922, "text": "So far we compiled programs where a single thread runs as a single process which is the running instance of the application. However, this way the application can perform one job at a time. To make it execute multiple tasks at a time, it could be divided into smaller threads." }, { "code": null, "e": 3456, "s": 3199, "text": "In .Net, the threading is handled through the 'System.Threading' namespace. Creating a variable of the System.Threading.Thread type allows you to create a new thread to start working with. It allows you to create and access individual threads in a program." }, { "code": null, "e": 3553, "s": 3456, "text": "A thread is created by creating a Thread object, giving its constructor a ThreadStart reference." }, { "code": null, "e": 3613, "s": 3553, "text": "ThreadStart childthreat = new ThreadStart(childthreadcall);" }, { "code": null, "e": 3773, "s": 3613, "text": "The life cycle of a thread starts when an object of the System.Threading.Thread class is created and ends when the thread is terminated or completes execution." }, { "code": null, "e": 3837, "s": 3773, "text": "Following are the various states in the life cycle of a thread:" }, { "code": null, "e": 3958, "s": 3837, "text": "The Unstarted State : It is the situation when the instance of the thread is created but the Start method is not called." }, { "code": null, "e": 4079, "s": 3958, "text": "The Unstarted State : It is the situation when the instance of the thread is created but the Start method is not called." }, { "code": null, "e": 4176, "s": 4079, "text": "The Ready State : It is the situation when the thread is ready to execute and waiting CPU cycle." }, { "code": null, "e": 4273, "s": 4176, "text": "The Ready State : It is the situation when the thread is ready to execute and waiting CPU cycle." }, { "code": null, "e": 4416, "s": 4273, "text": "The Not Runnable State : a thread is not runnable, when:\n\nSleep method has been called\nWait method has been called\nBlocked by I/O operations\n\n" }, { "code": null, "e": 4473, "s": 4416, "text": "The Not Runnable State : a thread is not runnable, when:" }, { "code": null, "e": 4502, "s": 4473, "text": "Sleep method has been called" }, { "code": null, "e": 4530, "s": 4502, "text": "Wait method has been called" }, { "code": null, "e": 4556, "s": 4530, "text": "Blocked by I/O operations" }, { "code": null, "e": 4654, "s": 4556, "text": "The Dead State : It is the situation when the thread has completed execution or has been aborted." }, { "code": null, "e": 4752, "s": 4654, "text": "The Dead State : It is the situation when the thread has completed execution or has been aborted." }, { "code": null, "e": 4923, "s": 4752, "text": "The Priority property of the Thread class specifies the priority of one thread with respect to other. The .Net runtime selects the ready thread with the highest priority." }, { "code": null, "e": 4963, "s": 4923, "text": "The priorities could be categorized as:" }, { "code": null, "e": 4976, "s": 4963, "text": "Above normal" }, { "code": null, "e": 4989, "s": 4976, "text": "Below normal" }, { "code": null, "e": 4997, "s": 4989, "text": "Highest" }, { "code": null, "e": 5004, "s": 4997, "text": "Lowest" }, { "code": null, "e": 5011, "s": 5004, "text": "Normal" }, { "code": null, "e": 5106, "s": 5011, "text": "Once a thread is created, its priority is set using the Priority property of the thread class." }, { "code": null, "e": 5151, "s": 5106, "text": "NewThread.Priority = ThreadPriority.Highest;" }, { "code": null, "e": 5208, "s": 5151, "text": "The Thread class has the following important properties:" }, { "code": null, "e": 5262, "s": 5208, "text": "The Thread class has the following important methods:" }, { "code": null, "e": 5537, "s": 5262, "text": "The following example illustrates the uses of the Thread class. The page has a label control for displaying messages from the child thread. The messages from the main program are directly displayed using the Response.Write() method. Hence they appear on the top of the page." }, { "code": null, "e": 5568, "s": 5537, "text": "The source file is as follows:" }, { "code": null, "e": 6189, "s": 5568, "text": "<%@ Page Language=\"C#\" AutoEventWireup=\"true\" CodeBehind=\"Default.aspx.cs\" Inherits=\"threaddemo._Default\" %>\n\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n\n<html xmlns=\"http://www.w3.org/1999/xhtml\" >\n\n <head runat=\"server\">\n <title>\n Untitled Page\n </title>\n </head>\n \n <body>\n <form id=\"form1\" runat=\"server\">\n <div>\n <h3>Thread Example</h3>\n </div>\n \n <asp:Label ID=\"lblmessage\" runat=\"server\" Text=\"Label\">\n </asp:Label>\n </form>\n </body>\n \n</html>" }, { "code": null, "e": 6225, "s": 6189, "text": "The code behind file is as follows:" }, { "code": null, "e": 7850, "s": 6225, "text": "using System;\nusing System.Collections;\nusing System.Configuration;\nusing System.Data;\nusing System.Linq;\n\nusing System.Web;\nusing System.Web.Security;\nusing System.Web.UI;\nusing System.Web.UI.HtmlControls;\nusing System.Web.UI.WebControls;\nusing System.Web.UI.WebControls.WebParts;\n\nusing System.Xml.Linq;\nusing System.Threading;\n\nnamespace threaddemo\n{\n public partial class _Default : System.Web.UI.Page\n {\n protected void Page_Load(object sender, EventArgs e)\n {\n ThreadStart childthreat = new ThreadStart(childthreadcall);\n Response.Write(\"Child Thread Started <br/>\");\n Thread child = new Thread(childthreat);\n \n child.Start();\n \n Response.Write(\"Main sleeping for 2 seconds.......<br/>\");\n Thread.Sleep(2000);\n Response.Write(\"<br/>Main aborting child thread<br/>\");\n \n child.Abort();\n }\n \n public void childthreadcall()\n {\n try{\n lblmessage.Text = \"<br />Child thread started <br/>\";\n lblmessage.Text += \"Child Thread: Coiunting to 10\";\n \n for( int i =0; i<10; i++)\n {\n Thread.Sleep(500);\n lblmessage.Text += \"<br/> in Child thread </br>\";\n }\n \n lblmessage.Text += \"<br/> child thread finished\";\n \n }catch(ThreadAbortException e){\n \n lblmessage.Text += \"<br /> child thread - exception\";\n \n }finally{\n lblmessage.Text += \"<br /> child thread - unable to catch the exception\";\n }\n }\n }\n}" }, { "code": null, "e": 8018, "s": 7850, "text": "When the page is loaded, a new thread is started with the reference of the method childthreadcall(). The main thread activities are displayed directly on the web page." }, { "code": null, "e": 8186, "s": 8018, "text": "When the page is loaded, a new thread is started with the reference of the method childthreadcall(). The main thread activities are displayed directly on the web page." }, { "code": null, "e": 8250, "s": 8186, "text": "The second thread runs and sends messages to the label control." }, { "code": null, "e": 8314, "s": 8250, "text": "The second thread runs and sends messages to the label control." }, { "code": null, "e": 8390, "s": 8314, "text": "The main thread sleeps for 2000 ms, during which the child thread executes." }, { "code": null, "e": 8466, "s": 8390, "text": "The main thread sleeps for 2000 ms, during which the child thread executes." }, { "code": null, "e": 8581, "s": 8466, "text": "The child thread runs till it is aborted by the main thread. It raises the ThreadAbortException and is terminated." }, { "code": null, "e": 8696, "s": 8581, "text": "The child thread runs till it is aborted by the main thread. It raises the ThreadAbortException and is terminated." }, { "code": null, "e": 8732, "s": 8696, "text": "Control returns to the main thread." }, { "code": null, "e": 8768, "s": 8732, "text": "Control returns to the main thread." }, { "code": null, "e": 8824, "s": 8768, "text": "When executed the program sends the following messages:" }, { "code": null, "e": 8859, "s": 8824, "text": "\n 51 Lectures \n 5.5 hours \n" }, { "code": null, "e": 8873, "s": 8859, "text": " Anadi Sharma" }, { "code": null, "e": 8908, "s": 8873, "text": "\n 44 Lectures \n 4.5 hours \n" }, { "code": null, "e": 8931, "s": 8908, "text": " Kaushik Roy Chowdhury" }, { "code": null, "e": 8965, "s": 8931, "text": "\n 42 Lectures \n 18 hours \n" }, { "code": null, "e": 8985, "s": 8965, "text": " SHIVPRASAD KOIRALA" }, { "code": null, "e": 9020, "s": 8985, "text": "\n 57 Lectures \n 3.5 hours \n" }, { "code": null, "e": 9037, "s": 9020, "text": " University Code" }, { "code": null, "e": 9072, "s": 9037, "text": "\n 40 Lectures \n 2.5 hours \n" }, { "code": null, "e": 9089, "s": 9072, "text": " University Code" }, { "code": null, "e": 9123, "s": 9089, "text": "\n 138 Lectures \n 9 hours \n" }, { "code": null, "e": 9138, "s": 9123, "text": " Bhrugen Patel" }, { "code": null, "e": 9145, "s": 9138, "text": " Print" }, { "code": null, "e": 9156, "s": 9145, "text": " Add Notes" } ]
What is Arduino Ticker Library?
The ticker library in Arduino helps you to perform fixed interval operations. It is a great alternative to using delay() as the interval, since this will provide non-blocking usage. This library doesn't use any hardware timer interrupts. Rather, it works with micros() and millis() to organize your tasks. All you need to provide this library is the name of the function to be called, at what interval, and how many times this should be repeated. The library does the rest. In order to install this library, open the Library Manager, and search for 'Ticker'. Install the library by Stefan Staub. Once the library is installed, go to File → Examples → Ticker → Ticker. The example sketch begins with inclusion of the library. #include "Ticker.h" Then, the 5 functions that we will use as callbacks are declared. Also, a couple of global variables are defined. With the ticker library, there isn't any limit on the number of callbacks. void printMessage(); void printCounter(); void printCountdown(); void blink(); void printCountUS(); bool ledState; int counterUS; The next part is important. The 5 ticker objects are defined. Ticker timer1(printMessage, 0, 1); Ticker timer2(printCounter, 1000, 0, MILLIS); Ticker timer3(printCountdown, 1000, 5); Ticker timer4(blink, 500); Ticker timer5(printCountUS, 100, 0, MICROS_MICROS); The syntax of the ticker object constructor is − Ticker ticker_name(fptr callback, uint32_t timer, uint16_t repeats, interval_t mode) Where, callback is the function you wish to call callback is the function you wish to call timer is the time interval in ms or us, depending on the mode. timer is the time interval in ms or us, depending on the mode. repeats is the number of times this callback should be triggered (0 means endless, and it is the default option) repeats is the number of times this callback should be triggered (0 means endless, and it is the default option) mode can have 3 values − MILLIS − timer unit is milliseconds, Internal resolution in milliseconds MILLIS − timer unit is milliseconds, Internal resolution in milliseconds MICROS − timer unit is milliseconds, Internal resolution in microseconds (DEFAULT) MICROS − timer unit is milliseconds, Internal resolution in microseconds (DEFAULT) MICROS_MICROS − timer unit in microseconds, Internal resolution in microseconds MICROS_MICROS − timer unit in microseconds, Internal resolution in microseconds With default mode (MICROS), you can have time intervals up to 70 minutes. Use MILLIS for larger time intervals. Thus, timer1 callback is triggered just once, and immediately (interval = 0) timer1 callback is triggered just once, and immediately (interval = 0) timer2 callback is triggered every 1000 ms, with interval resolution in milliseconds. timer2 callback is triggered every 1000 ms, with interval resolution in milliseconds. timer3 callback is triggered 5 times, every second. timer3 callback is triggered 5 times, every second. timer4 callback is triggered every 500 ms. timer4 callback is triggered every 500 ms. timer5 callback is triggered every 100 microseconds, with internal resolution of microseconds. timer5 callback is triggered every 100 microseconds, with internal resolution of microseconds. Within the setup, you start the ticker objects defined earlier. void setup() { pinMode(LED_BUILTIN, OUTPUT); Serial.begin(9600); delay(2000); timer1.start(); timer2.start(); timer3.start(); timer4.start(); timer5.start(); } Within the loop, you constantly call .update() function, which essentially checks the ticker and runs the callback function if necessary. void loop() { timer1.update(); timer2.update(); timer3.update(); timer4.update(); timer5.update(); if (timer4.counter() == 20) timer4.interval(200); if (timer4.counter() == 80) timer4.interval(1000); } Notice that there is no delay() in the loop, and even in the setup after the timers are begun.As per the official documentation, "If you use delay(), the Ticker will be ignored! You cannot use delay() command with the TimerObject. Instead of using delay, you can use the Ticker itself. For example, if you need that your loop run twice per second, just create a Ticker with 500 ms. It will have the same result that delay(500), but your code will be always state." Essentially, ticker functions use the underlying timer that delay() uses. Therefore, you can't use delay along with ticker objects. The .counter() function returns the number of executed callbacks. Thus, we change the interval of timer4 after 20 triggers and then again after 80 triggers. Later, the definitions of the 5 callback functions are given, which are more or less selfexplanatory. void printCounter() { Serial.print("Counter "); Serial.println(timer2.counter()); } void printCountdown() { Serial.print("Countdowm "); Serial.println(5 - timer3.counter()); } void printMessage() { Serial.println("Hello!"); } void blink() { digitalWrite(LED_BUILTIN, ledState); ledState = !ledState; } void printCountUS() { counterUS++; if (counterUS == 10000) { Serial.println("10000 * 100us"); counterUS = 0; } } You can use this library for performing tasks at a fixed interval, either endlessly, or for a certain number of times.
[ { "code": null, "e": 1536, "s": 1062, "text": "The ticker library in Arduino helps you to perform fixed interval operations. It is a great alternative to using delay() as the interval, since this will provide non-blocking usage. This library doesn't use any hardware timer interrupts. Rather, it works with micros() and millis() to organize your tasks. All you need to provide this library is the name of the function to be called, at what interval, and how many times this should be repeated. The library does the rest." }, { "code": null, "e": 1658, "s": 1536, "text": "In order to install this library, open the Library Manager, and search for 'Ticker'. Install the library by Stefan Staub." }, { "code": null, "e": 1730, "s": 1658, "text": "Once the library is installed, go to File → Examples → Ticker → Ticker." }, { "code": null, "e": 1787, "s": 1730, "text": "The example sketch begins with inclusion of the library." }, { "code": null, "e": 1807, "s": 1787, "text": "#include \"Ticker.h\"" }, { "code": null, "e": 1996, "s": 1807, "text": "Then, the 5 functions that we will use as callbacks are declared. Also, a couple of global variables are defined. With the ticker library, there isn't any limit on the number of callbacks." }, { "code": null, "e": 2126, "s": 1996, "text": "void printMessage();\nvoid printCounter();\nvoid printCountdown();\nvoid blink();\nvoid printCountUS();\nbool ledState;\nint counterUS;" }, { "code": null, "e": 2188, "s": 2126, "text": "The next part is important. The 5 ticker objects are defined." }, { "code": null, "e": 2388, "s": 2188, "text": "Ticker timer1(printMessage, 0, 1);\nTicker timer2(printCounter, 1000, 0, MILLIS);\nTicker timer3(printCountdown, 1000, 5);\nTicker timer4(blink, 500);\nTicker timer5(printCountUS, 100, 0, MICROS_MICROS);" }, { "code": null, "e": 2437, "s": 2388, "text": "The syntax of the ticker object constructor is −" }, { "code": null, "e": 2522, "s": 2437, "text": "Ticker ticker_name(fptr callback, uint32_t timer, uint16_t repeats, interval_t mode)" }, { "code": null, "e": 2529, "s": 2522, "text": "Where," }, { "code": null, "e": 2571, "s": 2529, "text": "callback is the function you wish to call" }, { "code": null, "e": 2613, "s": 2571, "text": "callback is the function you wish to call" }, { "code": null, "e": 2676, "s": 2613, "text": "timer is the time interval in ms or us, depending on the mode." }, { "code": null, "e": 2739, "s": 2676, "text": "timer is the time interval in ms or us, depending on the mode." }, { "code": null, "e": 2852, "s": 2739, "text": "repeats is the number of times this callback should be triggered (0 means endless, and it is the default option)" }, { "code": null, "e": 2965, "s": 2852, "text": "repeats is the number of times this callback should be triggered (0 means endless, and it is the default option)" }, { "code": null, "e": 2990, "s": 2965, "text": "mode can have 3 values −" }, { "code": null, "e": 3063, "s": 2990, "text": "MILLIS − timer unit is milliseconds, Internal resolution in milliseconds" }, { "code": null, "e": 3136, "s": 3063, "text": "MILLIS − timer unit is milliseconds, Internal resolution in milliseconds" }, { "code": null, "e": 3219, "s": 3136, "text": "MICROS − timer unit is milliseconds, Internal resolution in microseconds (DEFAULT)" }, { "code": null, "e": 3302, "s": 3219, "text": "MICROS − timer unit is milliseconds, Internal resolution in microseconds (DEFAULT)" }, { "code": null, "e": 3382, "s": 3302, "text": "MICROS_MICROS − timer unit in microseconds, Internal resolution in microseconds" }, { "code": null, "e": 3462, "s": 3382, "text": "MICROS_MICROS − timer unit in microseconds, Internal resolution in microseconds" }, { "code": null, "e": 3580, "s": 3462, "text": "With default mode (MICROS), you can have time intervals up to 70 minutes. Use MILLIS for larger time intervals. Thus," }, { "code": null, "e": 3651, "s": 3580, "text": "timer1 callback is triggered just once, and immediately (interval = 0)" }, { "code": null, "e": 3722, "s": 3651, "text": "timer1 callback is triggered just once, and immediately (interval = 0)" }, { "code": null, "e": 3808, "s": 3722, "text": "timer2 callback is triggered every 1000 ms, with interval resolution in milliseconds." }, { "code": null, "e": 3894, "s": 3808, "text": "timer2 callback is triggered every 1000 ms, with interval resolution in milliseconds." }, { "code": null, "e": 3946, "s": 3894, "text": "timer3 callback is triggered 5 times, every second." }, { "code": null, "e": 3998, "s": 3946, "text": "timer3 callback is triggered 5 times, every second." }, { "code": null, "e": 4041, "s": 3998, "text": "timer4 callback is triggered every 500 ms." }, { "code": null, "e": 4084, "s": 4041, "text": "timer4 callback is triggered every 500 ms." }, { "code": null, "e": 4179, "s": 4084, "text": "timer5 callback is triggered every 100 microseconds, with internal resolution of microseconds." }, { "code": null, "e": 4274, "s": 4179, "text": "timer5 callback is triggered every 100 microseconds, with internal resolution of microseconds." }, { "code": null, "e": 4338, "s": 4274, "text": "Within the setup, you start the ticker objects defined earlier." }, { "code": null, "e": 4522, "s": 4338, "text": "void setup() {\n pinMode(LED_BUILTIN, OUTPUT);\n Serial.begin(9600);\n delay(2000);\n timer1.start();\n timer2.start();\n timer3.start();\n timer4.start();\n timer5.start();\n}" }, { "code": null, "e": 4660, "s": 4522, "text": "Within the loop, you constantly call .update() function, which essentially checks the ticker and runs the callback function if necessary." }, { "code": null, "e": 4883, "s": 4660, "text": "void loop() {\n timer1.update();\n timer2.update();\n timer3.update();\n timer4.update();\n timer5.update();\n if (timer4.counter() == 20) timer4.interval(200);\n if (timer4.counter() == 80) timer4.interval(1000);\n}" }, { "code": null, "e": 5348, "s": 4883, "text": "Notice that there is no delay() in the loop, and even in the setup after the timers are begun.As per the official documentation, \"If you use delay(), the Ticker will be ignored! You cannot use delay() command with the TimerObject. Instead of using delay, you can use the Ticker itself. For example, if you need that your loop run twice per second, just create a Ticker with 500 ms. It will have the same result that delay(500), but your code will be always state.\"" }, { "code": null, "e": 5480, "s": 5348, "text": "Essentially, ticker functions use the underlying timer that delay() uses. Therefore, you can't use delay along with ticker objects." }, { "code": null, "e": 5637, "s": 5480, "text": "The .counter() function returns the number of executed callbacks. Thus, we change the interval of timer4 after 20 triggers and then again after 80 triggers." }, { "code": null, "e": 5739, "s": 5637, "text": "Later, the definitions of the 5 callback functions are given, which are more or less selfexplanatory." }, { "code": null, "e": 6196, "s": 5739, "text": "void printCounter() {\n Serial.print(\"Counter \");\n Serial.println(timer2.counter());\n}\nvoid printCountdown() {\n Serial.print(\"Countdowm \");\n Serial.println(5 - timer3.counter());\n}\nvoid printMessage() {\n Serial.println(\"Hello!\");\n}\nvoid blink() {\n digitalWrite(LED_BUILTIN, ledState);\n ledState = !ledState;\n}\nvoid printCountUS() {\n counterUS++;\n if (counterUS == 10000) {\n Serial.println(\"10000 * 100us\");\n counterUS = 0;\n }\n}" }, { "code": null, "e": 6315, "s": 6196, "text": "You can use this library for performing tasks at a fixed interval, either endlessly, or for a certain number of times." } ]
.NET Core - Package References
In this chapter, we will discuss how to add packages in your .NET Core application and how to find a specific package. We can directly go to NuGet and add package, but here we will see some other places. Let us now go to the source code of .NET Core which is located here − https://github.com/dotnet/corefx In CoreFx repo, open the src folder − And you will see the whole list of folders that correspond to different packages. Let us now search Json − There is another way to find your package, you probably know various types if you are familiar with .NET Framework, but the assembling of packages in .NET Core is totally different and you won’t know where that packages in. If you know the type, you can search to reverse package search by using https://packagesearch.azurewebsites.net/ Here you can enter any type of package you would like to find. Then, this site will scan NuGet and find the relevant packages for you. Let us now search for DataContractJson. You will now see that we get the same package; let us click on the package. You will now see the NuGet page; you need to confirm that you need this package. You can add this in your application using a few methods. Let us open the project.json file. { "version": "1.0.0-*", "buildOptions": { "emitEntryPoint": true }, "dependencies": { "Microsoft.NETCore.App": { "type": "platform", "version": "1.0.1" } }, "frameworks": { "netcoreapp1.0": { "imports": "dnxcore50" } } } This is the new project format and inside this file you will see the dependencies section. Let us add a new dependency as shown below. { "version": "1.0.0-*", "buildOptions": { "emitEntryPoint": true }, "dependencies": { "Microsoft.NETCore.App": { "type": "platform", "version": "1.0.1" }, "System.Runtime.Serialization.Json": "4.0.2" }, "frameworks": { "netcoreapp1.0": { "imports": "dnxcore50" } } } Now if you look at your references, then you will see that System.Runtime.Serialization.Json package is added to your project. Another way is to go to the NuGet Manager and browse the package you want to add. Print Add Notes Bookmark this page
[ { "code": null, "e": 2590, "s": 2386, "text": "In this chapter, we will discuss how to add packages in your .NET Core application and how to find a specific package. We can directly go to NuGet and add package, but here we will see some other places." }, { "code": null, "e": 2693, "s": 2590, "text": "Let us now go to the source code of .NET Core which is located here − https://github.com/dotnet/corefx" }, { "code": null, "e": 2731, "s": 2693, "text": "In CoreFx repo, open the src folder −" }, { "code": null, "e": 2838, "s": 2731, "text": "And you will see the whole list of folders that correspond to different packages. Let us now search Json −" }, { "code": null, "e": 3062, "s": 2838, "text": "There is another way to find your package, you probably know various types if you are familiar with .NET Framework, but the assembling of packages in .NET Core is totally different and you won’t know where that packages in." }, { "code": null, "e": 3175, "s": 3062, "text": "If you know the type, you can search to reverse package search by using https://packagesearch.azurewebsites.net/" }, { "code": null, "e": 3310, "s": 3175, "text": "Here you can enter any type of package you would like to find. Then, this site will scan NuGet and find the relevant packages for you." }, { "code": null, "e": 3350, "s": 3310, "text": "Let us now search for DataContractJson." }, { "code": null, "e": 3426, "s": 3350, "text": "You will now see that we get the same package; let us click on the package." }, { "code": null, "e": 3565, "s": 3426, "text": "You will now see the NuGet page; you need to confirm that you need this package. You can add this in your application using a few methods." }, { "code": null, "e": 3600, "s": 3565, "text": "Let us open the project.json file." }, { "code": null, "e": 3916, "s": 3600, "text": "{ \n \"version\": \"1.0.0-*\", \n \"buildOptions\": { \n \"emitEntryPoint\": true \n }, \n \"dependencies\": { \n \"Microsoft.NETCore.App\": { \n \"type\": \"platform\", \n \"version\": \"1.0.1\" \n } \n }, \n \"frameworks\": { \n \"netcoreapp1.0\": { \n \"imports\": \"dnxcore50\" \n } \n } \n} " }, { "code": null, "e": 4051, "s": 3916, "text": "This is the new project format and inside this file you will see the dependencies section. Let us add a new dependency as shown below." }, { "code": null, "e": 4419, "s": 4051, "text": "{ \n \"version\": \"1.0.0-*\", \n \"buildOptions\": { \n \"emitEntryPoint\": true \n }, \n \"dependencies\": { \n \"Microsoft.NETCore.App\": { \n \"type\": \"platform\", \n \"version\": \"1.0.1\" \n }, \n \"System.Runtime.Serialization.Json\": \"4.0.2\" \n }, \n \"frameworks\": { \n \"netcoreapp1.0\": { \n \"imports\": \"dnxcore50\" \n } \n } \n}" }, { "code": null, "e": 4546, "s": 4419, "text": "Now if you look at your references, then you will see that System.Runtime.Serialization.Json package is added to your project." }, { "code": null, "e": 4628, "s": 4546, "text": "Another way is to go to the NuGet Manager and browse the package you want to add." }, { "code": null, "e": 4635, "s": 4628, "text": " Print" }, { "code": null, "e": 4646, "s": 4635, "text": " Add Notes" } ]
Ext.js - Grid
This is a simple component to display data, which is a collection of record stored in Ext.data.Store in a tabular format. Following is a simple syntax to create grid. Ext.create('Ext.grid.Panel',{ grid properties.. columns : [Columns] }); Following is a simple example showing grid. <!DOCTYPE html> <html> <head> <link href = "https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/theme-classic/resources/theme-classic-all.css" rel = "stylesheet" /> <script type = "text/javascript" src = "https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/ext-all.js"></script> <script type = "text/javascript"> // Creation of data model Ext.define('StudentDataModel', { extend: 'Ext.data.Model', fields: [ {name: 'name', mapping : 'name'}, {name: 'age', mapping : 'age'}, {name: 'marks', mapping : 'marks'} ] }); Ext.onReady(function() { // Store data var myData = [ { name : "Asha", age : "16", marks : "90" }, { name : "Vinit", age : "18", marks : "95" }, { name : "Anand", age : "20", marks : "68" }, { name : "Niharika", age : "21", marks : "86" }, { name : "Manali", age : "22", marks : "57" } ]; // Creation of first grid store var gridStore = Ext.create('Ext.data.Store', { model: 'StudentDataModel', data: myData }); // Creation of first grid Ext.create('Ext.grid.Panel', { id : 'gridId', store : gridStore, stripeRows : true, title : 'Students Grid', // Title for the grid renderTo :'gridDiv', // Div id where the grid has to be rendered width : 600, collapsible : true, // property to collapse grid enableColumnMove :true, // property which allows column to move to different position by dragging that column. enableColumnResize:true, // property which allows to resize column run time. columns : [{ header: "Student Name", dataIndex: 'name', id : 'name', flex: 1, // property defines the amount of space this column is going to take in the grid container with respect to all. sortable: true, // property to sort grid column data. hideable: true // property which allows column to be hidden run time on user request. },{ header: "Age", dataIndex: 'age', flex: .5, sortable: true, hideable: false // this column will not be available to be hidden. },{ header: "Marks", dataIndex: 'marks', flex: .5, sortable: true, // renderer is used to manipulate data based on some conditions here // who ever has marks greater than 75 will be displayed as // 'Distinction' else 'Non Distinction'. renderer : function (value, metadata, record, rowIndex, colIndex, store) { if (value > 75) { return "Distinction"; } else { return "Non Distinction"; } } }] }); }); </script> </head> <body> <div id = "gridDiv"></div> </body> </html> The above program will produce the following result − Collapsible − This property is to add a collapse feature to the grid. Add "Collapsible : true" feature in grid properties to add this feature. Sorting − This property is to add a sorting feature to the grid. Add Column property"sortable : true" in the grid to apply sorting ASC/DESC. By default, it is true. It can be made false, if you don’t want this feature to appear. columns : [{ header: "Student Name", dataIndex: 'name', id : 'name', flex: 1, sortable: true // property to sort grid column data }] By default, sorting can be applied with property sorters : {property: 'id', direction : 'ASC'} in store. It will sort grid data based on the property provided in the sorters and the direction given, before rendering data into the grid. Enable Column resize − Column can be resized (its width can be increased or decreased) using grid properties "enableColumnResize: true". Column hideable − Add Column property "hideable : true" in a grid to make the column appear or hide. By default, it is true. It can be made false, if you don’t want this feature to appear. columns : [{ header: "Student Name", dataIndex: 'name', id : 'name', flex: 1, sortable: true, hideable: true // property which allows column to be hidden run time on user request }] Draggable column − Add Column property "enableColumnMove: true" is grid property with which we can move columns in a grid. Renderer − This is the property to customize the view of grid data based on the data we get from the store. columns : [{ header: "Marks", dataIndex: 'marks', flex: .5, sortable: true, // renderer is used to manipulate data based on some conditions here who // ever has marks greater than 75 will be displayed as 'Distinction' // else 'Non Distinction'. renderer : function (value, metadata, record, rowIndex, colIndex, store) { if (value > 75) { return "Distinction"; } else { return "Non Distinction"; } } }] Note − All the properties are added in the above grid example. Try them in try it editor. Print Add Notes Bookmark this page
[ { "code": null, "e": 2145, "s": 2023, "text": "This is a simple component to display data, which is a collection of record stored in Ext.data.Store in a tabular format." }, { "code": null, "e": 2190, "s": 2145, "text": "Following is a simple syntax to create grid." }, { "code": null, "e": 2269, "s": 2190, "text": "Ext.create('Ext.grid.Panel',{\n grid properties..\n columns : [Columns]\n});\n" }, { "code": null, "e": 2313, "s": 2269, "text": "Following is a simple example showing grid." }, { "code": null, "e": 5967, "s": 2313, "text": "<!DOCTYPE html>\n<html>\n <head>\n <link href = \"https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/theme-classic/resources/theme-classic-all.css\" \n rel = \"stylesheet\" />\n <script type = \"text/javascript\" \n src = \"https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/ext-all.js\"></script>\n \n <script type = \"text/javascript\">\n // Creation of data model\n Ext.define('StudentDataModel', {\n extend: 'Ext.data.Model',\n fields: [\n {name: 'name', mapping : 'name'},\n {name: 'age', mapping : 'age'},\n {name: 'marks', mapping : 'marks'}\n ]\n });\n \n Ext.onReady(function() {\n // Store data\n var myData = [\n { name : \"Asha\", age : \"16\", marks : \"90\" },\n { name : \"Vinit\", age : \"18\", marks : \"95\" },\n { name : \"Anand\", age : \"20\", marks : \"68\" },\n { name : \"Niharika\", age : \"21\", marks : \"86\" },\n { name : \"Manali\", age : \"22\", marks : \"57\" }\n ];\n \n // Creation of first grid store\n var gridStore = Ext.create('Ext.data.Store', {\n model: 'StudentDataModel',\n data: myData\n });\n \n // Creation of first grid\n Ext.create('Ext.grid.Panel', {\n id : 'gridId',\n store : gridStore,\n stripeRows : true,\n title : 'Students Grid', // Title for the grid\n renderTo :'gridDiv', // Div id where the grid has to be rendered\n width : 600,\n collapsible : true, // property to collapse grid\n enableColumnMove :true, // property which allows column to move to different position by dragging that column.\n enableColumnResize:true, // property which allows to resize column run time.\n \n columns :\n [{ \n header: \"Student Name\",\n dataIndex: 'name',\t\n id : 'name', \n flex: 1, // property defines the amount of space this column is going to take in the grid container with respect to all.\t\n sortable: true, // property to sort grid column data. \n hideable: true // property which allows column to be hidden run time on user request.\n },{\n header: \"Age\", \n dataIndex: 'age',\n flex: .5, \n sortable: true,\n hideable: false // this column will not be available to be hidden.\n },{\n header: \"Marks\",\n dataIndex: 'marks',\n flex: .5, \n sortable: true, \n \n // renderer is used to manipulate data based on some conditions here \n // who ever has marks greater than 75 will be displayed as \n // 'Distinction' else 'Non Distinction'.\n renderer : function (value, metadata, record, rowIndex, colIndex, store) {\n if (value > 75) {\n return \"Distinction\";\t \n } else {\n return \"Non Distinction\";\n }\n }\n }]\n });\n });\n </script>\n </head>\n \n <body>\n <div id = \"gridDiv\"></div>\n </body>\n</html>" }, { "code": null, "e": 6021, "s": 5967, "text": "The above program will produce the following result −" }, { "code": null, "e": 6164, "s": 6021, "text": "Collapsible − This property is to add a collapse feature to the grid. Add \"Collapsible : true\" feature in grid properties to add this feature." }, { "code": null, "e": 6393, "s": 6164, "text": "Sorting − This property is to add a sorting feature to the grid. Add Column property\"sortable : true\" in the grid to apply sorting ASC/DESC. By default, it is true. It can be made false, if you don’t want this feature to appear." }, { "code": null, "e": 6556, "s": 6393, "text": "columns : [{ \n header: \"Student Name\",\n dataIndex: 'name',\t\n id : 'name', \n flex: 1, \t\t\t\n sortable: true // property to sort grid column data \n}]" }, { "code": null, "e": 6792, "s": 6556, "text": "By default, sorting can be applied with property sorters : {property: 'id', direction : 'ASC'} in store. It will sort grid data based on the property provided in the sorters and the direction given, before rendering data into the grid." }, { "code": null, "e": 6929, "s": 6792, "text": "Enable Column resize − Column can be resized (its width can be increased or decreased) using grid properties \"enableColumnResize: true\"." }, { "code": null, "e": 7118, "s": 6929, "text": "Column hideable − Add Column property \"hideable : true\" in a grid to make the column appear or hide. By default, it is true. It can be made false, if you don’t want this feature to appear." }, { "code": null, "e": 7333, "s": 7118, "text": "columns : [{ \n header: \"Student Name\",\n dataIndex: 'name',\t\n id : 'name', \n flex: 1, \t\t\t\n sortable: true, \n hideable: true // property which allows column to be hidden run time on user request\n}]" }, { "code": null, "e": 7456, "s": 7333, "text": "Draggable column − Add Column property \"enableColumnMove: true\" is grid property with which we can move columns in a grid." }, { "code": null, "e": 7564, "s": 7456, "text": "Renderer − This is the property to customize the view of grid data based on the data we get from the store." }, { "code": null, "e": 8039, "s": 7564, "text": "columns : [{\n header: \"Marks\",\n dataIndex: 'marks',\n flex: .5, \n sortable: true, \n \n // renderer is used to manipulate data based on some conditions here who\n // ever has marks greater than 75 will be displayed as 'Distinction'\n // else 'Non Distinction'.\n renderer : function (value, metadata, record, rowIndex, colIndex, store) {\n if (value > 75) {\n return \"Distinction\";\t \n } else {\n return \"Non Distinction\";\n }\n }\n}]" }, { "code": null, "e": 8129, "s": 8039, "text": "Note − All the properties are added in the above grid example. Try them in try it editor." }, { "code": null, "e": 8136, "s": 8129, "text": " Print" }, { "code": null, "e": 8147, "s": 8136, "text": " Add Notes" } ]
Data Structures | Linked List | Question 17 - GeeksforGeeks
28 Jun, 2021 Consider the following function to traverse a linked list. void traverse(struct Node *head){ while (head->next != NULL) { printf("%d ", head->data); head = head->next; }} Which of the following is FALSE about above function?(A) The function may crash when the linked list is empty(B) The function doesn’t print the last node when the linked list is not empty(C) The function is implemented incorrectly because it changes headAnswer: (C)Explanation:Quiz of this Question Data Structures Data Structures-Linked List Linked Lists Data Structures Data Structures Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Advantages and Disadvantages of Linked List Introduction to Data Structures | 10 most commonly used Data Structures FIFO vs LIFO approach in Programming Multilevel Linked List Data Structures | Array | Question 2 Advantages of vector over array in C++ Difference between data type and data structure Bit manipulation | Swap Endianness of a number Program to create Custom Vector Class in C++ Data Structures | Queue | Question 1
[ { "code": null, "e": 24830, "s": 24802, "text": "\n28 Jun, 2021" }, { "code": null, "e": 24889, "s": 24830, "text": "Consider the following function to traverse a linked list." }, { "code": "void traverse(struct Node *head){ while (head->next != NULL) { printf(\"%d \", head->data); head = head->next; }}", "e": 25020, "s": 24889, "text": null }, { "code": null, "e": 25319, "s": 25020, "text": "Which of the following is FALSE about above function?(A) The function may crash when the linked list is empty(B) The function doesn’t print the last node when the linked list is not empty(C) The function is implemented incorrectly because it changes headAnswer: (C)Explanation:Quiz of this Question" }, { "code": null, "e": 25335, "s": 25319, "text": "Data Structures" }, { "code": null, "e": 25363, "s": 25335, "text": "Data Structures-Linked List" }, { "code": null, "e": 25376, "s": 25363, "text": "Linked Lists" }, { "code": null, "e": 25392, "s": 25376, "text": "Data Structures" }, { "code": null, "e": 25408, "s": 25392, "text": "Data Structures" }, { "code": null, "e": 25506, "s": 25408, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25515, "s": 25506, "text": "Comments" }, { "code": null, "e": 25528, "s": 25515, "text": "Old Comments" }, { "code": null, "e": 25572, "s": 25528, "text": "Advantages and Disadvantages of Linked List" }, { "code": null, "e": 25644, "s": 25572, "text": "Introduction to Data Structures | 10 most commonly used Data Structures" }, { "code": null, "e": 25681, "s": 25644, "text": "FIFO vs LIFO approach in Programming" }, { "code": null, "e": 25704, "s": 25681, "text": "Multilevel Linked List" }, { "code": null, "e": 25741, "s": 25704, "text": "Data Structures | Array | Question 2" }, { "code": null, "e": 25780, "s": 25741, "text": "Advantages of vector over array in C++" }, { "code": null, "e": 25828, "s": 25780, "text": "Difference between data type and data structure" }, { "code": null, "e": 25875, "s": 25828, "text": "Bit manipulation | Swap Endianness of a number" }, { "code": null, "e": 25920, "s": 25875, "text": "Program to create Custom Vector Class in C++" } ]
Dart Programming - Symbol
Symbols in Dart are opaque, dynamic string name used in reflecting out metadata from a library. Simply put, symbols are a way to store the relationship between a human readable string and a string that is optimized to be used by computers. Reflection is a mechanism to get metadata of a type at runtime like the number of methods in a class, the number of constructors it has or the number of parameters in a function. You can even invoke a method of the type which is loaded at runtime. In Dart reflection specific classes are available in the dart:mirrors package. This library works in both web applications and command line applications. Symbol obj = new Symbol('name'); // expects a name of class or function or library to reflect The name must be a valid public Dart member name, public constructor name, or library name. Consider the following example. The code declares a class Foo in a library foo_lib. The class defines the methods m1, m2, and m3. library foo_lib; // libarary name can be a symbol class Foo { // class name can be a symbol m1() { // method name can be a symbol print("Inside m1"); } m2() { print("Inside m2"); } m3() { print("Inside m3"); } } The following code loads Foo.dart library and searches for Foo class, with help of Symbol type. Since we are reflecting the metadata from the above library the code imports dart:mirrors library. import 'dart:core'; import 'dart:mirrors'; import 'Foo.dart'; main() { Symbol lib = new Symbol("foo_lib"); //library name stored as Symbol Symbol clsToSearch = new Symbol("Foo"); // class name stored as Symbol if(checkIf_classAvailableInlibrary(lib, clsToSearch)) // searches Foo class in foo_lib library print("class found.."); } bool checkIf_classAvailableInlibrary(Symbol libraryName, Symbol className) { MirrorSystem mirrorSystem = currentMirrorSystem(); LibraryMirror libMirror = mirrorSystem.findLibrary(libraryName); if (libMirror != null) { print("Found Library"); print("checkng...class details.."); print("No of classes found is : ${libMirror.declarations.length}"); libMirror.declarations.forEach((s, d) => print(s)); if (libMirror.declarations.containsKey(className)) return true; return false; } } Note that the line libMirror.declarations.forEach((s, d) => print(s)); will iterate across every declaration in the library at runtime and prints the declarations as type of Symbol. This code should produce the following output − Found Library checkng...class details.. No of classes found is : 1 Symbol("Foo") // class name displayed as symbol class found. Let us now consider displaying the number of instance methods in a class. The predefined class ClassMirror helps us to achieve the same. import 'dart:core'; import 'dart:mirrors'; import 'Foo.dart'; main() { Symbol lib = new Symbol("foo_lib"); Symbol clsToSearch = new Symbol("Foo"); reflect_InstanceMethods(lib, clsToSearch); } void reflect_InstanceMethods(Symbol libraryName, Symbol className) { MirrorSystem mirrorSystem = currentMirrorSystem(); LibraryMirror libMirror = mirrorSystem.findLibrary(libraryName); if (libMirror != null) { print("Found Library"); print("checkng...class details.."); print("No of classes found is : ${libMirror.declarations.length}"); libMirror.declarations.forEach((s, d) => print(s)); if (libMirror.declarations.containsKey(className)) print("found class"); ClassMirror classMirror = libMirror.declarations[className]; print("No of instance methods found is ${classMirror.instanceMembers.length}"); classMirror.instanceMembers.forEach((s, v) => print(s)); } } This code should produce the following output − Found Library checkng...class details.. No of classes found is : 1 Symbol("Foo") found class No of instance methods found is 8 Symbol("==") Symbol("hashCode") Symbol("toString") Symbol("noSuchMethod") Symbol("runtimeType") Symbol("m1") Symbol("m2") Symbol("m3") You can convert the name of a type like class or library stored in a symbol back to string using MirrorSystem class. The following code shows how you can convert a symbol to a string. import 'dart:mirrors'; void main(){ Symbol lib = new Symbol("foo_lib"); String name_of_lib = MirrorSystem.getName(lib); print(lib); print(name_of_lib); } It should produce the following output − Symbol("foo_lib") foo_lib 44 Lectures 4.5 hours Sriyank Siddhartha 34 Lectures 4 hours Sriyank Siddhartha 69 Lectures 4 hours Frahaan Hussain 117 Lectures 10 hours Frahaan Hussain 22 Lectures 1.5 hours Pranjal Srivastava 34 Lectures 3 hours Pranjal Srivastava Print Add Notes Bookmark this page
[ { "code": null, "e": 2765, "s": 2525, "text": "Symbols in Dart are opaque, dynamic string name used in reflecting out metadata from a library. Simply put, symbols are a way to store the relationship between a human readable string and a string that is optimized to be used by computers." }, { "code": null, "e": 3013, "s": 2765, "text": "Reflection is a mechanism to get metadata of a type at runtime like the number of methods in a class, the number of constructors it has or the number of parameters in a function. You can even invoke a method of the type which is loaded at runtime." }, { "code": null, "e": 3167, "s": 3013, "text": "In Dart reflection specific classes are available in the dart:mirrors package. This library works in both web applications and command line applications." }, { "code": null, "e": 3265, "s": 3167, "text": "Symbol obj = new Symbol('name'); \n// expects a name of class or function or library to reflect \n" }, { "code": null, "e": 3357, "s": 3265, "text": "The name must be a valid public Dart member name, public constructor name, or library name." }, { "code": null, "e": 3487, "s": 3357, "text": "Consider the following example. The code declares a class Foo in a library foo_lib. The class defines the methods m1, m2, and m3." }, { "code": null, "e": 3779, "s": 3487, "text": "library foo_lib; \n// libarary name can be a symbol \n\nclass Foo { \n // class name can be a symbol \n m1() { \n // method name can be a symbol \n print(\"Inside m1\"); \n } \n m2() { \n print(\"Inside m2\"); \n } \n m3() { \n print(\"Inside m3\"); \n } \n}" }, { "code": null, "e": 3974, "s": 3779, "text": "The following code loads Foo.dart library and searches for Foo class, with help of Symbol type. Since we are reflecting the metadata from the above library the code imports dart:mirrors library." }, { "code": null, "e": 4918, "s": 3974, "text": "import 'dart:core'; \nimport 'dart:mirrors'; \nimport 'Foo.dart'; \n\nmain() { \n Symbol lib = new Symbol(\"foo_lib\"); \n //library name stored as Symbol \n \n Symbol clsToSearch = new Symbol(\"Foo\"); \n // class name stored as Symbol \n \n if(checkIf_classAvailableInlibrary(lib, clsToSearch)) \n // searches Foo class in foo_lib library \n print(\"class found..\"); \n} \n \nbool checkIf_classAvailableInlibrary(Symbol libraryName, Symbol className) { \n MirrorSystem mirrorSystem = currentMirrorSystem(); \n LibraryMirror libMirror = mirrorSystem.findLibrary(libraryName); \n \n if (libMirror != null) { \n print(\"Found Library\"); \n print(\"checkng...class details..\"); \n print(\"No of classes found is : ${libMirror.declarations.length}\"); \n libMirror.declarations.forEach((s, d) => print(s)); \n \n if (libMirror.declarations.containsKey(className)) return true; \n return false; \n } \n}" }, { "code": null, "e": 5100, "s": 4918, "text": "Note that the line libMirror.declarations.forEach((s, d) => print(s)); will iterate across every declaration in the library at runtime and prints the declarations as type of Symbol." }, { "code": null, "e": 5148, "s": 5100, "text": "This code should produce the following output −" }, { "code": null, "e": 5283, "s": 5148, "text": "Found Library \ncheckng...class details.. \nNo of classes found is : 1 \nSymbol(\"Foo\") // class name displayed as symbol \nclass found. \n" }, { "code": null, "e": 5420, "s": 5283, "text": "Let us now consider displaying the number of instance methods in a class. The predefined class ClassMirror helps us to achieve the same." }, { "code": null, "e": 6392, "s": 5420, "text": "import 'dart:core'; \nimport 'dart:mirrors'; \nimport 'Foo.dart'; \n\nmain() { \n Symbol lib = new Symbol(\"foo_lib\"); \n Symbol clsToSearch = new Symbol(\"Foo\"); \n reflect_InstanceMethods(lib, clsToSearch); \n} \nvoid reflect_InstanceMethods(Symbol libraryName, Symbol className) { \n MirrorSystem mirrorSystem = currentMirrorSystem(); \n LibraryMirror libMirror = mirrorSystem.findLibrary(libraryName); \n \n if (libMirror != null) { \n print(\"Found Library\"); \n print(\"checkng...class details..\"); \n print(\"No of classes found is : ${libMirror.declarations.length}\"); \n libMirror.declarations.forEach((s, d) => print(s)); \n \n if (libMirror.declarations.containsKey(className)) print(\"found class\");\n ClassMirror classMirror = libMirror.declarations[className]; \n \n print(\"No of instance methods found is ${classMirror.instanceMembers.length}\");\n classMirror.instanceMembers.forEach((s, v) => print(s)); \n } \n} " }, { "code": null, "e": 6440, "s": 6392, "text": "This code should produce the following output −" }, { "code": null, "e": 6716, "s": 6440, "text": "Found Library \ncheckng...class details.. \nNo of classes found is : 1 \nSymbol(\"Foo\") \nfound class \nNo of instance methods found is 8 \nSymbol(\"==\") \nSymbol(\"hashCode\") \nSymbol(\"toString\") \nSymbol(\"noSuchMethod\") \nSymbol(\"runtimeType\") \nSymbol(\"m1\") \nSymbol(\"m2\") \nSymbol(\"m3\")\n" }, { "code": null, "e": 6900, "s": 6716, "text": "You can convert the name of a type like class or library stored in a symbol back to string using MirrorSystem class. The following code shows how you can convert a symbol to a string." }, { "code": null, "e": 7076, "s": 6900, "text": "import 'dart:mirrors'; \nvoid main(){ \n Symbol lib = new Symbol(\"foo_lib\"); \n String name_of_lib = MirrorSystem.getName(lib); \n \n print(lib); \n print(name_of_lib); \n}" }, { "code": null, "e": 7117, "s": 7076, "text": "It should produce the following output −" }, { "code": null, "e": 7153, "s": 7117, "text": "Symbol(\"foo_lib\") \n\nfoo_lib \n" }, { "code": null, "e": 7188, "s": 7153, "text": "\n 44 Lectures \n 4.5 hours \n" }, { "code": null, "e": 7208, "s": 7188, "text": " Sriyank Siddhartha" }, { "code": null, "e": 7241, "s": 7208, "text": "\n 34 Lectures \n 4 hours \n" }, { "code": null, "e": 7261, "s": 7241, "text": " Sriyank Siddhartha" }, { "code": null, "e": 7294, "s": 7261, "text": "\n 69 Lectures \n 4 hours \n" }, { "code": null, "e": 7311, "s": 7294, "text": " Frahaan Hussain" }, { "code": null, "e": 7346, "s": 7311, "text": "\n 117 Lectures \n 10 hours \n" }, { "code": null, "e": 7363, "s": 7346, "text": " Frahaan Hussain" }, { "code": null, "e": 7398, "s": 7363, "text": "\n 22 Lectures \n 1.5 hours \n" }, { "code": null, "e": 7418, "s": 7398, "text": " Pranjal Srivastava" }, { "code": null, "e": 7451, "s": 7418, "text": "\n 34 Lectures \n 3 hours \n" }, { "code": null, "e": 7471, "s": 7451, "text": " Pranjal Srivastava" }, { "code": null, "e": 7478, "s": 7471, "text": " Print" }, { "code": null, "e": 7489, "s": 7478, "text": " Add Notes" } ]
Count of pairs violating BST property - GeeksforGeeks
08 Jul, 2021 Given a Binary tree and number of nodes in the tree, the task is to find the number of pairs violating the BST property. Binary Search Tree is a node-based binary tree data structure which has the following properties: The left subtree of a node contains only nodes with keys lesser than the node’s key. The right subtree of a node contains only nodes with keys greater than the node’s key. The left and right subtree each must also be a binary search tree. Examples: Input: 4 / \ 5 6 Output: 1 For the above binary tree, pair (5, 4) violate the BST property. Thus, count of pairs violating BST property is 1. Input: 50 / \ 30 60 / \ / \ 20 25 10 40 Output: 7 For the above binary tree, pairs (20, 10), (25, 10), (30, 25), (30, 10), (50, 10), (50, 40), (60, 40) violate the BST property. Thus, count of pairs violating BST property is 7. Approach: Store the inorder traversal of the binary tree in an array. Now count all the pairs such that a[i] > a[j] for i < j which is number of inversions in the array. Print the count of pairs violating BST property. Below is the implementation of the above approach: Java Python3 C# Javascript // Java program to count number of pairs// in a binary tree violating the BST propertyimport java.io.*;import java.util.*; // Class that represents a node of the treeclass Node { int data; Node left, right; // Constructor to create a new tree node Node(int key) { data = key; left = right = null; }} class GFG { // This method sorts the input array and returns the // number of inversions in the array static int mergeSort(int arr[], int array_size) { int temp[] = new int[array_size]; return _mergeSort(arr, temp, 0, array_size - 1); } // An auxiliary recursive method that sorts // the input array and returns the number of // inversions in the array static int _mergeSort(int arr[], int temp[], int left, int right) { int mid, inv_count = 0; if (right > left) { // Divide the array into two parts and // call _mergeSortAndCountInv() for each // of the parts mid = (right + left) / 2; // Inversion count will be sum of inversions // in left-part, right-part and number of // inversions in merging inv_count = _mergeSort(arr, temp, left, mid); inv_count += _mergeSort(arr, temp, mid + 1, right); // Merge the two parts inv_count += merge(arr, temp, left, mid + 1, right); } return inv_count; } // This method merges two sorted arrays and returns // inversion count in the arrays static int merge(int arr[], int temp[], int left, int mid, int right) { int i, j, k; int inv_count = 0; // i is index for left subarray i = left; // j is index for right subarray j = mid; // k is index for resultant merged subarray k = left; while ((i <= mid - 1) && (j <= right)) { if (arr[i] <= arr[j]) { temp[k++] = arr[i++]; } else { temp[k++] = arr[j++]; inv_count = inv_count + (mid - i); } } // Copy the remaining elements of left subarray // (if there are any) to temp while (i <= mid - 1) temp[k++] = arr[i++]; // Copy the remaining elements of right subarray // if there are any) to temp while (j <= right) temp[k++] = arr[j++]; // Copy back the merged elements to original array for (i = left; i <= right; i++) arr[i] = temp[i]; return inv_count; } // Array to store // inorder traversal of the binary tree static int[] a; static int in; // Inorder traversal of the binary tree static void Inorder(Node node) { if (node == null) return; Inorder(node.left); a[in++] = node.data; Inorder(node.right); } // Function to count the pairs // in a binary tree violating BST property static int pairsViolatingBST(Node root, int N) { if (root == null) return 0; in = 0; a = new int[N]; Inorder(root); // Total inversions in the array int inversionCount = mergeSort(a, N); return inversionCount; } // Driver code public static void main(String args[]) { int N = 7; Node root = new Node(50); root.left = new Node(30); root.right = new Node(60); root.left.left = new Node(20); root.left.right = new Node(25); root.right.left = new Node(10); root.right.right = new Node(40); System.out.println(pairsViolatingBST(root, N)); }} # Python3 program to count number of pairs# in a binary tree violating the BST property # Class that represents a node of the treeclass newNode: def __init__(self, key): self.data = key self.left = None self.right = None # Array to store# inorder traversal of the binary treea = []id = 0 # This method sorts the input array# and returns the number of inversions# in the arraydef mergeSort(array_size): temp = [0] * array_size return _mergeSort(temp, 0, array_size - 1) # An auxiliary recursive method that sorts# the input array and returns the number of# inversions in the arraydef _mergeSort(temp, left, right): inv_count = 0 if (right > left): # Divide the array into two parts and # call _mergeSortAndCountInv() for each # of the parts mid = (right + left) // 2 # Inversion count will be sum of inversions # in left-part, right-part and number of # inversions in merging inv_count = _mergeSort(temp, left, mid) inv_count += _mergeSort(temp, mid + 1, right) # Merge the two parts inv_count += merge(temp, left, mid + 1, right) return inv_count # This method merges two sorted arrays# and returns inversion count in the arraysdef merge(temp, left, mid, right): global a inv_count = 0 # i is index for left subarray i = left # j is index for right subarray j = mid # k is index for resultant merged subarray k = left while ((i <= mid - 1) and (j <= right)): if (a[i] <= a[j]): temp[k] = a[i] k += 1 i += 1 else: temp[k] = a[j] k += 1 j += 1 inv_count = inv_count + (mid - i) # Copy the remaining elements of left # subarray (if there are any) to temp while (i <= mid - 1): temp[k] = a[i] k += 1 i += 1 # Copy the remaining elements of right # subarray if there are any) to temp while (j <= right): temp[k] = a[j] k += 1 j += 1 # Copy back the merged elements # to original array for i in range(left, right + 1, 1): a[i] = temp[i] return inv_count # Inorder traversal of the binary treedef Inorder(node): global a global id if (node == None): return Inorder(node.left) a.append(node.data) id += 1 Inorder(node.right) # Function to count the pairs# in a binary tree violating# BST propertydef pairsViolatingBST(root, N): if (root == None): return 0 Inorder(root) # Total inversions in the array inversionCount = mergeSort(N) return inversionCount # Driver codeif __name__ == '__main__': N = 7 root = newNode(50) root.left = newNode(30) root.right = newNode(60) root.left.left = newNode(20) root.left.right = newNode(25) root.right.left = newNode(10) root.right.right = newNode(40) print(pairsViolatingBST(root, N)) # This code is contributed by bgangwar59 // C# program to count number of pairs// in a binary tree violating the BST propertyusing System; // Class that represents a node of the treepublic class Node { public int data; public Node left, right; // Constructor to create a new tree node public Node(int key) { data = key; left = right = null; }} class GFG { // This method sorts the input array and returns the // number of inversions in the array static int mergeSort(int[] arr, int array_size) { int[] temp = new int[array_size]; return _mergeSort(arr, temp, 0, array_size - 1); } // An auxiliary recursive method that sorts // the input array and returns the number of // inversions in the array static int _mergeSort(int[] arr, int[] temp, int left, int right) { int mid, inv_count = 0; if (right > left) { // Divide the array into two parts and // call _mergeSortAndCountInv() for each // of the parts mid = (right + left) / 2; // Inversion count will be sum of inversions // in left-part, right-part and number of // inversions in merging inv_count = _mergeSort(arr, temp, left, mid); inv_count += _mergeSort(arr, temp, mid + 1, right); // Merge the two parts inv_count += merge(arr, temp, left, mid + 1, right); } return inv_count; } // This method merges two sorted arrays and returns // inversion count in the arrays static int merge(int[] arr, int[] temp, int left, int mid, int right) { int i, j, k; int inv_count = 0; // i is index for left subarray i = left; // j is index for right subarray j = mid; // k is index for resultant merged subarray k = left; while ((i <= mid - 1) && (j <= right)) { if (arr[i] <= arr[j]) { temp[k++] = arr[i++]; } else { temp[k++] = arr[j++]; inv_count = inv_count + (mid - i); } } // Copy the remaining elements of left subarray // (if there are any) to temp while (i <= mid - 1) temp[k++] = arr[i++]; // Copy the remaining elements of right subarray // if there are any) to temp while (j <= right) temp[k++] = arr[j++]; // Copy back the merged elements to original array for (i = left; i <= right; i++) arr[i] = temp[i]; return inv_count; } // Array to store // inorder traversal of the binary tree static int[] a; static int i; // Inorder traversal of the binary tree static void Inorder(Node node) { if (node == null) return; Inorder(node.left); a[i++] = node.data; Inorder(node.right); } // Function to count the pairs // in a binary tree violating BST property static int pairsViolatingBST(Node root, int N) { if (root == null) return 0; i = 0; a = new int[N]; Inorder(root); // Total inversions in the array int inversionCount = mergeSort(a, N); return inversionCount; } // Driver code public static void Main(String[] args) { int N = 7; Node root = new Node(50); root.left = new Node(30); root.right = new Node(60); root.left.left = new Node(20); root.left.right = new Node(25); root.right.left = new Node(10); root.right.right = new Node(40); Console.WriteLine(pairsViolatingBST(root, N)); }} // This code is contributed by Rajput-Ji <script> // JavaScript program to count number of pairs // in a binary tree violating the BST property // Class that represents a node of the tree class Node { // Constructor to create a new tree node constructor(key) { this.data = key; this.left = null; this.right = null; } } // This method sorts the input array and returns the // number of inversions in the array function mergeSort(arr, array_size) { var temp = new Array(array_size).fill(0); return _mergeSort(arr, temp, 0, array_size - 1); } // An auxiliary recursive method that sorts // the input array and returns the number of // inversions in the array function _mergeSort(arr, temp, left, right) { var mid, inv_count = 0; if (right > left) { // Divide the array into two parts and // call _mergeSortAndCountInv() for each // of the parts mid = parseInt((right + left) / 2); // Inversion count will be sum of inversions // in left-part, right-part and number of // inversions in merging inv_count = _mergeSort(arr, temp, left, mid); inv_count += _mergeSort(arr, temp, mid + 1, right); // Merge the two parts inv_count += merge(arr, temp, left, mid + 1, right); } return inv_count; } // This method merges two sorted arrays and returns // inversion count in the arrays function merge(arr, temp, left, mid, right) { var i, j, k; var inv_count = 0; // i is index for left subarray i = left; // j is index for right subarray j = mid; // k is index for resultant merged subarray k = left; while (i <= mid - 1 && j <= right) { if (arr[i] <= arr[j]) { temp[k++] = arr[i++]; } else { temp[k++] = arr[j++]; inv_count = inv_count + (mid - i); } } // Copy the remaining elements of left subarray // (if there are any) to temp while (i <= mid - 1) temp[k++] = arr[i++]; // Copy the remaining elements of right subarray // if there are any) to temp while (j <= right) temp[k++] = arr[j++]; // Copy back the merged elements to original array for (i = left; i <= right; i++) arr[i] = temp[i]; return inv_count; } // Array to store // inorder traversal of the binary tree var a = []; var i; // Inorder traversal of the binary tree function Inorder(node) { if (node == null) return; Inorder(node.left); a[i++] = node.data; Inorder(node.right); } // Function to count the pairs // in a binary tree violating BST property function pairsViolatingBST(root, N) { if (root == null) return 0; i = 0; a = new Array(N).fill(0); Inorder(root); // Total inversions in the array var inversionCount = mergeSort(a, N); return inversionCount; } // Driver code var N = 7; var root = new Node(50); root.left = new Node(30); root.right = new Node(60); root.left.left = new Node(20); root.left.right = new Node(25); root.right.left = new Node(10); root.right.right = new Node(40); document.write(pairsViolatingBST(root, N) + "<br>"); // This code is contributed by rdtank. </script> 7 Rajput-Ji bgangwar59 rdtank Binary Tree inversion Binary Search Tree Technical Scripter Binary Search Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Print BST keys in the given range Find the node with maximum value in a Binary Search Tree set vs unordered_set in C++ STL Floor and Ceil from a BST Construct BST from given preorder traversal | Set 2 Threaded Binary Tree | Insertion Red Black Tree vs AVL Tree Construct a Binary Search Tree from given postorder How to check if a given array represents a Binary Heap? Find the largest BST subtree in a given Binary Tree | Set 1
[ { "code": null, "e": 25226, "s": 25198, "text": "\n08 Jul, 2021" }, { "code": null, "e": 25446, "s": 25226, "text": "Given a Binary tree and number of nodes in the tree, the task is to find the number of pairs violating the BST property. Binary Search Tree is a node-based binary tree data structure which has the following properties: " }, { "code": null, "e": 25531, "s": 25446, "text": "The left subtree of a node contains only nodes with keys lesser than the node’s key." }, { "code": null, "e": 25618, "s": 25531, "text": "The right subtree of a node contains only nodes with keys greater than the node’s key." }, { "code": null, "e": 25685, "s": 25618, "text": "The left and right subtree each must also be a binary search tree." }, { "code": null, "e": 25696, "s": 25685, "text": "Examples: " }, { "code": null, "e": 26160, "s": 25696, "text": "Input: \n 4\n / \\\n 5 6\nOutput: 1\nFor the above binary tree, pair (5, 4) \nviolate the BST property. Thus, count\nof pairs violating BST property is 1.\n\nInput:\n 50\n / \\\n 30 60\n / \\ / \\\n 20 25 10 40\nOutput: 7\nFor the above binary tree, pairs (20, 10),\n(25, 10), (30, 25), (30, 10), (50, 10), \n(50, 40), (60, 40) violate the BST property. \nThus, count of pairs violating BST property \nis 7." }, { "code": null, "e": 26171, "s": 26160, "text": "Approach: " }, { "code": null, "e": 26231, "s": 26171, "text": "Store the inorder traversal of the binary tree in an array." }, { "code": null, "e": 26331, "s": 26231, "text": "Now count all the pairs such that a[i] > a[j] for i < j which is number of inversions in the array." }, { "code": null, "e": 26380, "s": 26331, "text": "Print the count of pairs violating BST property." }, { "code": null, "e": 26432, "s": 26380, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 26437, "s": 26432, "text": "Java" }, { "code": null, "e": 26445, "s": 26437, "text": "Python3" }, { "code": null, "e": 26448, "s": 26445, "text": "C#" }, { "code": null, "e": 26459, "s": 26448, "text": "Javascript" }, { "code": "// Java program to count number of pairs// in a binary tree violating the BST propertyimport java.io.*;import java.util.*; // Class that represents a node of the treeclass Node { int data; Node left, right; // Constructor to create a new tree node Node(int key) { data = key; left = right = null; }} class GFG { // This method sorts the input array and returns the // number of inversions in the array static int mergeSort(int arr[], int array_size) { int temp[] = new int[array_size]; return _mergeSort(arr, temp, 0, array_size - 1); } // An auxiliary recursive method that sorts // the input array and returns the number of // inversions in the array static int _mergeSort(int arr[], int temp[], int left, int right) { int mid, inv_count = 0; if (right > left) { // Divide the array into two parts and // call _mergeSortAndCountInv() for each // of the parts mid = (right + left) / 2; // Inversion count will be sum of inversions // in left-part, right-part and number of // inversions in merging inv_count = _mergeSort(arr, temp, left, mid); inv_count += _mergeSort(arr, temp, mid + 1, right); // Merge the two parts inv_count += merge(arr, temp, left, mid + 1, right); } return inv_count; } // This method merges two sorted arrays and returns // inversion count in the arrays static int merge(int arr[], int temp[], int left, int mid, int right) { int i, j, k; int inv_count = 0; // i is index for left subarray i = left; // j is index for right subarray j = mid; // k is index for resultant merged subarray k = left; while ((i <= mid - 1) && (j <= right)) { if (arr[i] <= arr[j]) { temp[k++] = arr[i++]; } else { temp[k++] = arr[j++]; inv_count = inv_count + (mid - i); } } // Copy the remaining elements of left subarray // (if there are any) to temp while (i <= mid - 1) temp[k++] = arr[i++]; // Copy the remaining elements of right subarray // if there are any) to temp while (j <= right) temp[k++] = arr[j++]; // Copy back the merged elements to original array for (i = left; i <= right; i++) arr[i] = temp[i]; return inv_count; } // Array to store // inorder traversal of the binary tree static int[] a; static int in; // Inorder traversal of the binary tree static void Inorder(Node node) { if (node == null) return; Inorder(node.left); a[in++] = node.data; Inorder(node.right); } // Function to count the pairs // in a binary tree violating BST property static int pairsViolatingBST(Node root, int N) { if (root == null) return 0; in = 0; a = new int[N]; Inorder(root); // Total inversions in the array int inversionCount = mergeSort(a, N); return inversionCount; } // Driver code public static void main(String args[]) { int N = 7; Node root = new Node(50); root.left = new Node(30); root.right = new Node(60); root.left.left = new Node(20); root.left.right = new Node(25); root.right.left = new Node(10); root.right.right = new Node(40); System.out.println(pairsViolatingBST(root, N)); }}", "e": 30142, "s": 26459, "text": null }, { "code": "# Python3 program to count number of pairs# in a binary tree violating the BST property # Class that represents a node of the treeclass newNode: def __init__(self, key): self.data = key self.left = None self.right = None # Array to store# inorder traversal of the binary treea = []id = 0 # This method sorts the input array# and returns the number of inversions# in the arraydef mergeSort(array_size): temp = [0] * array_size return _mergeSort(temp, 0, array_size - 1) # An auxiliary recursive method that sorts# the input array and returns the number of# inversions in the arraydef _mergeSort(temp, left, right): inv_count = 0 if (right > left): # Divide the array into two parts and # call _mergeSortAndCountInv() for each # of the parts mid = (right + left) // 2 # Inversion count will be sum of inversions # in left-part, right-part and number of # inversions in merging inv_count = _mergeSort(temp, left, mid) inv_count += _mergeSort(temp, mid + 1, right) # Merge the two parts inv_count += merge(temp, left, mid + 1, right) return inv_count # This method merges two sorted arrays# and returns inversion count in the arraysdef merge(temp, left, mid, right): global a inv_count = 0 # i is index for left subarray i = left # j is index for right subarray j = mid # k is index for resultant merged subarray k = left while ((i <= mid - 1) and (j <= right)): if (a[i] <= a[j]): temp[k] = a[i] k += 1 i += 1 else: temp[k] = a[j] k += 1 j += 1 inv_count = inv_count + (mid - i) # Copy the remaining elements of left # subarray (if there are any) to temp while (i <= mid - 1): temp[k] = a[i] k += 1 i += 1 # Copy the remaining elements of right # subarray if there are any) to temp while (j <= right): temp[k] = a[j] k += 1 j += 1 # Copy back the merged elements # to original array for i in range(left, right + 1, 1): a[i] = temp[i] return inv_count # Inorder traversal of the binary treedef Inorder(node): global a global id if (node == None): return Inorder(node.left) a.append(node.data) id += 1 Inorder(node.right) # Function to count the pairs# in a binary tree violating# BST propertydef pairsViolatingBST(root, N): if (root == None): return 0 Inorder(root) # Total inversions in the array inversionCount = mergeSort(N) return inversionCount # Driver codeif __name__ == '__main__': N = 7 root = newNode(50) root.left = newNode(30) root.right = newNode(60) root.left.left = newNode(20) root.left.right = newNode(25) root.right.left = newNode(10) root.right.right = newNode(40) print(pairsViolatingBST(root, N)) # This code is contributed by bgangwar59", "e": 33274, "s": 30142, "text": null }, { "code": "// C# program to count number of pairs// in a binary tree violating the BST propertyusing System; // Class that represents a node of the treepublic class Node { public int data; public Node left, right; // Constructor to create a new tree node public Node(int key) { data = key; left = right = null; }} class GFG { // This method sorts the input array and returns the // number of inversions in the array static int mergeSort(int[] arr, int array_size) { int[] temp = new int[array_size]; return _mergeSort(arr, temp, 0, array_size - 1); } // An auxiliary recursive method that sorts // the input array and returns the number of // inversions in the array static int _mergeSort(int[] arr, int[] temp, int left, int right) { int mid, inv_count = 0; if (right > left) { // Divide the array into two parts and // call _mergeSortAndCountInv() for each // of the parts mid = (right + left) / 2; // Inversion count will be sum of inversions // in left-part, right-part and number of // inversions in merging inv_count = _mergeSort(arr, temp, left, mid); inv_count += _mergeSort(arr, temp, mid + 1, right); // Merge the two parts inv_count += merge(arr, temp, left, mid + 1, right); } return inv_count; } // This method merges two sorted arrays and returns // inversion count in the arrays static int merge(int[] arr, int[] temp, int left, int mid, int right) { int i, j, k; int inv_count = 0; // i is index for left subarray i = left; // j is index for right subarray j = mid; // k is index for resultant merged subarray k = left; while ((i <= mid - 1) && (j <= right)) { if (arr[i] <= arr[j]) { temp[k++] = arr[i++]; } else { temp[k++] = arr[j++]; inv_count = inv_count + (mid - i); } } // Copy the remaining elements of left subarray // (if there are any) to temp while (i <= mid - 1) temp[k++] = arr[i++]; // Copy the remaining elements of right subarray // if there are any) to temp while (j <= right) temp[k++] = arr[j++]; // Copy back the merged elements to original array for (i = left; i <= right; i++) arr[i] = temp[i]; return inv_count; } // Array to store // inorder traversal of the binary tree static int[] a; static int i; // Inorder traversal of the binary tree static void Inorder(Node node) { if (node == null) return; Inorder(node.left); a[i++] = node.data; Inorder(node.right); } // Function to count the pairs // in a binary tree violating BST property static int pairsViolatingBST(Node root, int N) { if (root == null) return 0; i = 0; a = new int[N]; Inorder(root); // Total inversions in the array int inversionCount = mergeSort(a, N); return inversionCount; } // Driver code public static void Main(String[] args) { int N = 7; Node root = new Node(50); root.left = new Node(30); root.right = new Node(60); root.left.left = new Node(20); root.left.right = new Node(25); root.right.left = new Node(10); root.right.right = new Node(40); Console.WriteLine(pairsViolatingBST(root, N)); }} // This code is contributed by Rajput-Ji", "e": 36996, "s": 33274, "text": null }, { "code": "<script> // JavaScript program to count number of pairs // in a binary tree violating the BST property // Class that represents a node of the tree class Node { // Constructor to create a new tree node constructor(key) { this.data = key; this.left = null; this.right = null; } } // This method sorts the input array and returns the // number of inversions in the array function mergeSort(arr, array_size) { var temp = new Array(array_size).fill(0); return _mergeSort(arr, temp, 0, array_size - 1); } // An auxiliary recursive method that sorts // the input array and returns the number of // inversions in the array function _mergeSort(arr, temp, left, right) { var mid, inv_count = 0; if (right > left) { // Divide the array into two parts and // call _mergeSortAndCountInv() for each // of the parts mid = parseInt((right + left) / 2); // Inversion count will be sum of inversions // in left-part, right-part and number of // inversions in merging inv_count = _mergeSort(arr, temp, left, mid); inv_count += _mergeSort(arr, temp, mid + 1, right); // Merge the two parts inv_count += merge(arr, temp, left, mid + 1, right); } return inv_count; } // This method merges two sorted arrays and returns // inversion count in the arrays function merge(arr, temp, left, mid, right) { var i, j, k; var inv_count = 0; // i is index for left subarray i = left; // j is index for right subarray j = mid; // k is index for resultant merged subarray k = left; while (i <= mid - 1 && j <= right) { if (arr[i] <= arr[j]) { temp[k++] = arr[i++]; } else { temp[k++] = arr[j++]; inv_count = inv_count + (mid - i); } } // Copy the remaining elements of left subarray // (if there are any) to temp while (i <= mid - 1) temp[k++] = arr[i++]; // Copy the remaining elements of right subarray // if there are any) to temp while (j <= right) temp[k++] = arr[j++]; // Copy back the merged elements to original array for (i = left; i <= right; i++) arr[i] = temp[i]; return inv_count; } // Array to store // inorder traversal of the binary tree var a = []; var i; // Inorder traversal of the binary tree function Inorder(node) { if (node == null) return; Inorder(node.left); a[i++] = node.data; Inorder(node.right); } // Function to count the pairs // in a binary tree violating BST property function pairsViolatingBST(root, N) { if (root == null) return 0; i = 0; a = new Array(N).fill(0); Inorder(root); // Total inversions in the array var inversionCount = mergeSort(a, N); return inversionCount; } // Driver code var N = 7; var root = new Node(50); root.left = new Node(30); root.right = new Node(60); root.left.left = new Node(20); root.left.right = new Node(25); root.right.left = new Node(10); root.right.right = new Node(40); document.write(pairsViolatingBST(root, N) + \"<br>\"); // This code is contributed by rdtank. </script>", "e": 40532, "s": 36996, "text": null }, { "code": null, "e": 40534, "s": 40532, "text": "7" }, { "code": null, "e": 40546, "s": 40536, "text": "Rajput-Ji" }, { "code": null, "e": 40557, "s": 40546, "text": "bgangwar59" }, { "code": null, "e": 40564, "s": 40557, "text": "rdtank" }, { "code": null, "e": 40576, "s": 40564, "text": "Binary Tree" }, { "code": null, "e": 40586, "s": 40576, "text": "inversion" }, { "code": null, "e": 40605, "s": 40586, "text": "Binary Search Tree" }, { "code": null, "e": 40624, "s": 40605, "text": "Technical Scripter" }, { "code": null, "e": 40643, "s": 40624, "text": "Binary Search Tree" }, { "code": null, "e": 40741, "s": 40643, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 40775, "s": 40741, "text": "Print BST keys in the given range" }, { "code": null, "e": 40832, "s": 40775, "text": "Find the node with maximum value in a Binary Search Tree" }, { "code": null, "e": 40864, "s": 40832, "text": "set vs unordered_set in C++ STL" }, { "code": null, "e": 40890, "s": 40864, "text": "Floor and Ceil from a BST" }, { "code": null, "e": 40942, "s": 40890, "text": "Construct BST from given preorder traversal | Set 2" }, { "code": null, "e": 40975, "s": 40942, "text": "Threaded Binary Tree | Insertion" }, { "code": null, "e": 41002, "s": 40975, "text": "Red Black Tree vs AVL Tree" }, { "code": null, "e": 41054, "s": 41002, "text": "Construct a Binary Search Tree from given postorder" }, { "code": null, "e": 41110, "s": 41054, "text": "How to check if a given array represents a Binary Heap?" } ]
Generate k digit numbers with digits in strictly increasing order - GeeksforGeeks
26 Apr, 2021 Given a value k, generate all well-ordered numbers of length k. Well-ordered means that dig­its should be in increas­ing.Examples : Input : K = 7 Output : 1234567 1234568 1234569 1234578 1234579 1234589 1234678 1234679 1234689 1234789 1235678 1235679 1235689 1235789 1236789 1245678 1245679 1245689 1245789 1246789 1256789 1345678 1345679 1345689 1345789 1346789 1356789 1456789 2345678 2345679 2345689 2345789 2346789 2356789 2456789 3456789 Input : K = 3 Output : 123 124 125 126 127 128 129 134 135 136 137 138 139 145 146 147 148 149 156 157 158 159 167 168 169 178 179 189 234 235 236 237 238 239 245 246 247 248 249 256 257 258 259 267 268 269 278 279 289 345 346 347 348 349 356 357 358 359 367 368 369 378 379 389 456 457 458 459 467 468 469 478 479 489 567 568 569 578 579 589 678 679 689 789 This prob­lem is quite sim­i­lar to print all possible strings of length k that can be formed from a set of n characters1. Loop through i = x to 9. (all dig­its will be from 1 to 9). 2. x will start with 0 and will be incre­mented with every recur­sive call to make sure that the numbers are well-formed. 3. With every recur­sive call, mul­ti­ply the result (which will start with 0) by 10 and add i and make k = k-1.Below is the implementation of the above idea : C++ Java Python 3 C# PHP Javascript // C++ program to generate well// ordered numbers with k digits.#include<bits/stdc++.h>using namespace std; // number --> Current value of number.// x --> Current digit to be considered// k --> Remaining number of digitsvoid printWellOrdered(int number, int x, int k){ if (k == 0) { cout << number << " "; return; } // Try all possible greater digits for (int i = (x + 1); i < 10; i++) printWellOrdered(number * 10 + i, i, k - 1);} // Generates all well ordered // numbers of length k.void generateWellOrdered(int k){ printWellOrdered(0, 0, k);} // Driver codeint main(){ int k = 3; generateWellOrdered(k); return 0;} // Java program to generate well // ordered numbers with k digits. class Generate{ // number --> Current value of number. // x --> Current digit to be considered // k --> Remaining number of digits static void printWellOrdered(int number, int x, int k) { if (k == 0) { System.out.print(number+" "); return; } // Try all possible greater digits for (int i = (x + 1); i < 10; i++) printWellOrdered(number * 10 + i, i, k - 1); } // Generates all well ordered // numbers of length k. static void generateWellOrdered(int k) { printWellOrdered(0, 0, k); } // Driver Code public static void main (String[] args) { int k = 3; generateWellOrdered(k); }} # Python 3 program to generate well# ordered numbers with k digits. # number --> Current value of number.# x --> Current digit to be considered# k --> Remaining number of digitsdef printWellOrdered(number, x, k): if (k == 0): print(number, end = " ") return # Try all possible greater digits for i in range( (x + 1), 10): printWellOrdered(number * 10 + i, i, k - 1) # Generates all well ordered # numbers of length k.def generateWellOrdered(k): printWellOrdered(0, 0, k) # Driver codeif __name__ == "__main__": k = 3 generateWellOrdered(k) # This code is contributed by Ita_c // C# program to generate well// ordered numbers with k digits.using System; class GFG { // number --> Current value of number. // x --> Current digit to be considered // k --> Remaining number of digits static void printWellOrdered(int number, int x, int k) { if (k == 0) { Console.Write(number + " "); return; } // Try all possible greater digits for (int i = (x + 1); i < 10; i++) printWellOrdered(number * 10 + i, i, k - 1); } // Generates all well ordered // numbers of length k. static void generateWellOrdered(int k) { printWellOrdered(0, 0, k); } // Driver Code public static void Main () { int k = 3; generateWellOrdered(k); }} // This code is contributed by nitin mittal <?php// PHP program to generate well // ordered numbers with k digits. // number --> Current value of number.// x --> Current digit to be considered// k --> Remaining number of digitsfunction printWellOrdered($number, $x, $k){ if ($k == 0) { echo $number, " "; return; } // Try all possible greater digits for ($i = ($x + 1); $i < 10; $i++) printWellOrdered($number * 10 + $i, $i, $k - 1);} // Generates all well ordered // numbers of length kfunction generateWellOrdered($k){ printWellOrdered(0, 0, $k);} // Driver code$k = 3;generateWellOrdered($k); // This code is contributed by ajit.?> <script> // Javascript program to generate well // ordered numbers with k digits. // number --> Current value of number. // x --> Current digit to be considered // k --> Remaining number of digits function printWellOrdered(number,x,k) { if (k == 0) { document.write(number+" "); return; } // Try all possible greater digits for (let i = (x + 1); i < 10; i++) printWellOrdered(number * 10 + i, i, k - 1); } // Generates all well ordered // numbers of length k. function generateWellOrdered(k) { printWellOrdered(0, 0, k); } // Driver Code let k = 3; generateWellOrdered(k); // This code is contributed by rag2127 </script> Output : 123 124 125 126 127 128 129 134 135 136 137 138 139 145 146 147 148 149 156 157 158 159 167 168 169 178 179 189 234 235 236 237 238 239 245 246 247 248 249 256 257 258 259 267 268 269 278 279 289 345 346 347 348 349 356 357 358 359 367 368 369 378 379 389 456 457 458 459 467 468 469 478 479 489 567 568 569 578 579 589 678 679 689 789 This article is contributed by Rakesh Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. nitin mittal jit_t ukasp rag2127 number-digits Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Find all factors of a natural number | Set 1 Check if a number is Palindrome Program to print prime numbers from 1 to N. Program to add two binary strings Program to multiply two matrices Fizz Buzz Implementation Find pair with maximum GCD in an array Find Union and Intersection of two unsorted arrays Count all possible paths from top left to bottom right of a mXn matrix Count ways to reach the n'th stair
[ { "code": null, "e": 24301, "s": 24273, "text": "\n26 Apr, 2021" }, { "code": null, "e": 24435, "s": 24301, "text": "Given a value k, generate all well-ordered numbers of length k. Well-ordered means that dig­its should be in increas­ing.Examples : " }, { "code": null, "e": 25122, "s": 24435, "text": "Input : K = 7\nOutput :\n1234567 1234568 1234569 1234578 1234579\n1234589 1234678 1234679 1234689 1234789 \n1235678 1235679 1235689 1235789 1236789 \n1245678 1245679 1245689 1245789 1246789 \n1256789 1345678 1345679 1345689 1345789 \n1346789 1356789 1456789 2345678 2345679 \n2345689 2345789 2346789 2356789 2456789 \n3456789\n\nInput : K = 3\nOutput :\n123 124 125 126 127 128 129 134 135 136 \n137 138 139 145 146 147 148 149 156 157 \n158 159 167 168 169 178 179 189 234 235 \n236 237 238 239 245 246 247 248 249 256 \n257 258 259 267 268 269 278 279 289 345 \n346 347 348 349 356 357 358 359 367 368 \n369 378 379 389 456 457 458 459 467 468 \n469 478 479 489 567 568 569 578 579 589 \n678 679 689 789 " }, { "code": null, "e": 25590, "s": 25124, "text": "This prob­lem is quite sim­i­lar to print all possible strings of length k that can be formed from a set of n characters1. Loop through i = x to 9. (all dig­its will be from 1 to 9). 2. x will start with 0 and will be incre­mented with every recur­sive call to make sure that the numbers are well-formed. 3. With every recur­sive call, mul­ti­ply the result (which will start with 0) by 10 and add i and make k = k-1.Below is the implementation of the above idea : " }, { "code": null, "e": 25594, "s": 25590, "text": "C++" }, { "code": null, "e": 25599, "s": 25594, "text": "Java" }, { "code": null, "e": 25608, "s": 25599, "text": "Python 3" }, { "code": null, "e": 25611, "s": 25608, "text": "C#" }, { "code": null, "e": 25615, "s": 25611, "text": "PHP" }, { "code": null, "e": 25626, "s": 25615, "text": "Javascript" }, { "code": "// C++ program to generate well// ordered numbers with k digits.#include<bits/stdc++.h>using namespace std; // number --> Current value of number.// x --> Current digit to be considered// k --> Remaining number of digitsvoid printWellOrdered(int number, int x, int k){ if (k == 0) { cout << number << \" \"; return; } // Try all possible greater digits for (int i = (x + 1); i < 10; i++) printWellOrdered(number * 10 + i, i, k - 1);} // Generates all well ordered // numbers of length k.void generateWellOrdered(int k){ printWellOrdered(0, 0, k);} // Driver codeint main(){ int k = 3; generateWellOrdered(k); return 0;}", "e": 26344, "s": 25626, "text": null }, { "code": "// Java program to generate well // ordered numbers with k digits. class Generate{ // number --> Current value of number. // x --> Current digit to be considered // k --> Remaining number of digits static void printWellOrdered(int number, int x, int k) { if (k == 0) { System.out.print(number+\" \"); return; } // Try all possible greater digits for (int i = (x + 1); i < 10; i++) printWellOrdered(number * 10 + i, i, k - 1); } // Generates all well ordered // numbers of length k. static void generateWellOrdered(int k) { printWellOrdered(0, 0, k); } // Driver Code public static void main (String[] args) { int k = 3; generateWellOrdered(k); }}", "e": 27207, "s": 26344, "text": null }, { "code": "# Python 3 program to generate well# ordered numbers with k digits. # number --> Current value of number.# x --> Current digit to be considered# k --> Remaining number of digitsdef printWellOrdered(number, x, k): if (k == 0): print(number, end = \" \") return # Try all possible greater digits for i in range( (x + 1), 10): printWellOrdered(number * 10 + i, i, k - 1) # Generates all well ordered # numbers of length k.def generateWellOrdered(k): printWellOrdered(0, 0, k) # Driver codeif __name__ == \"__main__\": k = 3 generateWellOrdered(k) # This code is contributed by Ita_c", "e": 27867, "s": 27207, "text": null }, { "code": "// C# program to generate well// ordered numbers with k digits.using System; class GFG { // number --> Current value of number. // x --> Current digit to be considered // k --> Remaining number of digits static void printWellOrdered(int number, int x, int k) { if (k == 0) { Console.Write(number + \" \"); return; } // Try all possible greater digits for (int i = (x + 1); i < 10; i++) printWellOrdered(number * 10 + i, i, k - 1); } // Generates all well ordered // numbers of length k. static void generateWellOrdered(int k) { printWellOrdered(0, 0, k); } // Driver Code public static void Main () { int k = 3; generateWellOrdered(k); }} // This code is contributed by nitin mittal", "e": 28782, "s": 27867, "text": null }, { "code": "<?php// PHP program to generate well // ordered numbers with k digits. // number --> Current value of number.// x --> Current digit to be considered// k --> Remaining number of digitsfunction printWellOrdered($number, $x, $k){ if ($k == 0) { echo $number, \" \"; return; } // Try all possible greater digits for ($i = ($x + 1); $i < 10; $i++) printWellOrdered($number * 10 + $i, $i, $k - 1);} // Generates all well ordered // numbers of length kfunction generateWellOrdered($k){ printWellOrdered(0, 0, $k);} // Driver code$k = 3;generateWellOrdered($k); // This code is contributed by ajit.?>", "e": 29443, "s": 28782, "text": null }, { "code": "<script> // Javascript program to generate well // ordered numbers with k digits. // number --> Current value of number. // x --> Current digit to be considered // k --> Remaining number of digits function printWellOrdered(number,x,k) { if (k == 0) { document.write(number+\" \"); return; } // Try all possible greater digits for (let i = (x + 1); i < 10; i++) printWellOrdered(number * 10 + i, i, k - 1); } // Generates all well ordered // numbers of length k. function generateWellOrdered(k) { printWellOrdered(0, 0, k); } // Driver Code let k = 3; generateWellOrdered(k); // This code is contributed by rag2127 </script>", "e": 30260, "s": 29443, "text": null }, { "code": null, "e": 30270, "s": 30260, "text": "Output : " }, { "code": null, "e": 30614, "s": 30270, "text": "123 124 125 126 127 128 129 134 135 136 137 \n138 139 145 146 147 148 149 156 157 158 159 \n167 168 169 178 179 189 234 235 236 237 238 \n239 245 246 247 248 249 256 257 258 259 267 \n268 269 278 279 289 345 346 347 348 349 356 \n357 358 359 367 368 369 378 379 389 456 457 \n458 459 467 468 469 478 479 489 567 568 569 \n578 579 589 678 679 689 789 " }, { "code": null, "e": 31039, "s": 30614, "text": "This article is contributed by Rakesh Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 31052, "s": 31039, "text": "nitin mittal" }, { "code": null, "e": 31058, "s": 31052, "text": "jit_t" }, { "code": null, "e": 31064, "s": 31058, "text": "ukasp" }, { "code": null, "e": 31072, "s": 31064, "text": "rag2127" }, { "code": null, "e": 31086, "s": 31072, "text": "number-digits" }, { "code": null, "e": 31099, "s": 31086, "text": "Mathematical" }, { "code": null, "e": 31112, "s": 31099, "text": "Mathematical" }, { "code": null, "e": 31210, "s": 31112, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31219, "s": 31210, "text": "Comments" }, { "code": null, "e": 31232, "s": 31219, "text": "Old Comments" }, { "code": null, "e": 31277, "s": 31232, "text": "Find all factors of a natural number | Set 1" }, { "code": null, "e": 31309, "s": 31277, "text": "Check if a number is Palindrome" }, { "code": null, "e": 31353, "s": 31309, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 31387, "s": 31353, "text": "Program to add two binary strings" }, { "code": null, "e": 31420, "s": 31387, "text": "Program to multiply two matrices" }, { "code": null, "e": 31445, "s": 31420, "text": "Fizz Buzz Implementation" }, { "code": null, "e": 31484, "s": 31445, "text": "Find pair with maximum GCD in an array" }, { "code": null, "e": 31535, "s": 31484, "text": "Find Union and Intersection of two unsorted arrays" }, { "code": null, "e": 31606, "s": 31535, "text": "Count all possible paths from top left to bottom right of a mXn matrix" } ]
Synchronous Chatting Application using C++ boost::asio - GeeksforGeeks
22 Apr, 2021 Boost library consists of asio which is a free, cross-platform C++ library for network and low-level I/O programming that provides a consistent asynchronous model using a modern C++ approach. This article will help to develop a client-server synchronous chatting application using boost::asio. We are explicitly mentioning “synchronous” because in the synchronous model one of our client or server has to wait for another. Server-Side Application: Below are the various steps to create the Server Side application: Importing boost/asio.hpp (Version: 1.65.1.0) #include <boost/asio.hpp> Creating object of io_service (for server) which is mandatory for using boost::asio. boost::asio::io_service io_service_object; Creating object of acceptor, passing io_service object and endpoint of connection i.e. IPv4 and port number 9999 (IPv6 protocol is also supported in boost::asio, also note that port 0 – 1233 are reserved). boost::asio::ip::tcp::acceptor acceptor_object( io_service_object, tcp::endpoint(boost::asio::ip::tcp::v4(), 9999)); Creating tcp::socket object for our server. boost::asio::ip::tcp::socket socket_object(io_service_object) Invoking accept method of acceptor object to establish connection. acceptor_server.accept(server_socket); read_until() method fetches message from the buffer which stores data during communication. Here we are using “\n” as out delimiter, which means we shall keep reading data from the buffer until we encounter “\n” and store it. // Create buffer for storing boost::asio::streambuf buf; boost::asio::read_until(socket, buf, "\n"); string data = boost::asio::buffer_cast(buf.data()); write() method writes data to the buffer taking socket object and message as parameter. boost::asio::write( socket, boost::asio::buffer(message + "\n")); Client-Side Application: Below are the various steps to create the Client Side application: Importing boost/asio.hpp. #include <boost/asio.hpp> Creating object of io_service for client. boost::asio::io_service io_service_object; Creating tcp::socket object for client. boost::asio::ip::tcp::socket socket_object(io_service_object) Invoking connect method of socket object to initiate connection with server using localhost (IP 127.0.0.1) and connecting to same port 9999. client_socket.connect( tcp::endpoint( address::from_string("127.0.0.1"), 9999 )); read_until() and write() will remain same for our client application as well, as the Server side. Below is the implementation of the above approach: Program: // Server-side Synchronous Chatting Application // using C++ boost::asio #include <boost/asio.hpp> #include <iostream> using namespace std; using namespace boost::asio; using namespace boost::asio::ip; // Driver program for receiving data from buffer string getData(tcp::socket& socket) { streambuf buf; read_until(socket, buf, "\n"); string data = buffer_cast<const char*>(buf.data()); return data; } // Driver program to send data void sendData(tcp::socket& socket, const string& message) { write(socket, buffer(message + "\n")); } int main(int argc, char* argv[]) { io_service io_service; // Listening for any new incomming connection // at port 9999 with IPv4 protocol tcp::acceptor acceptor_server( io_service, tcp::endpoint(tcp::v4(), 9999)); // Creating socket object tcp::socket server_socket(io_service); // waiting for connection acceptor_server.accept(server_socket); // Reading username string u_name = getData(server_socket); // Removing "\n" from the username u_name.pop_back(); // Replying with default message to initiate chat string response, reply; reply = "Hello " + u_name + "!"; cout << "Server: " << reply << endl; sendData(server_socket, reply); while (true) { // Fetching response response = getData(server_socket); // Popping last character "\n" response.pop_back(); // Validating if the connection has to be closed if (response == "exit") { cout << u_name << " left!" << endl; break; } cout << u_name << ": " << response << endl; // Reading new message from input stream cout << "Server" << ": "; getline(cin, reply); sendData(server_socket, reply); if (reply == "exit") break; } return 0; } client.cpp // Client-side Synchronous Chatting Application // using C++ boost::asio #include <boost/asio.hpp> #include <iostream> using namespace std; using namespace boost::asio; using namespace boost::asio::ip; string getData(tcp::socket& socket) { streambuf buf; read_until(socket, buf, "\n"); string data = buffer_cast<const char*>(buf.data()); return data; } void sendData(tcp::socket& socket, const string& message) { write(socket, buffer(message + "\n")); } int main(int argc, char* argv[]) { io_service io_service; // socket creation ip::tcp::socket client_socket(io_service); client_socket .connect( tcp::endpoint( address::from_string("127.0.0.1"), 9999)); // Getting username from user cout << "Enter your name: "; string u_name, reply, response; getline(cin, u_name); // Sending username to another end // to initiate the conversation sendData(client_socket, u_name); // Infinite loop for chit-chat while (true) { // Fetching response response = getData(client_socket); // Popping last character "\n" response.pop_back(); // Validating if the connection has to be closed if (response == "exit") { cout << "Connection terminated" << endl; break; } cout << "Server: " << response << endl; // Reading new message from input stream cout << u_name << ": "; getline(cin, reply); sendData(client_socket, reply); if (reply == "exit") break; } return 0; } Compile and run the server first by executing: $ g++ client.cpp -o client -lboost_system ./client Open another cmd/terminal and run the client by executing: $ g++ server.cpp -o server -lboost_system ./server Output The above socket programming explains our simple synchronous TCP server and client chatting application. One of the major drawbacks of the synchronous client-server application is that one request has to be served before we request for another one, thus blocking our later requests. In case we want our program to perform multiple operations simultaneously, we can use multi-threaded TCP client-server to handle the situation. However, the multi-threaded application is not recommended because of various complexities involved in creating threads. Another option can come handy, and that is the asynchronous server. This is where boost::asio shines, we shall understand this in the next article. simmytarika5 C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Operator Overloading in C++ Polymorphism in C++ Friend class and function in C++ Sorting a vector in C++ std::string class in C++ Array of Strings in C++ (5 Different Ways to Create) Pair in C++ Standard Template Library (STL) Inline Functions in C++ Convert string to char array in C++ List in C++ Standard Template Library (STL)
[ { "code": null, "e": 24222, "s": 24194, "text": "\n22 Apr, 2021" }, { "code": null, "e": 24738, "s": 24222, "text": "Boost library consists of asio which is a free, cross-platform C++ library for network and low-level I/O programming that provides a consistent asynchronous model using a modern C++ approach. This article will help to develop a client-server synchronous chatting application using boost::asio. We are explicitly mentioning “synchronous” because in the synchronous model one of our client or server has to wait for another. Server-Side Application: Below are the various steps to create the Server Side application: " }, { "code": null, "e": 24785, "s": 24738, "text": "Importing boost/asio.hpp (Version: 1.65.1.0) " }, { "code": null, "e": 24811, "s": 24785, "text": "#include <boost/asio.hpp>" }, { "code": null, "e": 24898, "s": 24811, "text": "Creating object of io_service (for server) which is mandatory for using boost::asio. " }, { "code": null, "e": 24941, "s": 24898, "text": "boost::asio::io_service io_service_object;" }, { "code": null, "e": 25149, "s": 24941, "text": "Creating object of acceptor, passing io_service object and endpoint of connection i.e. IPv4 and port number 9999 (IPv6 protocol is also supported in boost::asio, also note that port 0 – 1233 are reserved). " }, { "code": null, "e": 25297, "s": 25149, "text": "boost::asio::ip::tcp::acceptor \n acceptor_object(\n io_service_object, \n tcp::endpoint(boost::asio::ip::tcp::v4(), \n 9999));" }, { "code": null, "e": 25343, "s": 25297, "text": "Creating tcp::socket object for our server. " }, { "code": null, "e": 25406, "s": 25343, "text": "boost::asio::ip::tcp::socket socket_object(io_service_object) " }, { "code": null, "e": 25475, "s": 25406, "text": "Invoking accept method of acceptor object to establish connection. " }, { "code": null, "e": 25514, "s": 25475, "text": "acceptor_server.accept(server_socket);" }, { "code": null, "e": 25742, "s": 25514, "text": "read_until() method fetches message from the buffer which stores data during communication. Here we are using “\\n” as out delimiter, which means we shall keep reading data from the buffer until we encounter “\\n” and store it. " }, { "code": null, "e": 25896, "s": 25742, "text": "// Create buffer for storing\nboost::asio::streambuf buf;\n\nboost::asio::read_until(socket, buf, \"\\n\");\nstring data = boost::asio::buffer_cast(buf.data());" }, { "code": null, "e": 25986, "s": 25896, "text": "write() method writes data to the buffer taking socket object and message as parameter. " }, { "code": null, "e": 26057, "s": 25986, "text": "boost::asio::write(\n socket, \n boost::asio::buffer(message + \"\\n\"));" }, { "code": null, "e": 26151, "s": 26057, "text": "Client-Side Application: Below are the various steps to create the Client Side application: " }, { "code": null, "e": 26179, "s": 26151, "text": "Importing boost/asio.hpp. " }, { "code": null, "e": 26205, "s": 26179, "text": "#include <boost/asio.hpp>" }, { "code": null, "e": 26249, "s": 26205, "text": "Creating object of io_service for client. " }, { "code": null, "e": 26292, "s": 26249, "text": "boost::asio::io_service io_service_object;" }, { "code": null, "e": 26334, "s": 26292, "text": "Creating tcp::socket object for client. " }, { "code": null, "e": 26399, "s": 26334, "text": "boost::asio::ip::tcp::socket\n socket_object(io_service_object) " }, { "code": null, "e": 26542, "s": 26399, "text": "Invoking connect method of socket object to initiate connection with server using localhost (IP 127.0.0.1) and connecting to same port 9999. " }, { "code": null, "e": 26635, "s": 26542, "text": "client_socket.connect(\n tcp::endpoint(\n address::from_string(\"127.0.0.1\"), \n 9999 ));" }, { "code": null, "e": 26733, "s": 26635, "text": "read_until() and write() will remain same for our client application as well, as the Server side." }, { "code": null, "e": 26794, "s": 26733, "text": "Below is the implementation of the above approach: Program: " }, { "code": null, "e": 28709, "s": 26794, "text": "\n// Server-side Synchronous Chatting Application\n// using C++ boost::asio\n\n#include <boost/asio.hpp>\n#include <iostream>\n\nusing namespace std;\nusing namespace boost::asio;\nusing namespace boost::asio::ip;\n\n// Driver program for receiving data from buffer\nstring getData(tcp::socket& socket)\n{\n streambuf buf;\n read_until(socket, buf, \"\\n\");\n string data = buffer_cast<const char*>(buf.data());\n return data;\n}\n\n// Driver program to send data\nvoid sendData(tcp::socket& socket, const string& message)\n{\n write(socket,\n buffer(message + \"\\n\"));\n}\n\nint main(int argc, char* argv[])\n{\n io_service io_service;\n\n // Listening for any new incomming connection\n // at port 9999 with IPv4 protocol\n tcp::acceptor acceptor_server(\n io_service,\n tcp::endpoint(tcp::v4(), 9999));\n\n // Creating socket object\n tcp::socket server_socket(io_service);\n\n // waiting for connection\n acceptor_server.accept(server_socket);\n\n // Reading username\n string u_name = getData(server_socket);\n // Removing \"\\n\" from the username\n u_name.pop_back();\n\n // Replying with default message to initiate chat\n string response, reply;\n reply = \"Hello \" + u_name + \"!\";\n cout << \"Server: \" << reply << endl;\n sendData(server_socket, reply);\n\n while (true) {\n\n // Fetching response\n response = getData(server_socket);\n\n // Popping last character \"\\n\"\n response.pop_back();\n\n // Validating if the connection has to be closed\n if (response == \"exit\") {\n cout << u_name << \" left!\" << endl;\n break;\n }\n cout << u_name << \": \" << response << endl;\n\n // Reading new message from input stream\n cout << \"Server\"\n << \": \";\n getline(cin, reply);\n sendData(server_socket, reply);\n\n if (reply == \"exit\")\n break;\n }\n return 0;\n}\n" }, { "code": null, "e": 28720, "s": 28709, "text": "client.cpp" }, { "code": null, "e": 30365, "s": 28720, "text": "\n// Client-side Synchronous Chatting Application\n// using C++ boost::asio\n\n#include <boost/asio.hpp>\n#include <iostream>\nusing namespace std;\nusing namespace boost::asio;\nusing namespace boost::asio::ip;\n\nstring getData(tcp::socket& socket)\n{\n streambuf buf;\n read_until(socket, buf, \"\\n\");\n string data = buffer_cast<const char*>(buf.data());\n return data;\n}\n\nvoid sendData(tcp::socket& socket, const string& message)\n{\n write(socket,\n buffer(message + \"\\n\"));\n}\n\nint main(int argc, char* argv[])\n{\n io_service io_service;\n // socket creation\n ip::tcp::socket client_socket(io_service);\n\n client_socket\n .connect(\n tcp::endpoint(\n address::from_string(\"127.0.0.1\"),\n 9999));\n\n // Getting username from user\n cout << \"Enter your name: \";\n string u_name, reply, response;\n getline(cin, u_name);\n\n // Sending username to another end\n // to initiate the conversation\n sendData(client_socket, u_name);\n\n // Infinite loop for chit-chat\n while (true) {\n\n // Fetching response\n response = getData(client_socket);\n\n // Popping last character \"\\n\"\n response.pop_back();\n\n // Validating if the connection has to be closed\n if (response == \"exit\") {\n cout << \"Connection terminated\" << endl;\n break;\n }\n cout << \"Server: \" << response << endl;\n\n // Reading new message from input stream\n cout << u_name << \": \";\n getline(cin, reply);\n sendData(client_socket, reply);\n\n if (reply == \"exit\")\n break;\n }\n return 0;\n}\n" }, { "code": null, "e": 30414, "s": 30365, "text": "Compile and run the server first by executing: " }, { "code": null, "e": 30465, "s": 30414, "text": "$ g++ client.cpp -o client -lboost_system\n./client" }, { "code": null, "e": 30528, "s": 30467, "text": "Open another cmd/terminal and run the client by executing: " }, { "code": null, "e": 30579, "s": 30528, "text": "$ g++ server.cpp -o server -lboost_system\n./server" }, { "code": null, "e": 30590, "s": 30581, "text": "Output " }, { "code": null, "e": 31291, "s": 30594, "text": "The above socket programming explains our simple synchronous TCP server and client chatting application. One of the major drawbacks of the synchronous client-server application is that one request has to be served before we request for another one, thus blocking our later requests. In case we want our program to perform multiple operations simultaneously, we can use multi-threaded TCP client-server to handle the situation. However, the multi-threaded application is not recommended because of various complexities involved in creating threads. Another option can come handy, and that is the asynchronous server. This is where boost::asio shines, we shall understand this in the next article. " }, { "code": null, "e": 31304, "s": 31291, "text": "simmytarika5" }, { "code": null, "e": 31308, "s": 31304, "text": "C++" }, { "code": null, "e": 31312, "s": 31308, "text": "CPP" }, { "code": null, "e": 31410, "s": 31312, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31438, "s": 31410, "text": "Operator Overloading in C++" }, { "code": null, "e": 31458, "s": 31438, "text": "Polymorphism in C++" }, { "code": null, "e": 31491, "s": 31458, "text": "Friend class and function in C++" }, { "code": null, "e": 31515, "s": 31491, "text": "Sorting a vector in C++" }, { "code": null, "e": 31540, "s": 31515, "text": "std::string class in C++" }, { "code": null, "e": 31593, "s": 31540, "text": "Array of Strings in C++ (5 Different Ways to Create)" }, { "code": null, "e": 31637, "s": 31593, "text": "Pair in C++ Standard Template Library (STL)" }, { "code": null, "e": 31661, "s": 31637, "text": "Inline Functions in C++" }, { "code": null, "e": 31697, "s": 31661, "text": "Convert string to char array in C++" } ]
[Machine Learning] How to do feature selection | by Jay Hui | Towards Data Science
When I had an interview for a data science-related job, the interviewer asked me the following question. Afterwards, I also asked the same question to the candidate when I was an interviewer: Given a large dataset (more than 1,000 columns with 100,000 rows (records)), how will you select the useful features to build a (supervised) model? This is a good question to distinguish your data science knowledge between a student and a professional level. When you are a student, you learn algorithms from a beautiful and cleansed dataset. However, in the business world, data scientists put a lot of effort into data cleansing to build a machine learning model. Back to our question: Given a large dataset (more than 1000 columns with 10000 rows (records)), how do you select the useful features to build a (supervised) model? In fact, there is no absolute solution to this question but is to test your logical thinking and explanation skill. In this post, I would share a few methodologies (feature selection) to handle it. The Kaggle notebook is uploaded here, where the dataset I use is the prudential life insurance underwriting data: www.kaggle.com This task aims to predict the risk level (underwriting) of the life insurance applicant. For more implementation of feature selection, you may check the Scikit-learn article as well. First, we read the data: Here I am going to do some simple data cleansing. Most machine learning model implementations do not accept string inputs, and hence we have to transform them into numeric values. As our target is is an ordinal target (i.e., supervised learning), transforming the categorical variable by the basic OneHotEncoder suffers from the “curse of dimensionality” (usually it takes more time in model training as well). Instead, what we do for the categorical column is as follows: Based on its categorical value, we calculate the corresponding mean values of the Y target (by “GroupBy”) and rank it from 0 to the number of unique categorical values that column minus 1. Such mapping is available for testing data or production later. Then, we fill in the missing value as a standard procedure: Suppose you have 200 football players, and you would like to select 11 of them to form the best football team. How would you select them? In the analogy of the football player selection, the unsupervised approach evaluates each player's basic information, such as height, BMI, age, and other health markers. These are not football-specific (unsupervised), but most excellent football players should have a good physical foundation. Drop columns with a high missing rateThe first and easiest approach is to drop columns in the unsupervised approach. We can drop columns that have too many missing values. (59381, 127)(59381, 126) Drop columns with a small varianceAnother way is to drop columns with too small a variance since these columns generally give little information. number of columns after dropping by variance threshold: 16 PCAPCA is a more advanced way to perform feature selection. The main advantage is that the transformed features are now independent; however, the transformed features are hard to interpret. You can check this article for the PCA implementation of Scikit-learn. A more sophisticated approach is to do it by supervised learning. Back to our analogy of football team selection, we do it in two rounds: In the first round, we evaluate the football skills (supervised), such as penalty kick, shooting, short-pass ability, for each player and rank them. Suppose we can select the top 50 players out of the 200 players now. In the second round, since we want to find the best combination of 11 players out of the 50 players, we need to evaluate how these 50 players will cooperate. We will finally find the best 11 players. (Why do we not do the second round directly? Running every iteration takes a lot of time, so we need the preliminary test in the first round.) Technically speaking, the first round is the “feature selection by model,” and the second round is “Recursive Feature Elimination” (RFE). Let’s go back to machine learning and coding now. Feature selection by modelSome ML models are designed for the feature selection, such as L1-based linear regression and Extremely Randomized Trees (Extra-trees model). Comparing to L2 regularization, L1 regularization tends to force the parameters of the unimportant features to zero. (Do you know why?) The extremely randomized trees split the leaf randomly (not through information gain or entropy). The important features should still be more important than the unimportant features (measured by the impurity-based feature importance). We evaluate it with three models: CPU times: user 15.9 s, sys: 271 ms, total: 16.2 sWall time: 14.3 s========== LogisticRegression ==========Accuracy in training: 0.4138598854833277Accuracy in valid: 0.41020945163666983Show top 10 important features: ========== ExtraTreesClassifier ==========Accuracy in training: 0.3467497473896935Accuracy in valid: 0.3467213977476055Show top 10 important features: ========== RandomForestClassifier ==========Accuracy in training: 0.3473391714381947Accuracy in valid: 0.34581622987053995Show top 10 important features: We also plot the model importance rankings for each model: Since L1-based logistic regression has the highest accuracy, so we will only select the top 60 features (from the graph) by logistic regression: selected_model = ‘LogisticRegression’number_of_features = 60selected_features_by_model = importance_fatures_sorted_all[importance_fatures_sorted_all[‘model’] == selected_model].index[:number_of_features].tolist() Recursive Feature Elimination (RFE)The second part is to select the best combination of features. We do it by “Recursive Feature Elimination” (RFE). Instead of building one model, we build n models (where n = the number of features). In the first iteration, we train the model by all 60 features and calculate the cross-validation accuracy and all columns' feature importance. Then we drop the least important feature, and so we have 59 features now. Based on these 59 features, we repeat the above process, and we end at the last single feature. This method takes time but will give you a reliable feature importance ranking. If time is not allowed for the large dataset, one can consider do it by sampling or dropping more features at each iteration. CPU times: user 7min 2s, sys: 334 ms, total: 7min 2sWall time: 26min 32s As you can see, the validation accuracy will finally saturate (around 0.475) as trained with more features. We can check our feature importance ranking now: Again, there is no Golden Rule to perform the feature selection. In the business world with production, we have to balance the hardware capability, required time, stability of the model, and the model performance. After finding the best combination of columns, we can now select the best set of hyper-parameter.
[ { "code": null, "e": 511, "s": 171, "text": "When I had an interview for a data science-related job, the interviewer asked me the following question. Afterwards, I also asked the same question to the candidate when I was an interviewer: Given a large dataset (more than 1,000 columns with 100,000 rows (records)), how will you select the useful features to build a (supervised) model?" }, { "code": null, "e": 829, "s": 511, "text": "This is a good question to distinguish your data science knowledge between a student and a professional level. When you are a student, you learn algorithms from a beautiful and cleansed dataset. However, in the business world, data scientists put a lot of effort into data cleansing to build a machine learning model." }, { "code": null, "e": 851, "s": 829, "text": "Back to our question:" }, { "code": null, "e": 994, "s": 851, "text": "Given a large dataset (more than 1000 columns with 10000 rows (records)), how do you select the useful features to build a (supervised) model?" }, { "code": null, "e": 1192, "s": 994, "text": "In fact, there is no absolute solution to this question but is to test your logical thinking and explanation skill. In this post, I would share a few methodologies (feature selection) to handle it." }, { "code": null, "e": 1306, "s": 1192, "text": "The Kaggle notebook is uploaded here, where the dataset I use is the prudential life insurance underwriting data:" }, { "code": null, "e": 1321, "s": 1306, "text": "www.kaggle.com" }, { "code": null, "e": 1504, "s": 1321, "text": "This task aims to predict the risk level (underwriting) of the life insurance applicant. For more implementation of feature selection, you may check the Scikit-learn article as well." }, { "code": null, "e": 1529, "s": 1504, "text": "First, we read the data:" }, { "code": null, "e": 1940, "s": 1529, "text": "Here I am going to do some simple data cleansing. Most machine learning model implementations do not accept string inputs, and hence we have to transform them into numeric values. As our target is is an ordinal target (i.e., supervised learning), transforming the categorical variable by the basic OneHotEncoder suffers from the “curse of dimensionality” (usually it takes more time in model training as well)." }, { "code": null, "e": 2255, "s": 1940, "text": "Instead, what we do for the categorical column is as follows: Based on its categorical value, we calculate the corresponding mean values of the Y target (by “GroupBy”) and rank it from 0 to the number of unique categorical values that column minus 1. Such mapping is available for testing data or production later." }, { "code": null, "e": 2315, "s": 2255, "text": "Then, we fill in the missing value as a standard procedure:" }, { "code": null, "e": 2453, "s": 2315, "text": "Suppose you have 200 football players, and you would like to select 11 of them to form the best football team. How would you select them?" }, { "code": null, "e": 2747, "s": 2453, "text": "In the analogy of the football player selection, the unsupervised approach evaluates each player's basic information, such as height, BMI, age, and other health markers. These are not football-specific (unsupervised), but most excellent football players should have a good physical foundation." }, { "code": null, "e": 2919, "s": 2747, "text": "Drop columns with a high missing rateThe first and easiest approach is to drop columns in the unsupervised approach. We can drop columns that have too many missing values." }, { "code": null, "e": 2944, "s": 2919, "text": "(59381, 127)(59381, 126)" }, { "code": null, "e": 3090, "s": 2944, "text": "Drop columns with a small varianceAnother way is to drop columns with too small a variance since these columns generally give little information." }, { "code": null, "e": 3149, "s": 3090, "text": "number of columns after dropping by variance threshold: 16" }, { "code": null, "e": 3410, "s": 3149, "text": "PCAPCA is a more advanced way to perform feature selection. The main advantage is that the transformed features are now independent; however, the transformed features are hard to interpret. You can check this article for the PCA implementation of Scikit-learn." }, { "code": null, "e": 3548, "s": 3410, "text": "A more sophisticated approach is to do it by supervised learning. Back to our analogy of football team selection, we do it in two rounds:" }, { "code": null, "e": 3766, "s": 3548, "text": "In the first round, we evaluate the football skills (supervised), such as penalty kick, shooting, short-pass ability, for each player and rank them. Suppose we can select the top 50 players out of the 200 players now." }, { "code": null, "e": 4109, "s": 3766, "text": "In the second round, since we want to find the best combination of 11 players out of the 50 players, we need to evaluate how these 50 players will cooperate. We will finally find the best 11 players. (Why do we not do the second round directly? Running every iteration takes a lot of time, so we need the preliminary test in the first round.)" }, { "code": null, "e": 4297, "s": 4109, "text": "Technically speaking, the first round is the “feature selection by model,” and the second round is “Recursive Feature Elimination” (RFE). Let’s go back to machine learning and coding now." }, { "code": null, "e": 4870, "s": 4297, "text": "Feature selection by modelSome ML models are designed for the feature selection, such as L1-based linear regression and Extremely Randomized Trees (Extra-trees model). Comparing to L2 regularization, L1 regularization tends to force the parameters of the unimportant features to zero. (Do you know why?) The extremely randomized trees split the leaf randomly (not through information gain or entropy). The important features should still be more important than the unimportant features (measured by the impurity-based feature importance). We evaluate it with three models:" }, { "code": null, "e": 5087, "s": 4870, "text": "CPU times: user 15.9 s, sys: 271 ms, total: 16.2 sWall time: 14.3 s========== LogisticRegression ==========Accuracy in training: 0.4138598854833277Accuracy in valid: 0.41020945163666983Show top 10 important features:" }, { "code": null, "e": 5238, "s": 5087, "text": "========== ExtraTreesClassifier ==========Accuracy in training: 0.3467497473896935Accuracy in valid: 0.3467213977476055Show top 10 important features:" }, { "code": null, "e": 5392, "s": 5238, "text": "========== RandomForestClassifier ==========Accuracy in training: 0.3473391714381947Accuracy in valid: 0.34581622987053995Show top 10 important features:" }, { "code": null, "e": 5451, "s": 5392, "text": "We also plot the model importance rankings for each model:" }, { "code": null, "e": 5596, "s": 5451, "text": "Since L1-based logistic regression has the highest accuracy, so we will only select the top 60 features (from the graph) by logistic regression:" }, { "code": null, "e": 5809, "s": 5596, "text": "selected_model = ‘LogisticRegression’number_of_features = 60selected_features_by_model = importance_fatures_sorted_all[importance_fatures_sorted_all[‘model’] == selected_model].index[:number_of_features].tolist()" }, { "code": null, "e": 6562, "s": 5809, "text": "Recursive Feature Elimination (RFE)The second part is to select the best combination of features. We do it by “Recursive Feature Elimination” (RFE). Instead of building one model, we build n models (where n = the number of features). In the first iteration, we train the model by all 60 features and calculate the cross-validation accuracy and all columns' feature importance. Then we drop the least important feature, and so we have 59 features now. Based on these 59 features, we repeat the above process, and we end at the last single feature. This method takes time but will give you a reliable feature importance ranking. If time is not allowed for the large dataset, one can consider do it by sampling or dropping more features at each iteration." }, { "code": null, "e": 6635, "s": 6562, "text": "CPU times: user 7min 2s, sys: 334 ms, total: 7min 2sWall time: 26min 32s" }, { "code": null, "e": 6792, "s": 6635, "text": "As you can see, the validation accuracy will finally saturate (around 0.475) as trained with more features. We can check our feature importance ranking now:" } ]
Bokeh - Developing with JavaScript
The Bokeh Python library, and libraries for Other Languages such as R, Scala, and Julia, primarily interacts with BokehJS at a high level. A Python programmer does not have to worry about JavaScript or web development. However, one can use BokehJS API, to do pure JavaScript development using BokehJS directly. BokehJS objects such as glyphs and widgets are built more or less similarly as in Bokeh Python API. Typically, any Python ClassName is available as Bokeh.ClassName from JavaScript. For example, a Range1d object as obtained in Python. xrange = Range1d(start=-0.5, end=20.5) It is equivalently obtained with BokehJS as − var xrange = new Bokeh.Range1d({ start: -0.5, end: 20.5 }); Following JavaScript code when embedded in a HTML file renders a simple line plot in the browser. First include all BokehJS libraries in <head>..</head> secion of web page as below <head> <script type="text/javascript" src="https://cdn.pydata.org/bokeh/release/bokeh-1.3.4.min.js"></script> <script type="text/javascript" src="https://cdn.pydata.org/bokeh/release/bokeh-widgets-1.3.4.min.js"></script> <script type="text/javascript" src="https://cdn.pydata.org/bokeh/release/bokeh-tables-1.3.4.min.js"></script> <script type="text/javascript" src="https://cdn.pydata.org/bokeh/release/bokeh-gl-1.3.4.min.js"></script> <script type="text/javascript" src="https://cdn.pydata.org/bokeh/release/bokeh-api-1.3.4.min.js"></script> <script type="text/javascript" src="https://cdn.pydata.org/bokeh/release/bokeh-api-1.3.4.min.js"></script> </head> In the body section following snippets of JavaScript construct various parts of a Bokeh Plot. <script> // create some data and a ColumnDataSource var x = Bokeh.LinAlg.linspace(-0.5, 20.5, 10); var y = x.map(function (v) { return v * 0.5 + 3.0; }); var source = new Bokeh.ColumnDataSource({ data: { x: x, y: y } }); // make the plot var plot = new Bokeh.Plot({ title: "BokehJS Plot", plot_width: 400, plot_height: 400 }); // add axes to the plot var xaxis = new Bokeh.LinearAxis({ axis_line_color: null }); var yaxis = new Bokeh.LinearAxis({ axis_line_color: null }); plot.add_layout(xaxis, "below"); plot.add_layout(yaxis, "left"); // add a Line glyph var line = new Bokeh.Line({ x: { field: "x" }, y: { field: "y" }, line_color: "#666699", line_width: 2 }); plot.add_glyph(line, source); Bokeh.Plotting.show(plot); </script> Save above code as a web page and open it in a browser of your choice. Print Add Notes Bookmark this page
[ { "code": null, "e": 2581, "s": 2270, "text": "The Bokeh Python library, and libraries for Other Languages such as R, Scala, and Julia, primarily interacts with BokehJS at a high level. A Python programmer does not have to worry about JavaScript or web development. However, one can use BokehJS API, to do pure JavaScript development using BokehJS directly." }, { "code": null, "e": 2815, "s": 2581, "text": "BokehJS objects such as glyphs and widgets are built more or less similarly as in Bokeh Python API. Typically, any Python ClassName is available as Bokeh.ClassName from JavaScript. For example, a Range1d object as obtained in Python." }, { "code": null, "e": 2855, "s": 2815, "text": "xrange = Range1d(start=-0.5, end=20.5)\n" }, { "code": null, "e": 2901, "s": 2855, "text": "It is equivalently obtained with BokehJS as −" }, { "code": null, "e": 2962, "s": 2901, "text": "var xrange = new Bokeh.Range1d({ start: -0.5, end: 20.5 });\n" }, { "code": null, "e": 3060, "s": 2962, "text": "Following JavaScript code when embedded in a HTML file renders a simple line plot in the browser." }, { "code": null, "e": 3143, "s": 3060, "text": "First include all BokehJS libraries in <head>..</head> secion of web page as below" }, { "code": null, "e": 3802, "s": 3143, "text": "<head>\n<script type=\"text/javascript\" src=\"https://cdn.pydata.org/bokeh/release/bokeh-1.3.4.min.js\"></script>\n<script type=\"text/javascript\" src=\"https://cdn.pydata.org/bokeh/release/bokeh-widgets-1.3.4.min.js\"></script>\n<script type=\"text/javascript\" src=\"https://cdn.pydata.org/bokeh/release/bokeh-tables-1.3.4.min.js\"></script>\n<script type=\"text/javascript\" src=\"https://cdn.pydata.org/bokeh/release/bokeh-gl-1.3.4.min.js\"></script>\n<script type=\"text/javascript\" src=\"https://cdn.pydata.org/bokeh/release/bokeh-api-1.3.4.min.js\"></script>\n<script type=\"text/javascript\" src=\"https://cdn.pydata.org/bokeh/release/bokeh-api-1.3.4.min.js\"></script>\n</head>" }, { "code": null, "e": 3896, "s": 3802, "text": "In the body section following snippets of JavaScript construct various parts of a Bokeh Plot." }, { "code": null, "e": 4652, "s": 3896, "text": "<script>\n// create some data and a ColumnDataSource\nvar x = Bokeh.LinAlg.linspace(-0.5, 20.5, 10);\nvar y = x.map(function (v) { return v * 0.5 + 3.0; });\nvar source = new Bokeh.ColumnDataSource({ data: { x: x, y: y } });\n// make the plot\nvar plot = new Bokeh.Plot({\n title: \"BokehJS Plot\",\n plot_width: 400,\n plot_height: 400\n});\n\n// add axes to the plot\nvar xaxis = new Bokeh.LinearAxis({ axis_line_color: null });\nvar yaxis = new Bokeh.LinearAxis({ axis_line_color: null });\nplot.add_layout(xaxis, \"below\");\nplot.add_layout(yaxis, \"left\");\n\n// add a Line glyph\nvar line = new Bokeh.Line({\n x: { field: \"x\" },\n y: { field: \"y\" },\n line_color: \"#666699\",\n line_width: 2\n});\nplot.add_glyph(line, source);\n\nBokeh.Plotting.show(plot);\n</script>" }, { "code": null, "e": 4723, "s": 4652, "text": "Save above code as a web page and open it in a browser of your choice." }, { "code": null, "e": 4730, "s": 4723, "text": " Print" }, { "code": null, "e": 4741, "s": 4730, "text": " Add Notes" } ]
chattr command in Linux with examples - GeeksforGeeks
04 Aug, 2021 The chattr command in Linux is a file system command which is used for changing the attributes of a file in a directory. The primary use of this command is to make several files unable to alter for users other than the superuser. As we know Linux is a multi-user operating system, there exist a chance that a user can delete a file that is of much concern to another user, say the administrator. To avoid such kinds of scenarios, Linux provides ‘chattr‘. In short, ‘chattr’ can make a file immutable, undeletable, only appendable and many more! Synopsis: chattr [ -RVf ] [ -v version ] [ mode ] files... At the beginning of a mode string, one of the following operators must appear: ‘+‘ : Adding selected attributes to the existing attributes of the files. ‘–‘ : Causes selected attributes to be removed. ‘=‘ : Causes selected attributes to be the only attributes that the files have. The format of symbolic mode is: {+|-|=}[aAcCdDeijsStTu] Following are the list of common attributes and associated flags can be set/unset using the chattr command: A set : The atime record is not updated. S set : The changes are updated synchronously on the disk. a set : File can only be opened in append mode for writing. i set : File cannot be modified (immutable), the only superuser can unset the attribute. j set : All of files information is updated to the ext3 journal before being updated to the file itself. t set : No tail-merging is allowed. d set : No more candidate for backup when the dump process is run. u set : When such a file is deleted, its data is saved enabling the user to ask for its undeletion. All the commands above are however not qualified to files and can be used on directories (Folders) as well to secure a directory from deletion or any other analogous accidents. However, while securing a directory the flag -R’ is suggested to be used in order to recursively secure all the content in the specified directory. Below are the different options of chattr command: -R : It is used to display the list attributes of directories and their contents recursively. -V : It will display the version of the program. -a : Used to list all the files of a directory which also includes the whose name starts with a Period(‘.’). -d : This option will list the directories as regular files instead of listing their contents. -v : Used to display the file’s version/generation number etc. Use of chattr Command: The chattr’ can be used to preserve some system files that are very important and needs to remain in the host PC no matter what. Also to make a directory undeletable or unmodifiable for users other than superuser, this is necessary. The common use of ‘chattr’ is as below:- Making the file immutable: The command here made the file named file.txt immutable, hence now no operations are possible on this file until the attributes of the file are changed again.Opening the file only in append mode: The flag a’ is used to open the file only in append mode. Consequently, it can only be appended and the previous data can’t be modified.Making directories secured: The flag +i’ can be used for a directory(as shown below) to make the directory immutable. Also, the flag -R’ is used here, which makes the call recursive and all the subfiles and directories are made immutable as well. Making the file immutable: The command here made the file named file.txt immutable, hence now no operations are possible on this file until the attributes of the file are changed again. Opening the file only in append mode: The flag a’ is used to open the file only in append mode. Consequently, it can only be appended and the previous data can’t be modified. Making directories secured: The flag +i’ can be used for a directory(as shown below) to make the directory immutable. Also, the flag -R’ is used here, which makes the call recursive and all the subfiles and directories are made immutable as well. Note: lsattr command is used to see the attributes of files in a directory. Here, it should be noted that the e flag in the file is previously set and it means that the file is using extents for mapping blocks on the disk. The extents are filesystem dependent. They are seldom removable. kapoorsagar226 linux-command Linux-directory-commands 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 SED command in Linux | Set 2 mv command in Linux with examples 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": 25675, "s": 25647, "text": "\n04 Aug, 2021" }, { "code": null, "e": 26221, "s": 25675, "text": "The chattr command in Linux is a file system command which is used for changing the attributes of a file in a directory. The primary use of this command is to make several files unable to alter for users other than the superuser. As we know Linux is a multi-user operating system, there exist a chance that a user can delete a file that is of much concern to another user, say the administrator. To avoid such kinds of scenarios, Linux provides ‘chattr‘. In short, ‘chattr’ can make a file immutable, undeletable, only appendable and many more! " }, { "code": null, "e": 26232, "s": 26221, "text": "Synopsis: " }, { "code": null, "e": 26283, "s": 26234, "text": "chattr [ -RVf ] [ -v version ] [ mode ] files..." }, { "code": null, "e": 26363, "s": 26283, "text": "At the beginning of a mode string, one of the following operators must appear: " }, { "code": null, "e": 26439, "s": 26365, "text": "‘+‘ : Adding selected attributes to the existing attributes of the files." }, { "code": null, "e": 26487, "s": 26439, "text": "‘–‘ : Causes selected attributes to be removed." }, { "code": null, "e": 26567, "s": 26487, "text": "‘=‘ : Causes selected attributes to be the only attributes that the files have." }, { "code": null, "e": 26600, "s": 26567, "text": "The format of symbolic mode is: " }, { "code": null, "e": 26626, "s": 26602, "text": "{+|-|=}[aAcCdDeijsStTu]" }, { "code": null, "e": 26735, "s": 26626, "text": "Following are the list of common attributes and associated flags can be set/unset using the chattr command: " }, { "code": null, "e": 26778, "s": 26737, "text": "A set : The atime record is not updated." }, { "code": null, "e": 26837, "s": 26778, "text": "S set : The changes are updated synchronously on the disk." }, { "code": null, "e": 26897, "s": 26837, "text": "a set : File can only be opened in append mode for writing." }, { "code": null, "e": 26986, "s": 26897, "text": "i set : File cannot be modified (immutable), the only superuser can unset the attribute." }, { "code": null, "e": 27091, "s": 26986, "text": "j set : All of files information is updated to the ext3 journal before being updated to the file itself." }, { "code": null, "e": 27127, "s": 27091, "text": "t set : No tail-merging is allowed." }, { "code": null, "e": 27194, "s": 27127, "text": "d set : No more candidate for backup when the dump process is run." }, { "code": null, "e": 27294, "s": 27194, "text": "u set : When such a file is deleted, its data is saved enabling the user to ask for its undeletion." }, { "code": null, "e": 27620, "s": 27294, "text": "All the commands above are however not qualified to files and can be used on directories (Folders) as well to secure a directory from deletion or any other analogous accidents. However, while securing a directory the flag -R’ is suggested to be used in order to recursively secure all the content in the specified directory. " }, { "code": null, "e": 27672, "s": 27620, "text": "Below are the different options of chattr command: " }, { "code": null, "e": 27768, "s": 27674, "text": "-R : It is used to display the list attributes of directories and their contents recursively." }, { "code": null, "e": 27817, "s": 27768, "text": "-V : It will display the version of the program." }, { "code": null, "e": 27926, "s": 27817, "text": "-a : Used to list all the files of a directory which also includes the whose name starts with a Period(‘.’)." }, { "code": null, "e": 28021, "s": 27926, "text": "-d : This option will list the directories as regular files instead of listing their contents." }, { "code": null, "e": 28084, "s": 28021, "text": "-v : Used to display the file’s version/generation number etc." }, { "code": null, "e": 28382, "s": 28084, "text": "Use of chattr Command: The chattr’ can be used to preserve some system files that are very important and needs to remain in the host PC no matter what. Also to make a directory undeletable or unmodifiable for users other than superuser, this is necessary. The common use of ‘chattr’ is as below:- " }, { "code": null, "e": 28990, "s": 28384, "text": "Making the file immutable: The command here made the file named file.txt immutable, hence now no operations are possible on this file until the attributes of the file are changed again.Opening the file only in append mode: The flag a’ is used to open the file only in append mode. Consequently, it can only be appended and the previous data can’t be modified.Making directories secured: The flag +i’ can be used for a directory(as shown below) to make the directory immutable. Also, the flag -R’ is used here, which makes the call recursive and all the subfiles and directories are made immutable as well." }, { "code": null, "e": 29176, "s": 28990, "text": "Making the file immutable: The command here made the file named file.txt immutable, hence now no operations are possible on this file until the attributes of the file are changed again." }, { "code": null, "e": 29351, "s": 29176, "text": "Opening the file only in append mode: The flag a’ is used to open the file only in append mode. Consequently, it can only be appended and the previous data can’t be modified." }, { "code": null, "e": 29598, "s": 29351, "text": "Making directories secured: The flag +i’ can be used for a directory(as shown below) to make the directory immutable. Also, the flag -R’ is used here, which makes the call recursive and all the subfiles and directories are made immutable as well." }, { "code": null, "e": 29887, "s": 29598, "text": "Note: lsattr command is used to see the attributes of files in a directory. Here, it should be noted that the e flag in the file is previously set and it means that the file is using extents for mapping blocks on the disk. The extents are filesystem dependent. They are seldom removable. " }, { "code": null, "e": 29902, "s": 29887, "text": "kapoorsagar226" }, { "code": null, "e": 29916, "s": 29902, "text": "linux-command" }, { "code": null, "e": 29941, "s": 29916, "text": "Linux-directory-commands" }, { "code": null, "e": 29948, "s": 29941, "text": "Picked" }, { "code": null, "e": 29959, "s": 29948, "text": "Linux-Unix" }, { "code": null, "e": 30057, "s": 29959, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30092, "s": 30057, "text": "scp command in Linux with Examples" }, { "code": null, "e": 30118, "s": 30092, "text": "Docker - COPY Instruction" }, { "code": null, "e": 30147, "s": 30118, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 30181, "s": 30147, "text": "mv command in Linux with examples" }, { "code": null, "e": 30218, "s": 30181, "text": "chown command in Linux with Examples" }, { "code": null, "e": 30255, "s": 30218, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 30297, "s": 30255, "text": "Named Pipe or FIFO with example C program" }, { "code": null, "e": 30323, "s": 30297, "text": "Thread functions in C/C++" }, { "code": null, "e": 30359, "s": 30323, "text": "uniq Command in LINUX with examples" } ]
How do I find an element that contains specific text in Selenium Webdriver?
We can find an element with a specific text visible on the screen in Selenium. This is achieved with the xpath locator. The xpath locator contains some in-built functions that help to create customized xpath. Let us consider a portion of the web page as given below − text() − It is a built in function to identify an element based on the text displayed on the screen. For example, if we want to identify Library from the above webpage, the customized xpath with text() should be − text() − It is a built in function to identify an element based on the text displayed on the screen. For example, if we want to identify Library from the above webpage, the customized xpath with text() should be − Syntax //*[text()='Library'] contains() − It is a built in function to identify an element based on the partial text match. For example, if we want to identify GATE Exams from the above webpage, the customized xpath with contains() should be contains() − It is a built in function to identify an element based on the partial text match. For example, if we want to identify GATE Exams from the above webpage, the customized xpath with contains() should be Syntax //*[contains(text(),'GATE')] Code Implementation . import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import java.util.concurrent.TimeUnit; public class TextMatch{ public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); String url = "https://www.tutorialspoint.com/index.htm"; driver.get(url); driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS); // identify element with text() WebElement l=driver.findElement(By.xpath("//*[text()='Library']")); // identify element with contains() WebElement m=driver.findElement(By.xpath("//*[contains(text(),'GATE')]")); System.out.println("Element with text(): " + l.getText()); System.out.println("Element with contains(): " + m.getText()); driver.quit(); } }
[ { "code": null, "e": 1271, "s": 1062, "text": "We can find an element with a specific text visible on the screen in Selenium. This is achieved with the xpath locator. The xpath locator contains some in-built functions that help to create customized xpath." }, { "code": null, "e": 1330, "s": 1271, "text": "Let us consider a portion of the web page as given below −" }, { "code": null, "e": 1544, "s": 1330, "text": "text() − It is a built in function to identify an element based on the text displayed on the screen. For example, if we want to identify Library from the above webpage, the customized xpath with text() should be −" }, { "code": null, "e": 1758, "s": 1544, "text": "text() − It is a built in function to identify an element based on the text displayed on the screen. For example, if we want to identify Library from the above webpage, the customized xpath with text() should be −" }, { "code": null, "e": 1765, "s": 1758, "text": "Syntax" }, { "code": null, "e": 1787, "s": 1765, "text": "//*[text()='Library']" }, { "code": null, "e": 2000, "s": 1787, "text": "contains() − It is a built in function to identify an element based on the partial text match. For example, if we want to identify GATE Exams from the above webpage, the customized xpath with contains() should be" }, { "code": null, "e": 2213, "s": 2000, "text": "contains() − It is a built in function to identify an element based on the partial text match. For example, if we want to identify GATE Exams from the above webpage, the customized xpath with contains() should be" }, { "code": null, "e": 2220, "s": 2213, "text": "Syntax" }, { "code": null, "e": 2249, "s": 2220, "text": "//*[contains(text(),'GATE')]" }, { "code": null, "e": 2271, "s": 2249, "text": "Code Implementation ." }, { "code": null, "e": 3240, "s": 2271, "text": "import org.openqa.selenium.By;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.chrome.ChromeDriver;\nimport java.util.concurrent.TimeUnit;\npublic class TextMatch{\n public static void main(String[] args) {\n System.setProperty(\"webdriver.chrome.driver\", \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\chromedriver.exe\");\n WebDriver driver = new ChromeDriver();\n String url = \"https://www.tutorialspoint.com/index.htm\";\n driver.get(url);\n driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS);\n // identify element with text()\n WebElement l=driver.findElement(By.xpath(\"//*[text()='Library']\"));\n // identify element with contains()\n WebElement m=driver.findElement(By.xpath(\"//*[contains(text(),'GATE')]\"));\n System.out.println(\"Element with text(): \" + l.getText());\n System.out.println(\"Element with contains(): \" + m.getText());\n driver.quit();\n }\n}" } ]
Broadcasting Arrays with NumPy. Operations on arrays with different... | by Soner Yıldırım | Towards Data Science
NumPy is a scientific computing library for Python. It serves as a basis for many other libraries in data science domain such as Pandas. Whatever the format the raw data comes in, it must be converted to arrays of numbers for calculations and analysis. Hence, a fast, robust, and accurate calculations on arrays are required to perform efficient operations with data. NumPy is a predominant library for scientific computing since it offers the features we have just mentioned. In this article, we focus on a specific type of operation with NumPy which is broadcasting. Broadcasting describes how arrays with different shapes are handled during arithmetic operations. We will be going over examples to comprehend and practice the details of broadcasting. We first need to mention some structural properties of arrays. Dimension: Number of indices Shape: Size of array in each dimension Size: Total number of elements in an array. Size is calculated by multiplying sizes in each dimension. Let’s do a quick example. import numpy as nparr = np.random.randint(10, size=(3,4))arrarray([[7, 8, 9, 9], [6, 0, 2, 9], [3, 0, 8, 0]])arr.ndim2arr.shape(3,4)arr.size12 Arithmetic operations with NumPy are usually done element-wise. For instance, when we add two arrays, the elements in the same positions are added. a = np.array([1,2,3,4])b = np.array([1,1,1,1])a + barray([2, 3, 4, 5]) Since the operations are done element-wise, the arrays must have the same shape. Broadcasting allows for some flexibility on this condition so arithmetic operations can be done on arrays with different shapes. There are still some rules that must be satisfied. We cannot just broadcast any arrays. In the following examples, we will explore these rules and how broadcasting occurs. The simplest form of broadcasting occurs when we an array and a scalar are added. a = np.array([1,2,3,4])b = 1a + barray([2, 3, 4, 5]) The addition operation is done as if b was an array with 4 integers of 1. The illustrated stretching in the figure is only conceptual. NumPy does not actually make copies of the scalar to match the size of the array. Instead, the original scalar value is used in the addition. Thus, broadcasting operations are highly efficient in terms of memory and computation. We can also add a scalar to a higher dimensional array. In that case, broadcasting occurs in all axes. In the following example, we have a two-dimensional array with a shape of (3,4). The scalar is added to all the elements of the array. A = np.random.randint(5, size=(3, 4))B = 2print(A)print("--------")print(A + B)[[0 1 0 0] [0 2 4 3] [0 1 2 1]]--------[[2 3 2 2] [2 4 6 5] [2 3 4 3]] The broadcasting in this example occurs as follows: The rules of broadcasting We cannot just broadcast any arrays in an arithmetic operation. Broadcasting is applicable if dimensions of arrays are compatible. Two dimensions are compatible when: the sizes in each dimension are equal, orone of them is 1. the sizes in each dimension are equal, or one of them is 1. In other words, if the sizes in a dimension are not equal, one of them must be 1. Consider the following example. We have a couple of two-dimensional arrays. The sizes in the second dimension are equal. However, one of them has a size of 3 in the first dimension and the other one has a size of 1. Thus, the second array is broadcasted in the addition. Two arrays might have different sizes in both dimensions. In such case, the dimension with a size of 1 is broadcasted to match the largest size in that dimension. The following figure illustrates an example for this case. The shape of the first array is (4,1) and the second array is (1,4). The shape of the resulting array is (4,4) because broadcasting occurs in both dimensions. The broadcasting also occurs when doing arithmetic operations with more than two arrays. Same rules apply here too. The sizes in each dimension must be equal or 1. A = np.random.randint(5, size=(1,3,4))B = np.random.randint(5, size=(2,1,4))C = np.random.randint(5, size=(2,3,1)) All these arrays are three-dimensional. If a size in a particular dimension is different from the other arrays, it must be 1. If we add these three arrays together, the shape of the resulting array will be (2, 3, 4) because the dimension with a size of 1 is broadcasted to match the largest size in that dimension. print((A + B + C).shape)(2, 3, 4) We have introduced the idea of broadcasting in NumPy. It provides flexibility when performing arithmetic calculations with arrays. Broadcasting also makes certain operations more efficient in terms of memory and computation by preventing NumPy from making unnecessary copies of values. Thank you for reading. Please let me know if you have any feedback.
[ { "code": null, "e": 309, "s": 172, "text": "NumPy is a scientific computing library for Python. It serves as a basis for many other libraries in data science domain such as Pandas." }, { "code": null, "e": 540, "s": 309, "text": "Whatever the format the raw data comes in, it must be converted to arrays of numbers for calculations and analysis. Hence, a fast, robust, and accurate calculations on arrays are required to perform efficient operations with data." }, { "code": null, "e": 741, "s": 540, "text": "NumPy is a predominant library for scientific computing since it offers the features we have just mentioned. In this article, we focus on a specific type of operation with NumPy which is broadcasting." }, { "code": null, "e": 926, "s": 741, "text": "Broadcasting describes how arrays with different shapes are handled during arithmetic operations. We will be going over examples to comprehend and practice the details of broadcasting." }, { "code": null, "e": 989, "s": 926, "text": "We first need to mention some structural properties of arrays." }, { "code": null, "e": 1018, "s": 989, "text": "Dimension: Number of indices" }, { "code": null, "e": 1057, "s": 1018, "text": "Shape: Size of array in each dimension" }, { "code": null, "e": 1101, "s": 1057, "text": "Size: Total number of elements in an array." }, { "code": null, "e": 1186, "s": 1101, "text": "Size is calculated by multiplying sizes in each dimension. Let’s do a quick example." }, { "code": null, "e": 1341, "s": 1186, "text": "import numpy as nparr = np.random.randint(10, size=(3,4))arrarray([[7, 8, 9, 9], [6, 0, 2, 9], [3, 0, 8, 0]])arr.ndim2arr.shape(3,4)arr.size12" }, { "code": null, "e": 1489, "s": 1341, "text": "Arithmetic operations with NumPy are usually done element-wise. For instance, when we add two arrays, the elements in the same positions are added." }, { "code": null, "e": 1560, "s": 1489, "text": "a = np.array([1,2,3,4])b = np.array([1,1,1,1])a + barray([2, 3, 4, 5])" }, { "code": null, "e": 1770, "s": 1560, "text": "Since the operations are done element-wise, the arrays must have the same shape. Broadcasting allows for some flexibility on this condition so arithmetic operations can be done on arrays with different shapes." }, { "code": null, "e": 1942, "s": 1770, "text": "There are still some rules that must be satisfied. We cannot just broadcast any arrays. In the following examples, we will explore these rules and how broadcasting occurs." }, { "code": null, "e": 2024, "s": 1942, "text": "The simplest form of broadcasting occurs when we an array and a scalar are added." }, { "code": null, "e": 2077, "s": 2024, "text": "a = np.array([1,2,3,4])b = 1a + barray([2, 3, 4, 5])" }, { "code": null, "e": 2151, "s": 2077, "text": "The addition operation is done as if b was an array with 4 integers of 1." }, { "code": null, "e": 2441, "s": 2151, "text": "The illustrated stretching in the figure is only conceptual. NumPy does not actually make copies of the scalar to match the size of the array. Instead, the original scalar value is used in the addition. Thus, broadcasting operations are highly efficient in terms of memory and computation." }, { "code": null, "e": 2679, "s": 2441, "text": "We can also add a scalar to a higher dimensional array. In that case, broadcasting occurs in all axes. In the following example, we have a two-dimensional array with a shape of (3,4). The scalar is added to all the elements of the array." }, { "code": null, "e": 2829, "s": 2679, "text": "A = np.random.randint(5, size=(3, 4))B = 2print(A)print(\"--------\")print(A + B)[[0 1 0 0] [0 2 4 3] [0 1 2 1]]--------[[2 3 2 2] [2 4 6 5] [2 3 4 3]]" }, { "code": null, "e": 2881, "s": 2829, "text": "The broadcasting in this example occurs as follows:" }, { "code": null, "e": 2907, "s": 2881, "text": "The rules of broadcasting" }, { "code": null, "e": 3074, "s": 2907, "text": "We cannot just broadcast any arrays in an arithmetic operation. Broadcasting is applicable if dimensions of arrays are compatible. Two dimensions are compatible when:" }, { "code": null, "e": 3133, "s": 3074, "text": "the sizes in each dimension are equal, orone of them is 1." }, { "code": null, "e": 3175, "s": 3133, "text": "the sizes in each dimension are equal, or" }, { "code": null, "e": 3193, "s": 3175, "text": "one of them is 1." }, { "code": null, "e": 3275, "s": 3193, "text": "In other words, if the sizes in a dimension are not equal, one of them must be 1." }, { "code": null, "e": 3546, "s": 3275, "text": "Consider the following example. We have a couple of two-dimensional arrays. The sizes in the second dimension are equal. However, one of them has a size of 3 in the first dimension and the other one has a size of 1. Thus, the second array is broadcasted in the addition." }, { "code": null, "e": 3709, "s": 3546, "text": "Two arrays might have different sizes in both dimensions. In such case, the dimension with a size of 1 is broadcasted to match the largest size in that dimension." }, { "code": null, "e": 3927, "s": 3709, "text": "The following figure illustrates an example for this case. The shape of the first array is (4,1) and the second array is (1,4). The shape of the resulting array is (4,4) because broadcasting occurs in both dimensions." }, { "code": null, "e": 4091, "s": 3927, "text": "The broadcasting also occurs when doing arithmetic operations with more than two arrays. Same rules apply here too. The sizes in each dimension must be equal or 1." }, { "code": null, "e": 4206, "s": 4091, "text": "A = np.random.randint(5, size=(1,3,4))B = np.random.randint(5, size=(2,1,4))C = np.random.randint(5, size=(2,3,1))" }, { "code": null, "e": 4332, "s": 4206, "text": "All these arrays are three-dimensional. If a size in a particular dimension is different from the other arrays, it must be 1." }, { "code": null, "e": 4521, "s": 4332, "text": "If we add these three arrays together, the shape of the resulting array will be (2, 3, 4) because the dimension with a size of 1 is broadcasted to match the largest size in that dimension." }, { "code": null, "e": 4555, "s": 4521, "text": "print((A + B + C).shape)(2, 3, 4)" }, { "code": null, "e": 4686, "s": 4555, "text": "We have introduced the idea of broadcasting in NumPy. It provides flexibility when performing arithmetic calculations with arrays." }, { "code": null, "e": 4841, "s": 4686, "text": "Broadcasting also makes certain operations more efficient in terms of memory and computation by preventing NumPy from making unnecessary copies of values." } ]
Makefile - Directives
There are numerous directives available in various forms. The make program on your system may not support all the directives. So please check if your make supports the directives we are explaining here. GNU make supports these directives. The conditional directives are − The ifeq directive begins the conditional, and specifies the condition. It contains two arguments, separated by a comma and surrounded by parentheses. Variable substitution is performed on both arguments and then they are compared. The lines of the makefile following the ifeq are obeyed if the two arguments match; otherwise they are ignored. The ifeq directive begins the conditional, and specifies the condition. It contains two arguments, separated by a comma and surrounded by parentheses. Variable substitution is performed on both arguments and then they are compared. The lines of the makefile following the ifeq are obeyed if the two arguments match; otherwise they are ignored. The ifneq directive begins the conditional, and specifies the condition. It contains two arguments, separated by a comma and surrounded by parentheses. Variable substitution is performed on both arguments and then they are compared. The lines of the makefile following the ifneq are obeyed if the two arguments do not match; otherwise they are ignored. The ifneq directive begins the conditional, and specifies the condition. It contains two arguments, separated by a comma and surrounded by parentheses. Variable substitution is performed on both arguments and then they are compared. The lines of the makefile following the ifneq are obeyed if the two arguments do not match; otherwise they are ignored. The ifdef directive begins the conditional, and specifies the condition. It contains single argument. If the given argument is true then condition becomes true. The ifdef directive begins the conditional, and specifies the condition. It contains single argument. If the given argument is true then condition becomes true. The ifndef directive begins the conditional, and specifies the condition. It contains single argument. If the given argument is false then condition becomes true. The ifndef directive begins the conditional, and specifies the condition. It contains single argument. If the given argument is false then condition becomes true. The else directive causes the following lines to be obeyed if the previous conditional failed. In the example above this means the second alternative linking command is used whenever the first alternative is not used. It is optional to have an else in a conditional. The else directive causes the following lines to be obeyed if the previous conditional failed. In the example above this means the second alternative linking command is used whenever the first alternative is not used. It is optional to have an else in a conditional. The endif directive ends the conditional. Every conditional must end with an endif. The endif directive ends the conditional. Every conditional must end with an endif. The syntax of a simple conditional with no else is as follows − conditional-directive text-if-true endif The text-if-true may be any lines of text, to be considered as part of the makefile if the condition is true. If the condition is false, no text is used instead. The syntax of a complex conditional is as follows − conditional-directive text-if-true else text-if-false endif If the condition is true, text-if-true is used; otherwise, text-if-false is used. The text-if-false can be any number of lines of text. The syntax of the conditional-directive is the same whether the conditional is simple or complex. There are four different directives that test various conditions. They are as given − ifeq (arg1, arg2) ifeq 'arg1' 'arg2' ifeq "arg1" "arg2" ifeq "arg1" 'arg2' ifeq 'arg1' "arg2" Opposite directives of the above conditions are are follows − ifneq (arg1, arg2) ifneq 'arg1' 'arg2' ifneq "arg1" "arg2" ifneq "arg1" 'arg2' ifneq 'arg1' "arg2" libs_for_gcc = -lgnu normal_libs = foo: $(objects) ifeq ($(CC),gcc) $(CC) -o foo $(objects) $(libs_for_gcc) else $(CC) -o foo $(objects) $(normal_libs) endif The include directive allows make to suspend reading the current makefile and read one or more other makefiles before continuing. The directive is a line in the makefile that looks follows − include filenames... The filenames can contain shell file name patterns. Extra spaces are allowed and ignored at the beginning of the line, but a tab is not allowed. For example, if you have three `.mk' files, namely, `a.mk', `b.mk', and `c.mk', and $(bar) then it expands to bish bash, and then the following expression. include foo *.mk $(bar) is equivalent to: include foo a.mk b.mk c.mk bish bash When the make processes an include directive, it suspends reading of the makefile and reads from each listed file in turn. When that is finished, make resumes reading the makefile in which the directive appears. If a variable has been set with a command argument, then ordinary assignments in the makefile are ignored. If you want to set the variable in the makefile even though it was set with a command argument, you can use an override directive, which is a line that looks follows− override variable = value or override variable := value Print Add Notes Bookmark this page
[ { "code": null, "e": 2023, "s": 1784, "text": "There are numerous directives available in various forms. The make program on your system may not support all the directives. So please check if your make supports the directives we are explaining here. GNU make supports these directives." }, { "code": null, "e": 2056, "s": 2023, "text": "The conditional directives are −" }, { "code": null, "e": 2400, "s": 2056, "text": "The ifeq directive begins the conditional, and specifies the condition. It contains two arguments, separated by a comma and surrounded by parentheses. Variable substitution is performed on both arguments and then they are compared. The lines of the makefile following the ifeq are obeyed if the two arguments match; otherwise they are ignored." }, { "code": null, "e": 2744, "s": 2400, "text": "The ifeq directive begins the conditional, and specifies the condition. It contains two arguments, separated by a comma and surrounded by parentheses. Variable substitution is performed on both arguments and then they are compared. The lines of the makefile following the ifeq are obeyed if the two arguments match; otherwise they are ignored." }, { "code": null, "e": 3097, "s": 2744, "text": "The ifneq directive begins the conditional, and specifies the condition. It contains two arguments, separated by a comma and surrounded by parentheses. Variable substitution is performed on both arguments and then they are compared. The lines of the makefile following the ifneq are obeyed if the two arguments do not match; otherwise they are ignored." }, { "code": null, "e": 3450, "s": 3097, "text": "The ifneq directive begins the conditional, and specifies the condition. It contains two arguments, separated by a comma and surrounded by parentheses. Variable substitution is performed on both arguments and then they are compared. The lines of the makefile following the ifneq are obeyed if the two arguments do not match; otherwise they are ignored." }, { "code": null, "e": 3611, "s": 3450, "text": "The ifdef directive begins the conditional, and specifies the condition. It contains single argument. If the given argument is true then condition becomes true." }, { "code": null, "e": 3772, "s": 3611, "text": "The ifdef directive begins the conditional, and specifies the condition. It contains single argument. If the given argument is true then condition becomes true." }, { "code": null, "e": 3935, "s": 3772, "text": "The ifndef directive begins the conditional, and specifies the condition. It contains single argument. If the given argument is false then condition becomes true." }, { "code": null, "e": 4098, "s": 3935, "text": "The ifndef directive begins the conditional, and specifies the condition. It contains single argument. If the given argument is false then condition becomes true." }, { "code": null, "e": 4365, "s": 4098, "text": "The else directive causes the following lines to be obeyed if the previous conditional failed. In the example above this means the second alternative linking command is used whenever the first alternative is not used. It is optional to have an else in a conditional." }, { "code": null, "e": 4632, "s": 4365, "text": "The else directive causes the following lines to be obeyed if the previous conditional failed. In the example above this means the second alternative linking command is used whenever the first alternative is not used. It is optional to have an else in a conditional." }, { "code": null, "e": 4716, "s": 4632, "text": "The endif directive ends the conditional. Every conditional must end with an endif." }, { "code": null, "e": 4800, "s": 4716, "text": "The endif directive ends the conditional. Every conditional must end with an endif." }, { "code": null, "e": 4864, "s": 4800, "text": "The syntax of a simple conditional with no else is as follows −" }, { "code": null, "e": 4909, "s": 4864, "text": "conditional-directive\n text-if-true\nendif\n" }, { "code": null, "e": 5071, "s": 4909, "text": "The text-if-true may be any lines of text, to be considered as part of the makefile if the condition is true. If the condition is false, no text is used instead." }, { "code": null, "e": 5123, "s": 5071, "text": "The syntax of a complex conditional is as follows −" }, { "code": null, "e": 5190, "s": 5123, "text": "conditional-directive\n text-if-true\nelse\n text-if-false\nendif\n" }, { "code": null, "e": 5326, "s": 5190, "text": "If the condition is true, text-if-true is used; otherwise, text-if-false is used. The text-if-false can be any number of lines of text." }, { "code": null, "e": 5510, "s": 5326, "text": "The syntax of the conditional-directive is the same whether the conditional is simple or complex. There are four different directives that test various conditions. They are as given −" }, { "code": null, "e": 5606, "s": 5510, "text": "ifeq (arg1, arg2)\nifeq 'arg1' 'arg2'\nifeq \"arg1\" \"arg2\"\nifeq \"arg1\" 'arg2'\nifeq 'arg1' \"arg2\" \n" }, { "code": null, "e": 5668, "s": 5606, "text": "Opposite directives of the above conditions are are follows −" }, { "code": null, "e": 5769, "s": 5668, "text": "ifneq (arg1, arg2)\nifneq 'arg1' 'arg2'\nifneq \"arg1\" \"arg2\"\nifneq \"arg1\" 'arg2'\nifneq 'arg1' \"arg2\" \n" }, { "code": null, "e": 5934, "s": 5769, "text": "libs_for_gcc = -lgnu\nnormal_libs =\n\nfoo: $(objects)\nifeq ($(CC),gcc)\n $(CC) -o foo $(objects) $(libs_for_gcc)\nelse\n $(CC) -o foo $(objects) $(normal_libs)\nendif" }, { "code": null, "e": 6125, "s": 5934, "text": "The include directive allows make to suspend reading the current makefile and read one or more other makefiles before continuing. The directive is a line in the makefile that looks follows −" }, { "code": null, "e": 6147, "s": 6125, "text": "include filenames...\n" }, { "code": null, "e": 6448, "s": 6147, "text": "The filenames can contain shell file name patterns. Extra spaces are allowed and ignored at the beginning of the line, but a tab is not allowed. For example, if you have three `.mk' files, namely, `a.mk', `b.mk', and `c.mk', and $(bar) then it expands to bish bash, and then the following expression." }, { "code": null, "e": 6529, "s": 6448, "text": "include foo *.mk $(bar)\n\nis equivalent to:\n\ninclude foo a.mk b.mk c.mk bish bash" }, { "code": null, "e": 6741, "s": 6529, "text": "When the make processes an include directive, it suspends reading of the makefile and reads from each listed file in turn. When that is finished, make resumes reading the makefile in which the directive appears." }, { "code": null, "e": 7015, "s": 6741, "text": "If a variable has been set with a command argument, then ordinary assignments in the makefile are ignored. If you want to set the variable in the makefile even though it was set with a command argument, you can use an override directive, which is a line that looks follows−" }, { "code": null, "e": 7073, "s": 7015, "text": "override variable = value\n\nor\n\noverride variable := value" }, { "code": null, "e": 7080, "s": 7073, "text": " Print" }, { "code": null, "e": 7091, "s": 7080, "text": " Add Notes" } ]
Python | Remove prefix strings from list - GeeksforGeeks
29 Nov, 2019 Sometimes, while working with data, we can have a problem in which we need to filter the strings list in such a way that strings starting with specific prefix are removed. Let’s discuss certain ways in which this task can be performed. Method #1 : Using loop + remove() + startswith()The combination of above functions can solve this problem. In this, we remove the elements that start with particular prefix accessed using loop and return the modified list. # Python3 code to demonstrate working of# Remove prefix strings from list# using loop + remove() + startswith() # initialize list test_list = ['xall', 'xlove', 'gfg', 'xit', 'is', 'best'] # printing original list print("The original list : " + str(test_list)) # initialize prefix pref = 'x' # Remove prefix strings from list# using loop + remove() + startswith()for word in test_list[:]: if word.startswith(pref): test_list.remove(word) # printing resultprint("List after removal of Kth character of each string : " + str(test_list)) The original list : ['xall', 'xlove', 'gfg', 'xit', 'is', 'best'] List after removal of Kth character of each string : ['gfg', 'is', 'best'] Method #2 : Using list comprehension + startswith()This is another way in which this task can be performed. In this, we don’t perform removal in place, instead, we recreate the list without the elements that match the prefix. # Python3 code to demonstrate working of# Remove prefix strings from list# using list comprehension + startswith() # initialize list test_list = ['xall', 'xlove', 'gfg', 'xit', 'is', 'best'] # printing original list print("The original list : " + str(test_list)) # initialize prefix pref = 'x' # Remove prefix strings from list# using list comprehension + startswith()res = [ele for ele in test_list if not ele.startswith(pref)] # printing resultprint("List after removal of Kth character of each string : " + str(res)) The original list : ['xall', 'xlove', 'gfg', 'xit', 'is', 'best'] List after removal of Kth character of each string : ['gfg', 'is', 'best'] Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Read a file line by line in Python Enumerate() in Python Iterate over a list in Python How to Install PIP on Windows ? Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary
[ { "code": null, "e": 24593, "s": 24565, "text": "\n29 Nov, 2019" }, { "code": null, "e": 24829, "s": 24593, "text": "Sometimes, while working with data, we can have a problem in which we need to filter the strings list in such a way that strings starting with specific prefix are removed. Let’s discuss certain ways in which this task can be performed." }, { "code": null, "e": 25052, "s": 24829, "text": "Method #1 : Using loop + remove() + startswith()The combination of above functions can solve this problem. In this, we remove the elements that start with particular prefix accessed using loop and return the modified list." }, { "code": "# Python3 code to demonstrate working of# Remove prefix strings from list# using loop + remove() + startswith() # initialize list test_list = ['xall', 'xlove', 'gfg', 'xit', 'is', 'best'] # printing original list print(\"The original list : \" + str(test_list)) # initialize prefix pref = 'x' # Remove prefix strings from list# using loop + remove() + startswith()for word in test_list[:]: if word.startswith(pref): test_list.remove(word) # printing resultprint(\"List after removal of Kth character of each string : \" + str(test_list))", "e": 25601, "s": 25052, "text": null }, { "code": null, "e": 25743, "s": 25601, "text": "The original list : ['xall', 'xlove', 'gfg', 'xit', 'is', 'best']\nList after removal of Kth character of each string : ['gfg', 'is', 'best']\n" }, { "code": null, "e": 25971, "s": 25745, "text": "Method #2 : Using list comprehension + startswith()This is another way in which this task can be performed. In this, we don’t perform removal in place, instead, we recreate the list without the elements that match the prefix." }, { "code": "# Python3 code to demonstrate working of# Remove prefix strings from list# using list comprehension + startswith() # initialize list test_list = ['xall', 'xlove', 'gfg', 'xit', 'is', 'best'] # printing original list print(\"The original list : \" + str(test_list)) # initialize prefix pref = 'x' # Remove prefix strings from list# using list comprehension + startswith()res = [ele for ele in test_list if not ele.startswith(pref)] # printing resultprint(\"List after removal of Kth character of each string : \" + str(res))", "e": 26496, "s": 25971, "text": null }, { "code": null, "e": 26638, "s": 26496, "text": "The original list : ['xall', 'xlove', 'gfg', 'xit', 'is', 'best']\nList after removal of Kth character of each string : ['gfg', 'is', 'best']\n" }, { "code": null, "e": 26659, "s": 26638, "text": "Python list-programs" }, { "code": null, "e": 26666, "s": 26659, "text": "Python" }, { "code": null, "e": 26682, "s": 26666, "text": "Python Programs" }, { "code": null, "e": 26780, "s": 26682, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26789, "s": 26780, "text": "Comments" }, { "code": null, "e": 26802, "s": 26789, "text": "Old Comments" }, { "code": null, "e": 26820, "s": 26802, "text": "Python Dictionary" }, { "code": null, "e": 26855, "s": 26820, "text": "Read a file line by line in Python" }, { "code": null, "e": 26877, "s": 26855, "text": "Enumerate() in Python" }, { "code": null, "e": 26907, "s": 26877, "text": "Iterate over a list in Python" }, { "code": null, "e": 26939, "s": 26907, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26982, "s": 26939, "text": "Python program to convert a list to string" }, { "code": null, "e": 27004, "s": 26982, "text": "Defaultdict in Python" }, { "code": null, "e": 27043, "s": 27004, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 27089, "s": 27043, "text": "Python | Split string into list of characters" } ]
Add an element to a Stack in Java
An element can be added into the stack by using the java.util.Stack.push() method. This method pushes the required element to the top of the stack. The only parameter required for the Stack.push() method is the element that is to be pushed into the stack. A program that demonstrates this is given as follows − Live Demo import java.util.Stack; public class Demo { public static void main (String args[]) { Stack stack = new Stack(); stack.push("Apple"); stack.push("Mango"); stack.push("Guava"); stack.push("Pear"); stack.push("Orange"); System.out.println("The stack elements are: " + stack); } } The stack elements are: [Apple, Mango, Guava, Pear, Orange] Now let us understand the above program. The Stack is created. Then Stack.push() method is used to add the elements to the stack. Finally the stack is displayed. A code snippet which demonstrates this is as follows − Stack stack = new Stack(); stack.push("Apple"); stack.push("Mango"); stack.push("Guava"); stack.push("Pear"); stack.push("Orange"); System.out.println("The stack elements are: " + stack);
[ { "code": null, "e": 1318, "s": 1062, "text": "An element can be added into the stack by using the java.util.Stack.push() method. This method pushes the required element to the top of the stack. The only parameter required for the Stack.push() method is the element that is to be pushed into the stack." }, { "code": null, "e": 1373, "s": 1318, "text": "A program that demonstrates this is given as follows −" }, { "code": null, "e": 1384, "s": 1373, "text": " Live Demo" }, { "code": null, "e": 1710, "s": 1384, "text": "import java.util.Stack;\npublic class Demo {\n public static void main (String args[]) {\n Stack stack = new Stack();\n stack.push(\"Apple\");\n stack.push(\"Mango\");\n stack.push(\"Guava\");\n stack.push(\"Pear\");\n stack.push(\"Orange\");\n System.out.println(\"The stack elements are: \" + stack);\n }\n}" }, { "code": null, "e": 1770, "s": 1710, "text": "The stack elements are: [Apple, Mango, Guava, Pear, Orange]" }, { "code": null, "e": 1811, "s": 1770, "text": "Now let us understand the above program." }, { "code": null, "e": 1987, "s": 1811, "text": "The Stack is created. Then Stack.push() method is used to add the elements to the stack. Finally the stack is displayed. A code snippet which demonstrates this is as follows −" }, { "code": null, "e": 2175, "s": 1987, "text": "Stack stack = new Stack();\nstack.push(\"Apple\");\nstack.push(\"Mango\");\nstack.push(\"Guava\");\nstack.push(\"Pear\");\nstack.push(\"Orange\");\nSystem.out.println(\"The stack elements are: \" + stack);" } ]
Kepler.GL & Jupyter Notebooks: Geospatial Data Visualization with Uber’s opensource Kepler.GL | by Abdishakur | Towards Data Science
kepler.gl for Jupyter is an excellent tool for big Geospatial data visualisation. Combine world-class visualisation tool, easy to use User interface (UI), and flexibility of python and Jupyter notebooks (3D Visualization GIF below, more in the article). kepler.gl is a web-based visualisation tool for large Geospatial datasets built on top of deck.gl. Uber made it an open-source last year, and its functionality is impressive. You can easily drag and drop your dataset and tweak it immediately on the web to visualise large scale geospatial datasets with ease. Have a look at this GIF below showcasing Kepler web-application. I love working in Jupyter Notebook, and the same functionality of Kepler.gl is available in a Jupyter Notebook environment. In this tutorial, I highlight how you can incorporate kepler.gl for Jupyter visualisation tool inside your notebook. The advantage of using Kepler Jupyter notebook is that you get both the flexibility of Jupyter Notebooks as Kepler’s great visualisation tools. The dataset we use for this tutorial comes from NYC Open Data Portal. It is all incidents reported in New York in 2018. import pandas as pdfrom keplergl import KeplerGlimport geopandas as gpddf = gpd.read_file("NYPD_complaints_2018.csv")df.head() The first few rows of the dataset are below. Incident data, category and the coordinates of the incident place are among the columns available in this dataset. To plot your data with Kepler, you first need to create a map. Let us do that with just one line of code. #Create a basemap map = KeplerGl(height=600, width=800)#show the mapmap The default map, with a dark base map, appears in the notebook. You can easily change that if you want. Now, let us add our data to the map. The easiest way to directly add your data to Kepler.gl is to convert it to a Geodataframe, and that we can do quickly with Geopandas. # Create a gepdataframegdf = gpd.GeoDataFrame(df, geometry=gpd.points_from_xy(df.Longitude, df.Latitude))# Add data to Keplermap.add_data(data=gdf, name=”crimes”) We added the data to the first map we created ( You can call again map to display in the cell below, but that is not necessary). The points appear on top of the base map created above. The map has many points and is messy. Let us do some tweaking. Following is the fun part, you can tweak the type of visualisation, the colour and size easily with Kepler’s User interface. Let us change the colours and size of the map ( See GIF below). We have shown above only one way of visualising and that typically depends on the dataset at hand. However, the following are the functionalities available in Kepler.gl now (See the picture below). You can visualise your data as Point, Hexagon, Heatmap, Arc or line with line data and Buildings visualisation with 3D availability. Let us cover some more data visualisation (See Hexagon visualisation below GIF). Kepler automatically counts each hexagon and visualises it. See how periphery areas have fewer incidents from the map below. Another great tool in Kepler.gl Jupyter notebook is the in-built time-series animations. The beauty of this is that you get the Kepler’s functionality without leaving Jupyter notebook. Let us say we are interested in aggregating the data into neighbourhoods. I download the neighbourhood file and perform a simple spatial join to count out how many incidents are within each neighbourhood. I have a created a function that does that: spatial join, group by and then return a Geodataframe. def count_incidents_neighborhood(data, neighb): # spatial join and group by to get count of incidents in each poneighbourhood joined = gpd.sjoin(gdf, neighb, op=”within”) grouped = joined.groupby(‘ntaname’).size() df = grouped.to_frame().reset_index() df.columns = [‘ntaname’, ‘count’] merged = Neighborhood.merge(df, on=’ntaname’, how=’outer’) merged[‘count’].fillna(0,inplace=True) merged[‘count’] = merged[‘count’].astype(int) return mergedmerged_gdf = count_incidents_neighborhood(gdf, Neighborhood) Once we have the data we want to map, we can create a Kepler Map. Let us do this in a separate map; we call it map2. We add the data we have just created to visualise it. map2 = KeplerGl(height=600, width=800)# Add data to Keplermap2.add_data(data=merged_gdf, name=”NeighborhoodCrimes”)map2 And here is the initial map and how you can tweak it. Kepler also has handy 3D visualisation. Here is an example using San Fransisco open data for building footprints. To Install Keplergl Jupyter notebook, just run these three lines on your terminal. pip install ipywidgetspip install keplergljupyter nbextension install --py --sys-prefix keplergl We have covered some use case of Kepler.gl Jupyter notebook to visualise Geospatial data. I find this tool very useful as it offers an impressive functionality within Jupyter notebook. Experiment with it and let me know if you give it a try.
[ { "code": null, "e": 426, "s": 172, "text": "kepler.gl for Jupyter is an excellent tool for big Geospatial data visualisation. Combine world-class visualisation tool, easy to use User interface (UI), and flexibility of python and Jupyter notebooks (3D Visualization GIF below, more in the article)." }, { "code": null, "e": 800, "s": 426, "text": "kepler.gl is a web-based visualisation tool for large Geospatial datasets built on top of deck.gl. Uber made it an open-source last year, and its functionality is impressive. You can easily drag and drop your dataset and tweak it immediately on the web to visualise large scale geospatial datasets with ease. Have a look at this GIF below showcasing Kepler web-application." }, { "code": null, "e": 1041, "s": 800, "text": "I love working in Jupyter Notebook, and the same functionality of Kepler.gl is available in a Jupyter Notebook environment. In this tutorial, I highlight how you can incorporate kepler.gl for Jupyter visualisation tool inside your notebook." }, { "code": null, "e": 1185, "s": 1041, "text": "The advantage of using Kepler Jupyter notebook is that you get both the flexibility of Jupyter Notebooks as Kepler’s great visualisation tools." }, { "code": null, "e": 1305, "s": 1185, "text": "The dataset we use for this tutorial comes from NYC Open Data Portal. It is all incidents reported in New York in 2018." }, { "code": null, "e": 1432, "s": 1305, "text": "import pandas as pdfrom keplergl import KeplerGlimport geopandas as gpddf = gpd.read_file(\"NYPD_complaints_2018.csv\")df.head()" }, { "code": null, "e": 1592, "s": 1432, "text": "The first few rows of the dataset are below. Incident data, category and the coordinates of the incident place are among the columns available in this dataset." }, { "code": null, "e": 1698, "s": 1592, "text": "To plot your data with Kepler, you first need to create a map. Let us do that with just one line of code." }, { "code": null, "e": 1770, "s": 1698, "text": "#Create a basemap map = KeplerGl(height=600, width=800)#show the mapmap" }, { "code": null, "e": 1874, "s": 1770, "text": "The default map, with a dark base map, appears in the notebook. You can easily change that if you want." }, { "code": null, "e": 2045, "s": 1874, "text": "Now, let us add our data to the map. The easiest way to directly add your data to Kepler.gl is to convert it to a Geodataframe, and that we can do quickly with Geopandas." }, { "code": null, "e": 2208, "s": 2045, "text": "# Create a gepdataframegdf = gpd.GeoDataFrame(df, geometry=gpd.points_from_xy(df.Longitude, df.Latitude))# Add data to Keplermap.add_data(data=gdf, name=”crimes”)" }, { "code": null, "e": 2393, "s": 2208, "text": "We added the data to the first map we created ( You can call again map to display in the cell below, but that is not necessary). The points appear on top of the base map created above." }, { "code": null, "e": 2456, "s": 2393, "text": "The map has many points and is messy. Let us do some tweaking." }, { "code": null, "e": 2645, "s": 2456, "text": "Following is the fun part, you can tweak the type of visualisation, the colour and size easily with Kepler’s User interface. Let us change the colours and size of the map ( See GIF below)." }, { "code": null, "e": 2976, "s": 2645, "text": "We have shown above only one way of visualising and that typically depends on the dataset at hand. However, the following are the functionalities available in Kepler.gl now (See the picture below). You can visualise your data as Point, Hexagon, Heatmap, Arc or line with line data and Buildings visualisation with 3D availability." }, { "code": null, "e": 3182, "s": 2976, "text": "Let us cover some more data visualisation (See Hexagon visualisation below GIF). Kepler automatically counts each hexagon and visualises it. See how periphery areas have fewer incidents from the map below." }, { "code": null, "e": 3271, "s": 3182, "text": "Another great tool in Kepler.gl Jupyter notebook is the in-built time-series animations." }, { "code": null, "e": 3572, "s": 3271, "text": "The beauty of this is that you get the Kepler’s functionality without leaving Jupyter notebook. Let us say we are interested in aggregating the data into neighbourhoods. I download the neighbourhood file and perform a simple spatial join to count out how many incidents are within each neighbourhood." }, { "code": null, "e": 3671, "s": 3572, "text": "I have a created a function that does that: spatial join, group by and then return a Geodataframe." }, { "code": null, "e": 4176, "s": 3671, "text": "def count_incidents_neighborhood(data, neighb): # spatial join and group by to get count of incidents in each poneighbourhood joined = gpd.sjoin(gdf, neighb, op=”within”) grouped = joined.groupby(‘ntaname’).size() df = grouped.to_frame().reset_index() df.columns = [‘ntaname’, ‘count’] merged = Neighborhood.merge(df, on=’ntaname’, how=’outer’) merged[‘count’].fillna(0,inplace=True) merged[‘count’] = merged[‘count’].astype(int) return mergedmerged_gdf = count_incidents_neighborhood(gdf, Neighborhood)" }, { "code": null, "e": 4347, "s": 4176, "text": "Once we have the data we want to map, we can create a Kepler Map. Let us do this in a separate map; we call it map2. We add the data we have just created to visualise it." }, { "code": null, "e": 4467, "s": 4347, "text": "map2 = KeplerGl(height=600, width=800)# Add data to Keplermap2.add_data(data=merged_gdf, name=”NeighborhoodCrimes”)map2" }, { "code": null, "e": 4521, "s": 4467, "text": "And here is the initial map and how you can tweak it." }, { "code": null, "e": 4635, "s": 4521, "text": "Kepler also has handy 3D visualisation. Here is an example using San Fransisco open data for building footprints." }, { "code": null, "e": 4718, "s": 4635, "text": "To Install Keplergl Jupyter notebook, just run these three lines on your terminal." }, { "code": null, "e": 4815, "s": 4718, "text": "pip install ipywidgetspip install keplergljupyter nbextension install --py --sys-prefix keplergl" } ]
GCD of two numbers | Practice | GeeksforGeeks
Given two positive integers A and B, find GCD of A and B. Example 1: Input: A = 3, B = 6 Output: 3 Explanation: GCD of 3 and 6 is 3 Example 2: Input: A = 1, B = 1 Output: 1 Explanation: GCD of 1 and 1 is 1 Your Task: You don't need to read input or print anything. Complete the function gcd() which takes two positive integers as input parameters and returns an integer. Expected Time Complexity: O(log(min(A, B))) Expected Auxiliary Space: O(1) Constraints: 1 ≤ A, B ≤ 109 +1 rapuritejain 10 hours class Solution: def gcd(self, A, B): if B== 0: return A else: return (ob.gcd(B,A%B)) 0 rsbly7300951 week ago Javascript solution class Solution{ gcd(A , B) { if (B === 0) return A; let a = this.gcd(B, A % B); return a; } } 0 mankesh0161 week ago return (A%B)? gcd(B,A%B) : B; 0 mainakdeykol1 week ago class Solution { public int gcd(int A , int B) { //code here if(A==B) return A; if(A>B){ return gcd(A-B,B); } return gcd(A,B-A); } } 0 abhigyanpatek2 weeks ago Simple C++ O(log min(A,B)): int gcd(int A, int B) { while(A%B != 0){ int temp = A%B; A = B; B = temp; } return B;} 0 abhinav904442 weeks ago // { Driver Code Starts#include <bits/stdc++.h>using namespace std; // } Driver Code Ends//User function Template for C++class Solution{public: int gcd(int A, int B) { // code here if (B==0) return A; return gcd(B,A%B); } }; // { Driver Code Starts. int main() { int t; cin >> t; while (t--) { int A, B; cin >> A >> B; Solution ob; cout << ob.gcd(A, B) << "\n"; } return 0;} // } Driver Code Ends +3 kartikeyashokgautam3 weeks ago JAVA Solution :- public int gcd(int A , int B) { if(A==0) return B; if(B==0) return A; if(A==B) return A; if (A > B) return gcd(A-B, B); return gcd(A, B-A); } 0 mail2rajab011 month ago // Simple Java Solution Total Time Taken: 0.2/1.3 class Solution{ public int gcd(int A , int B) { //code here if(B==0) return A; return gcd(B,A%B); } } 0 0niharika22 months ago if(B==0) return A; return gcd(B,A%B); 0 ankitparashxr2 months ago java if(b==0) { return a; } return gcd(b,a%b); We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 296, "s": 238, "text": "Given two positive integers A and B, find GCD of A and B." }, { "code": null, "e": 308, "s": 296, "text": "\nExample 1:" }, { "code": null, "e": 371, "s": 308, "text": "Input: A = 3, B = 6\nOutput: 3\nExplanation: GCD of 3 and 6 is 3" }, { "code": null, "e": 383, "s": 371, "text": "\nExample 2:" }, { "code": null, "e": 446, "s": 383, "text": "Input: A = 1, B = 1\nOutput: 1\nExplanation: GCD of 1 and 1 is 1" }, { "code": null, "e": 614, "s": 446, "text": "\nYour Task: \nYou don't need to read input or print anything. Complete the function gcd() which takes two positive integers as input parameters and returns an integer." }, { "code": null, "e": 691, "s": 614, "text": "\nExpected Time Complexity: O(log(min(A, B)))\nExpected Auxiliary Space: O(1) " }, { "code": null, "e": 720, "s": 691, "text": "\nConstraints:\n1 ≤ A, B ≤ 109" }, { "code": null, "e": 723, "s": 720, "text": "+1" }, { "code": null, "e": 745, "s": 723, "text": "rapuritejain 10 hours" }, { "code": null, "e": 864, "s": 745, "text": "class Solution: def gcd(self, A, B): if B== 0: return A else: return (ob.gcd(B,A%B))" }, { "code": null, "e": 866, "s": 864, "text": "0" }, { "code": null, "e": 888, "s": 866, "text": "rsbly7300951 week ago" }, { "code": null, "e": 908, "s": 888, "text": "Javascript solution" }, { "code": null, "e": 1030, "s": 908, "text": "class Solution{ gcd(A , B) { if (B === 0) return A; let a = this.gcd(B, A % B); return a;" }, { "code": null, "e": 1039, "s": 1030, "text": " } }" }, { "code": null, "e": 1041, "s": 1039, "text": "0" }, { "code": null, "e": 1062, "s": 1041, "text": "mankesh0161 week ago" }, { "code": null, "e": 1092, "s": 1062, "text": "return (A%B)? gcd(B,A%B) : B;" }, { "code": null, "e": 1094, "s": 1092, "text": "0" }, { "code": null, "e": 1117, "s": 1094, "text": "mainakdeykol1 week ago" }, { "code": null, "e": 1308, "s": 1117, "text": "class Solution\n{\n public int gcd(int A , int B) \n { \n //code here\n if(A==B) return A;\n if(A>B){\n return gcd(A-B,B);\n }\n return gcd(A,B-A);\n } \n}" }, { "code": null, "e": 1310, "s": 1308, "text": "0" }, { "code": null, "e": 1335, "s": 1310, "text": "abhigyanpatek2 weeks ago" }, { "code": null, "e": 1363, "s": 1335, "text": "Simple C++ O(log min(A,B)):" }, { "code": null, "e": 1493, "s": 1363, "text": "int gcd(int A, int B) { while(A%B != 0){ int temp = A%B; A = B; B = temp; } return B;}" }, { "code": null, "e": 1495, "s": 1493, "text": "0" }, { "code": null, "e": 1519, "s": 1495, "text": "abhinav904442 weeks ago" }, { "code": null, "e": 1587, "s": 1519, "text": "// { Driver Code Starts#include <bits/stdc++.h>using namespace std;" }, { "code": null, "e": 1766, "s": 1587, "text": "// } Driver Code Ends//User function Template for C++class Solution{public: int gcd(int A, int B) { // code here if (B==0) return A; return gcd(B,A%B); } };" }, { "code": null, "e": 1791, "s": 1766, "text": "// { Driver Code Starts." }, { "code": null, "e": 1976, "s": 1791, "text": "int main() { int t; cin >> t; while (t--) { int A, B; cin >> A >> B; Solution ob; cout << ob.gcd(A, B) << \"\\n\"; } return 0;} // } Driver Code Ends" }, { "code": null, "e": 1979, "s": 1976, "text": "+3" }, { "code": null, "e": 2010, "s": 1979, "text": "kartikeyashokgautam3 weeks ago" }, { "code": null, "e": 2027, "s": 2010, "text": "JAVA Solution :-" }, { "code": null, "e": 2272, "s": 2027, "text": " public int gcd(int A , int B) { if(A==0) return B; if(B==0) return A; if(A==B) return A; if (A > B) return gcd(A-B, B); return gcd(A, B-A); } " }, { "code": null, "e": 2274, "s": 2272, "text": "0" }, { "code": null, "e": 2298, "s": 2274, "text": "mail2rajab011 month ago" }, { "code": null, "e": 2322, "s": 2298, "text": "// Simple Java Solution" }, { "code": null, "e": 2348, "s": 2322, "text": "Total Time Taken: 0.2/1.3" }, { "code": null, "e": 2499, "s": 2350, "text": "class Solution{ public int gcd(int A , int B) { //code here if(B==0) return A; return gcd(B,A%B); } }" }, { "code": null, "e": 2501, "s": 2499, "text": "0" }, { "code": null, "e": 2524, "s": 2501, "text": "0niharika22 months ago" }, { "code": null, "e": 2572, "s": 2524, "text": "if(B==0) return A; return gcd(B,A%B);" }, { "code": null, "e": 2574, "s": 2572, "text": "0" }, { "code": null, "e": 2600, "s": 2574, "text": "ankitparashxr2 months ago" }, { "code": null, "e": 2605, "s": 2600, "text": "java" }, { "code": null, "e": 2675, "s": 2605, "text": "if(b==0) { return a; } return gcd(b,a%b);" }, { "code": null, "e": 2821, "s": 2675, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 2857, "s": 2821, "text": " Login to access your submissions. " }, { "code": null, "e": 2867, "s": 2857, "text": "\nProblem\n" }, { "code": null, "e": 2877, "s": 2867, "text": "\nContest\n" }, { "code": null, "e": 2940, "s": 2877, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 3088, "s": 2940, "text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 3296, "s": 3088, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints." }, { "code": null, "e": 3402, "s": 3296, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Number of lines from given N points not parallel to X or Y axis - GeeksforGeeks
24 Nov, 2021 Given N distinct integers points on 2D Plane. The task is to count the number of lines which are formed from given N points and not parallel to X or Y-axis. Examples: Input: points[][] = {{1, 2}, {1, 5}, {1, 15}, {2, 10}} Output: 3 Chosen pairs are {(1, 2), (2, 10)}, {(1, 5), (2, 10)}, {(1, 15), (2, 10)}. Input: points[][] = {{1, 2}, {2, 5}, {3, 15}} Output: 3 Choose any pair of points. Approach: We know that Line formed by connecting any two-points will be parallel to X-axis if they have the same Y coordinatesIt will be parallel to Y-axis if they have the same X coordinates.Total number of line segments that can formed from N points = Now we will exclude those line segments which are parallel to the X-axis or the Y-axis.For each X coordinate and Y coordinate, calculate the number of points and exclude those line segments at the end. We know that Line formed by connecting any two-points will be parallel to X-axis if they have the same Y coordinatesIt will be parallel to Y-axis if they have the same X coordinates. Line formed by connecting any two-points will be parallel to X-axis if they have the same Y coordinates It will be parallel to Y-axis if they have the same X coordinates. Total number of line segments that can formed from N points = Now we will exclude those line segments which are parallel to the X-axis or the Y-axis. For each X coordinate and Y coordinate, calculate the number of points and exclude those line segments at the end. Below is the implementation of above approach: C++ Java C# Python3 Javascript // C++ program to find the number// of lines which are formed from// given N points and not parallel// to X or Y axis #include <bits/stdc++.h>using namespace std; // Function to find the number of lines// which are formed from given N points// and not parallel to X or Y axisint NotParallel(int p[][2], int n){ // This will store the number of points has // same x or y coordinates using the map as // the value of coordinate can be very large map<int, int> x_axis, y_axis; for (int i = 0; i < n; i++) { // Counting frequency of each x and y // coordinates x_axis[p[i][0]]++; y_axis[p[i][1]]++; } // Total number of pairs can be formed int total = (n * (n - 1)) / 2; for (auto i : x_axis) { int c = i.second; // We can not choose pairs from these as // they have same x coordinatethus they // will result line segment // parallel to y axis total -= (c * (c - 1)) / 2; } for (auto i : y_axis) { int c = i.second; // we can not choose pairs from these as // they have same y coordinate thus they // will result line segment // parallel to x-axis total -= (c * (c - 1)) / 2; } // Return the required answer return total;} // Driver Codeint main(){ int p[][2] = { { 1, 2 }, { 1, 5 }, { 1, 15 }, { 2, 10 } }; int n = sizeof(p) / sizeof(p[0]); // Function call cout << NotParallel(p, n); return 0;} // Java program to find the number// of lines which are formed from// given N points and not parallel// to X or Y axisimport java.util.*; class GFG{ // Function to find the number of lines// which are formed from given N points// and not parallel to X or Y axisstatic int NotParallel(int p[][], int n){ // This will store the number of points has // same x or y coordinates using the map as // the value of coordinate can be very large HashMap<Integer,Integer> x_axis = new HashMap<Integer,Integer>(); HashMap<Integer,Integer> y_axis = new HashMap<Integer,Integer>(); for (int i = 0; i < n; i++) { // Counting frequency of each x and y // coordinates if(x_axis.containsKey(p[i][0])) x_axis.put(p[i][0], x_axis.get(p[i][0])+1); else x_axis.put(p[i][0], 1); if(y_axis.containsKey(p[i][1])) y_axis.put(p[i][1], y_axis.get(p[i][1])+1); else y_axis.put(p[i][1], 1); } // Total number of pairs can be formed int total = (n * (n - 1)) / 2; for (Map.Entry<Integer,Integer> i : x_axis.entrySet()) { int c = i.getValue(); // We can not choose pairs from these as // they have same x coordinatethus they // will result line segment // parallel to y axis total -= (c * (c - 1)) / 2; } for (Map.Entry<Integer,Integer> i : y_axis.entrySet()) { int c = i.getValue(); // we can not choose pairs from these as // they have same y coordinate thus they // will result line segment // parallel to x-axis total -= (c * (c - 1)) / 2; } // Return the required answer return total;} // Driver Codepublic static void main(String[] args){ int p[][] = { { 1, 2 }, { 1, 5 }, { 1, 15 }, { 2, 10 } }; int n = p.length; // Function call System.out.print(NotParallel(p, n)); }} // This code is contributed by PrinciRaj1992 // C# program to find the number// of lines which are formed from// given N points and not parallel// to X or Y axisusing System;using System.Collections.Generic; class GFG{ // Function to find the number of lines// which are formed from given N points// and not parallel to X or Y axisstatic int NotParallel(int [,]p, int n){ // This will store the number of points has // same x or y coordinates using the map as // the value of coordinate can be very large Dictionary<int,int> x_axis = new Dictionary<int,int>(); Dictionary<int,int> y_axis = new Dictionary<int,int>(); for (int i = 0; i < n; i++) { // Counting frequency of each x and y // coordinates if(x_axis.ContainsKey(p[i, 0])) x_axis[p[i, 0]] = x_axis[p[i, 0]] + 1; else x_axis.Add(p[i, 0], 1); if(y_axis.ContainsKey(p[i, 1])) y_axis[p[i, 1]] = y_axis[p[i, 1]] + 1; else y_axis.Add(p[i, 1], 1); } // Total number of pairs can be formed int total = (n * (n - 1)) / 2; foreach (KeyValuePair<int,int> i in x_axis) { int c = i.Value; // We can not choose pairs from these as // they have same x coordinatethus they // will result line segment // parallel to y axis total -= (c * (c - 1)) / 2; } foreach (KeyValuePair<int,int> i in y_axis) { int c = i.Value; // we can not choose pairs from these as // they have same y coordinate thus they // will result line segment // parallel to x-axis total -= (c * (c - 1)) / 2; } // Return the required answer return total;} // Driver Codepublic static void Main(String[] args){ int [,]p = { { 1, 2 }, { 1, 5 }, { 1, 15 }, { 2, 10 } }; int n = p.GetLength(0); // Function call Console.Write(NotParallel(p, n)); }} // This code is contributed by Princi Singh # Python3 program to find the number# of lines which are formed from# given N points and not parallel# to X or Y axis # Function to find the number of lines# which are formed from given N points# and not parallel to X or Y axisdef NotParallel(p, n) : # This will store the number of points has # same x or y coordinates using the map as # the value of coordinate can be very large x_axis = {}; y_axis = {}; for i in range(n) : # Counting frequency of each x and y # coordinates if p[i][0] not in x_axis : x_axis[p[i][0]] = 0; x_axis[p[i][0]] += 1; if p[i][1] not in y_axis : y_axis[p[i][1]] = 0; y_axis[p[i][1]] += 1; # Total number of pairs can be formed total = (n * (n - 1)) // 2; for i in x_axis : c = x_axis[i]; # We can not choose pairs from these as # they have same x coordinatethus they # will result line segment # parallel to y axis total -= (c * (c - 1)) // 2; for i in y_axis : c = y_axis[i]; # we can not choose pairs from these as # they have same y coordinate thus they # will result line segment # parallel to x-axis total -= (c * (c - 1)) // 2; # Return the required answer return total; # Driver Codeif __name__ == "__main__" : p = [ [ 1, 2 ], [1, 5 ], [1, 15 ], [ 2, 10 ] ]; n = len(p); # Function call print(NotParallel(p, n)); # This code is contributed by AnkitRai01 <script> // Javascript program to find the number// of lines which are formed from// given N points and not parallel// to X or Y axis // Function to find the number of lines// which are formed from given N points// and not parallel to X or Y axisfunction NotParallel(p, n){ // This will store the number of points has // same x or y coordinates using the map as // the value of coordinate can be very large var x_axis = new Map(), y_axis = new Map(); for (var i = 0; i < n; i++) { // Counting frequency of each x and y // coordinates if(x_axis.has(p[i][0])) x_axis.set(p[i][0], x_axis.get(p[i][0])+1) else x_axis.set(p[i][0], 1) if(y_axis.has(p[i][1])) y_axis.set(p[i][1], y_axis.get(p[i][1])+1) else y_axis.set(p[i][1], 1) } // Total number of pairs can be formed var total = (n * (n - 1)) / 2; x_axis.forEach((value, key) => { var c = value; // We can not choose pairs from these as // they have same x coordinatethus they // will result line segment // parallel to y axis total -= (c * (c - 1)) / 2; }); y_axis.forEach((value, key) => { var c = value; // we can not choose pairs from these as // they have same y coordinate thus they // will result line segment // parallel to x-axis total -= (c * (c - 1)) / 2; }); // Return the required answer return total;} // Driver Codevar p = [ [ 1, 2 ], [ 1, 5 ], [ 1, 15 ], [ 2, 10 ] ];var n = p.length; // Function calldocument.write( NotParallel(p, n)); // This code is contributed by itsok.</script> 3 Time Complexity: O(N) Auxiliary Space: O(N) princiraj1992 princi singh ankthon nidhi_biet itsok gabaa406 souravmahato348 Geometric Mathematical Mathematical Geometric Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Haversine formula to find distance between two points on a sphere Equation of circle when three points on the circle are given Program to find slope of a line Check if a line touches or intersects a circle Program to find line passing through 2 Points 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) Coin Change | DP-7
[ { "code": null, "e": 26671, "s": 26643, "text": "\n24 Nov, 2021" }, { "code": null, "e": 26828, "s": 26671, "text": "Given N distinct integers points on 2D Plane. The task is to count the number of lines which are formed from given N points and not parallel to X or Y-axis." }, { "code": null, "e": 26839, "s": 26828, "text": "Examples: " }, { "code": null, "e": 26979, "s": 26839, "text": "Input: points[][] = {{1, 2}, {1, 5}, {1, 15}, {2, 10}} Output: 3 Chosen pairs are {(1, 2), (2, 10)}, {(1, 5), (2, 10)}, {(1, 15), (2, 10)}." }, { "code": null, "e": 27063, "s": 26979, "text": "Input: points[][] = {{1, 2}, {2, 5}, {3, 15}} Output: 3 Choose any pair of points. " }, { "code": null, "e": 27075, "s": 27063, "text": "Approach: " }, { "code": null, "e": 27522, "s": 27075, "text": "We know that Line formed by connecting any two-points will be parallel to X-axis if they have the same Y coordinatesIt will be parallel to Y-axis if they have the same X coordinates.Total number of line segments that can formed from N points = Now we will exclude those line segments which are parallel to the X-axis or the Y-axis.For each X coordinate and Y coordinate, calculate the number of points and exclude those line segments at the end." }, { "code": null, "e": 27705, "s": 27522, "text": "We know that Line formed by connecting any two-points will be parallel to X-axis if they have the same Y coordinatesIt will be parallel to Y-axis if they have the same X coordinates." }, { "code": null, "e": 27809, "s": 27705, "text": "Line formed by connecting any two-points will be parallel to X-axis if they have the same Y coordinates" }, { "code": null, "e": 27876, "s": 27809, "text": "It will be parallel to Y-axis if they have the same X coordinates." }, { "code": null, "e": 27940, "s": 27876, "text": "Total number of line segments that can formed from N points = " }, { "code": null, "e": 28028, "s": 27940, "text": "Now we will exclude those line segments which are parallel to the X-axis or the Y-axis." }, { "code": null, "e": 28143, "s": 28028, "text": "For each X coordinate and Y coordinate, calculate the number of points and exclude those line segments at the end." }, { "code": null, "e": 28192, "s": 28143, "text": "Below is the implementation of above approach: " }, { "code": null, "e": 28196, "s": 28192, "text": "C++" }, { "code": null, "e": 28201, "s": 28196, "text": "Java" }, { "code": null, "e": 28204, "s": 28201, "text": "C#" }, { "code": null, "e": 28212, "s": 28204, "text": "Python3" }, { "code": null, "e": 28223, "s": 28212, "text": "Javascript" }, { "code": "// C++ program to find the number// of lines which are formed from// given N points and not parallel// to X or Y axis #include <bits/stdc++.h>using namespace std; // Function to find the number of lines// which are formed from given N points// and not parallel to X or Y axisint NotParallel(int p[][2], int n){ // This will store the number of points has // same x or y coordinates using the map as // the value of coordinate can be very large map<int, int> x_axis, y_axis; for (int i = 0; i < n; i++) { // Counting frequency of each x and y // coordinates x_axis[p[i][0]]++; y_axis[p[i][1]]++; } // Total number of pairs can be formed int total = (n * (n - 1)) / 2; for (auto i : x_axis) { int c = i.second; // We can not choose pairs from these as // they have same x coordinatethus they // will result line segment // parallel to y axis total -= (c * (c - 1)) / 2; } for (auto i : y_axis) { int c = i.second; // we can not choose pairs from these as // they have same y coordinate thus they // will result line segment // parallel to x-axis total -= (c * (c - 1)) / 2; } // Return the required answer return total;} // Driver Codeint main(){ int p[][2] = { { 1, 2 }, { 1, 5 }, { 1, 15 }, { 2, 10 } }; int n = sizeof(p) / sizeof(p[0]); // Function call cout << NotParallel(p, n); return 0;}", "e": 29751, "s": 28223, "text": null }, { "code": "// Java program to find the number// of lines which are formed from// given N points and not parallel// to X or Y axisimport java.util.*; class GFG{ // Function to find the number of lines// which are formed from given N points// and not parallel to X or Y axisstatic int NotParallel(int p[][], int n){ // This will store the number of points has // same x or y coordinates using the map as // the value of coordinate can be very large HashMap<Integer,Integer> x_axis = new HashMap<Integer,Integer>(); HashMap<Integer,Integer> y_axis = new HashMap<Integer,Integer>(); for (int i = 0; i < n; i++) { // Counting frequency of each x and y // coordinates if(x_axis.containsKey(p[i][0])) x_axis.put(p[i][0], x_axis.get(p[i][0])+1); else x_axis.put(p[i][0], 1); if(y_axis.containsKey(p[i][1])) y_axis.put(p[i][1], y_axis.get(p[i][1])+1); else y_axis.put(p[i][1], 1); } // Total number of pairs can be formed int total = (n * (n - 1)) / 2; for (Map.Entry<Integer,Integer> i : x_axis.entrySet()) { int c = i.getValue(); // We can not choose pairs from these as // they have same x coordinatethus they // will result line segment // parallel to y axis total -= (c * (c - 1)) / 2; } for (Map.Entry<Integer,Integer> i : y_axis.entrySet()) { int c = i.getValue(); // we can not choose pairs from these as // they have same y coordinate thus they // will result line segment // parallel to x-axis total -= (c * (c - 1)) / 2; } // Return the required answer return total;} // Driver Codepublic static void main(String[] args){ int p[][] = { { 1, 2 }, { 1, 5 }, { 1, 15 }, { 2, 10 } }; int n = p.length; // Function call System.out.print(NotParallel(p, n)); }} // This code is contributed by PrinciRaj1992", "e": 31748, "s": 29751, "text": null }, { "code": "// C# program to find the number// of lines which are formed from// given N points and not parallel// to X or Y axisusing System;using System.Collections.Generic; class GFG{ // Function to find the number of lines// which are formed from given N points// and not parallel to X or Y axisstatic int NotParallel(int [,]p, int n){ // This will store the number of points has // same x or y coordinates using the map as // the value of coordinate can be very large Dictionary<int,int> x_axis = new Dictionary<int,int>(); Dictionary<int,int> y_axis = new Dictionary<int,int>(); for (int i = 0; i < n; i++) { // Counting frequency of each x and y // coordinates if(x_axis.ContainsKey(p[i, 0])) x_axis[p[i, 0]] = x_axis[p[i, 0]] + 1; else x_axis.Add(p[i, 0], 1); if(y_axis.ContainsKey(p[i, 1])) y_axis[p[i, 1]] = y_axis[p[i, 1]] + 1; else y_axis.Add(p[i, 1], 1); } // Total number of pairs can be formed int total = (n * (n - 1)) / 2; foreach (KeyValuePair<int,int> i in x_axis) { int c = i.Value; // We can not choose pairs from these as // they have same x coordinatethus they // will result line segment // parallel to y axis total -= (c * (c - 1)) / 2; } foreach (KeyValuePair<int,int> i in y_axis) { int c = i.Value; // we can not choose pairs from these as // they have same y coordinate thus they // will result line segment // parallel to x-axis total -= (c * (c - 1)) / 2; } // Return the required answer return total;} // Driver Codepublic static void Main(String[] args){ int [,]p = { { 1, 2 }, { 1, 5 }, { 1, 15 }, { 2, 10 } }; int n = p.GetLength(0); // Function call Console.Write(NotParallel(p, n)); }} // This code is contributed by Princi Singh", "e": 33720, "s": 31748, "text": null }, { "code": "# Python3 program to find the number# of lines which are formed from# given N points and not parallel# to X or Y axis # Function to find the number of lines# which are formed from given N points# and not parallel to X or Y axisdef NotParallel(p, n) : # This will store the number of points has # same x or y coordinates using the map as # the value of coordinate can be very large x_axis = {}; y_axis = {}; for i in range(n) : # Counting frequency of each x and y # coordinates if p[i][0] not in x_axis : x_axis[p[i][0]] = 0; x_axis[p[i][0]] += 1; if p[i][1] not in y_axis : y_axis[p[i][1]] = 0; y_axis[p[i][1]] += 1; # Total number of pairs can be formed total = (n * (n - 1)) // 2; for i in x_axis : c = x_axis[i]; # We can not choose pairs from these as # they have same x coordinatethus they # will result line segment # parallel to y axis total -= (c * (c - 1)) // 2; for i in y_axis : c = y_axis[i]; # we can not choose pairs from these as # they have same y coordinate thus they # will result line segment # parallel to x-axis total -= (c * (c - 1)) // 2; # Return the required answer return total; # Driver Codeif __name__ == \"__main__\" : p = [ [ 1, 2 ], [1, 5 ], [1, 15 ], [ 2, 10 ] ]; n = len(p); # Function call print(NotParallel(p, n)); # This code is contributed by AnkitRai01", "e": 35282, "s": 33720, "text": null }, { "code": "<script> // Javascript program to find the number// of lines which are formed from// given N points and not parallel// to X or Y axis // Function to find the number of lines// which are formed from given N points// and not parallel to X or Y axisfunction NotParallel(p, n){ // This will store the number of points has // same x or y coordinates using the map as // the value of coordinate can be very large var x_axis = new Map(), y_axis = new Map(); for (var i = 0; i < n; i++) { // Counting frequency of each x and y // coordinates if(x_axis.has(p[i][0])) x_axis.set(p[i][0], x_axis.get(p[i][0])+1) else x_axis.set(p[i][0], 1) if(y_axis.has(p[i][1])) y_axis.set(p[i][1], y_axis.get(p[i][1])+1) else y_axis.set(p[i][1], 1) } // Total number of pairs can be formed var total = (n * (n - 1)) / 2; x_axis.forEach((value, key) => { var c = value; // We can not choose pairs from these as // they have same x coordinatethus they // will result line segment // parallel to y axis total -= (c * (c - 1)) / 2; }); y_axis.forEach((value, key) => { var c = value; // we can not choose pairs from these as // they have same y coordinate thus they // will result line segment // parallel to x-axis total -= (c * (c - 1)) / 2; }); // Return the required answer return total;} // Driver Codevar p = [ [ 1, 2 ], [ 1, 5 ], [ 1, 15 ], [ 2, 10 ] ];var n = p.length; // Function calldocument.write( NotParallel(p, n)); // This code is contributed by itsok.</script>", "e": 37019, "s": 35282, "text": null }, { "code": null, "e": 37021, "s": 37019, "text": "3" }, { "code": null, "e": 37045, "s": 37023, "text": "Time Complexity: O(N)" }, { "code": null, "e": 37068, "s": 37045, "text": "Auxiliary Space: O(N) " }, { "code": null, "e": 37082, "s": 37068, "text": "princiraj1992" }, { "code": null, "e": 37095, "s": 37082, "text": "princi singh" }, { "code": null, "e": 37103, "s": 37095, "text": "ankthon" }, { "code": null, "e": 37114, "s": 37103, "text": "nidhi_biet" }, { "code": null, "e": 37120, "s": 37114, "text": "itsok" }, { "code": null, "e": 37129, "s": 37120, "text": "gabaa406" }, { "code": null, "e": 37145, "s": 37129, "text": "souravmahato348" }, { "code": null, "e": 37155, "s": 37145, "text": "Geometric" }, { "code": null, "e": 37168, "s": 37155, "text": "Mathematical" }, { "code": null, "e": 37181, "s": 37168, "text": "Mathematical" }, { "code": null, "e": 37191, "s": 37181, "text": "Geometric" }, { "code": null, "e": 37289, "s": 37191, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37355, "s": 37289, "text": "Haversine formula to find distance between two points on a sphere" }, { "code": null, "e": 37416, "s": 37355, "text": "Equation of circle when three points on the circle are given" }, { "code": null, "e": 37448, "s": 37416, "text": "Program to find slope of a line" }, { "code": null, "e": 37495, "s": 37448, "text": "Check if a line touches or intersects a circle" }, { "code": null, "e": 37541, "s": 37495, "text": "Program to find line passing through 2 Points" }, { "code": null, "e": 37571, "s": 37541, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 37586, "s": 37571, "text": "C++ Data Types" }, { "code": null, "e": 37646, "s": 37586, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 37689, "s": 37646, "text": "Set in C++ Standard Template Library (STL)" } ]
How to use toUpperCase () in Android textview?
This example demonstrate about How to use toUpperCase () in Android textview. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:gravity="center" tools:context=".MainActivity"> <EditText android:id="@+id/name" android:layout_width="match_parent" android:hint="Enter name" android:layout_height="wrap_content" /> <Button android:id="@+id/click" android:text="Click" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <TextView android:id="@+id/textview" android:layout_width="wrap_content" android:textSize="25sp" android:layout_height="wrap_content" /> </LinearLayout> In the above code, we have taken name as Edit text, when user click on button it will take data and Convert into upper case letters. Step 3 − Add the following code to src/MainActivity.java package com.example.myapplication; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; public class MainActivity extends AppCompatActivity { EditText name; Button button; TextView text; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); name = findViewById(R.id.name); button = findViewById(R.id.click); text = findViewById(R.id.textview); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!name.getText().toString().isEmpty()) { if (name.getText().toString().length() >= 0) { String touppercase = name.getText().toString().toUpperCase(); text.setText(String.valueOf(touppercase)); } } else { name.setError("Plz enter name"); } } }); } } Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen − In the above result, enter the string as “krishna” (ALL LOWER CASE) and it returned upper case letters as KRISHNA. Click here to download the project code
[ { "code": null, "e": 1140, "s": 1062, "text": "This example demonstrate about How to use toUpperCase () in Android textview." }, { "code": null, "e": 1269, "s": 1140, "text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project." }, { "code": null, "e": 1334, "s": 1269, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2224, "s": 1334, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:app=\"http://schemas.android.com/apk/res-auto\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:orientation=\"vertical\"\n android:gravity=\"center\"\n tools:context=\".MainActivity\">\n <EditText\n android:id=\"@+id/name\"\n android:layout_width=\"match_parent\"\n android:hint=\"Enter name\"\n android:layout_height=\"wrap_content\" />\n <Button\n android:id=\"@+id/click\"\n android:text=\"Click\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\" />\n <TextView\n android:id=\"@+id/textview\"\n android:layout_width=\"wrap_content\"\n android:textSize=\"25sp\"\n android:layout_height=\"wrap_content\" />\n</LinearLayout>" }, { "code": null, "e": 2357, "s": 2224, "text": "In the above code, we have taken name as Edit text, when user click on button it will take data and Convert into upper case letters." }, { "code": null, "e": 2414, "s": 2357, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 3539, "s": 2414, "text": "package com.example.myapplication;\n\nimport android.os.Bundle;\nimport android.support.v7.app.AppCompatActivity;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.EditText;\nimport android.widget.TextView;\n\npublic class MainActivity extends AppCompatActivity {\n EditText name;\n Button button;\n TextView text;\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n name = findViewById(R.id.name);\n button = findViewById(R.id.click);\n text = findViewById(R.id.textview);\n button.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n if (!name.getText().toString().isEmpty()) {\n if (name.getText().toString().length() >= 0) {\n String touppercase = name.getText().toString().toUpperCase();\n text.setText(String.valueOf(touppercase));\n }\n } else {\n name.setError(\"Plz enter name\");\n }\n }\n });\n }\n}" }, { "code": null, "e": 3886, "s": 3539, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −" }, { "code": null, "e": 4001, "s": 3886, "text": "In the above result, enter the string as “krishna” (ALL LOWER CASE) and it returned upper case letters as KRISHNA." }, { "code": null, "e": 4041, "s": 4001, "text": "Click here to download the project code" } ]
Angular 8 - Services and Dependency Injection
As learned earlier, Services provides specific functionality in an Angular application. In a given Angular application, there may be one or more services can be used. Similarly, an Angular component may depend on one or more services. Also, Angular services may depend on another services to work properly. Dependency resolution is one of the complex and time consuming activity in developing any application. To reduce the complexity, Angular provides Dependency Injection pattern as one of the core concept. Let us learn, how to use Dependency Injection in Angular application in this chapter. An Angular service is plain Typescript class having one or more methods (functionality) along with @Injectable decorator. It enables the normal Typescript class to be used as service in Angular application. import { Injectable } from '@angular/core'; @Injectable() export class DebugService { constructor() { } } Here, @Injectable decorator converts a plain Typescript class into Angular service. To use Dependency Injection, every service needs to be registered into the system. Angular provides multiple option to register a service. They are as follows − ModuleInjector @ root level ModuleInjector @ platform level ElementInjector using providers meta data ElementInjector using viewProviders meta data NullInjector ModuleInjector enforces the service to used only inside a specific module. ProvidedInmeta data available in @Injectable has to be used to specify the module in which the service can be used. The value should refer to the one of the registered Angular Module (decorated with @NgModule). root is a special option which refers the root module of the application. The sample code is as follows − import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root', }) export class DebugService { constructor() { } } Platform Injector is one level higher than ModuleInject and it is only in advanced and rare situation. Every Angular application starts by executing PreformBrowserDynamic().bootstrap method (see main.js), which is responsible for bootstrapping root module of Angular application. PreformBrowserDynamic() method creates an injector configured by PlatformModule. We can configure platform level services using platformBrowser() method provided by PlatformModule. NullInjector is one level higher than platform level ModuleInjector and is in the top level of the hierarchy. We could not able to register any service in the NullInjector. It resolves when the required service is not found anywhere in the hierarchy and simply throws an error. ElementInjector enforces the service to be used only inside some particular components. providers and ViewProviders meta data available in @Component decorator is used to specify the list of services to be visible for the particular component. The sample code to use providers is as follows − ExpenseEntryListComponent // import statement import { DebugService } from '../debug.service'; // component decorator @Component({ selector: 'app-expense-entry-list', templateUrl: './expense-entry-list.component.html', styleUrls: ['./expense-entry-list.component.css'], providers: [DebugService] }) Here, DebugService will be available only inside the ExpenseEntryListComponent and its view. To make DebugService in other component, simply use providers decorator in necessary component. viewProviders is similar to provider except it does not allow the service to be used inside the componentâ€TMs content created using ng-content directive. ExpenseEntryListComponent // import statement import { DebugService } from '../debug.service'; // component decorator @Component({ selector: 'app-expense-entry-list', templateUrl: './expense-entry-list.component.html', styleUrls: ['./expense-entry-list.component.css'], viewProviders: [DebugService] }) Parent component can use a child component either through its view or content. Example of a parent component with child and content view is mentioned below − Parent component view / template <div> child template in view <child></child> </div> <ng-content></ng-content> child component view / template <div> child template in view </div> Parent component usage in a template (another component) <parent> <!-- child template in content --> <child></child> </parent> Here, child component is used in two place. One inside the parent’s view. Another inside parent content. Services will be available in child component, which is placed inside parent’s view. Services will not be available in child component, which is placed inside parent’s content. Let us see how a component can resolve a service using the below flow diagram. Here, First, component tries to find the service registered using viewProviders meta data. If not found, component tries to find the service registered using providers meta data. If not found, Component tries to find the service registered using ModuleInjector If not found, component tries to find the service registered using PlatformInjector If not found, component tries to find the service registered using NullInjector, which always throws error. The hierarchy of the Injector along with work flow of the resolving the service is as follows − As we learn in the previous chapter, the resolution of the service starts from component and stops either when a service is found or NUllInjector is reached. This is the default resolution and it can be changed using Resolution Modifier. They are as follows − Self() Self() start and stops the search for the service in its current ElementInjector itself. import { Self } from '@angular/core'; constructor(@Self() public debugService: DebugService) {} SkipSelf() SkipSelf() is just opposite to Self(). It skips the current ElementInjector and starts the search for service from its parent ElementInjector. import { SkipSelf } from '@angular/core'; constructor(@SkipSelf() public debugService: DebugService) {} Host() Host() stop the search for the service in its host ElementInjector. Even if service available up in the higher level, it stops at host. import { Host } from '@angular/core'; constructor(@Host() public debugService: DebugService) {} Optional() Optional() does not throws the error when the search for the service fails. import { Optional } from '@angular/core'; constructor(@Optional() private debugService?: DebugService) { if (this.debugService) { this.debugService.info("Debugger initialized"); } } Dependency Injector providers serves two purpose. First, it helps in setting a token for the service to be registered. The token will be used to refer and call the service. Second, it helps in creating the service from the given configuration. As learned earlier, the simplest provider is as follows − providers: [ DebugService ] Here, DebugService is both token as well as the class, with which the service object has to be created. The actual form of the provider is as follows − providers: [ { provides: DebugService, useClass: DebugService }] Here, provides is the token and useClass is the class reference to create the service object. Angular provides some more providers and they are as follows − Aliased class providers The purpose of the providers is to reuse the existing service. providers: [ DebugService, { provides: AnotherDebugService, userClass: DebugService }] Here, only one instance of DebugService service will be created. Value providers The purpose of the Value providers is to supply the value itself instead of asking the DI to create an instance of the service object. It may use existing object as well. The only restriction is that the object should be in the shape of referenced service. export class MyCustomService { name = "My Custom Service" } [{ provide: MyService, useValue: { name: 'instance of MyCustomService' }] Here, DI provider just return the instance set in useValue option instead of creating a new service object. Non-class dependency providers It enables string, function or object to be used in Angular DI. Let us see a simple example. // Create the injectable token import { InjectionToken } from '@angular/core'; export const APP_CONFIG = new InjectionToken<AppConfig>('app.config'); // Create value export const MY_CONFIG: AppConfig = { title: 'Dependency Injection' }; // congfigure providers providers: [{ provide: APP_CONFIG, useValue: HERO_DI_CONFIG }] // inject the service constructor(@Inject(APP_CONFIG) config: AppConfig) { Factory providers Factory Providers enables complex service creation. It delegates the creation of the object to an external function. Factory providers has option to set the dependency for factory object as well. { provide: MyService, useFactory: myServiceFactory, deps: [DebugService] }; Here, myServiceFactory returns the instance of MyService. Now, we know how to create and register Angular Service. Let us see how to use the Angular Service inside a component. Using an Angular service is as simple as setting the type of parameters of the constructor as the token of the service providers. export class ExpenseEntryListComponent implements OnInit { title = 'Expense List'; constructor(private debugService : DebugService) {} ngOnInit() { this.debugService.info("Angular Application starts"); } } Here, ExpenseEntryListComponent constructor set a parameter of type DebugService. ExpenseEntryListComponent constructor set a parameter of type DebugService. Angular Dependency Injector (DI) will try to find any service registered in the application with type DebugService. If found, it will set an instance of DebugService to ExpenseEntryListComponent component. If not found, it will throw an error. Angular Dependency Injector (DI) will try to find any service registered in the application with type DebugService. If found, it will set an instance of DebugService to ExpenseEntryListComponent component. If not found, it will throw an error. Let us add a simple Debug service, which will help us to print the debugging information during application development. Open command prompt and go to project root folder. cd /go/to/expense-manager Start the application. ng serve Run the below command to generate an Angular service, DebugService. ng g service debug This will create two Typescript files (debug service & its test) as specified below − CREATE src/app/debug.service.spec.ts (328 bytes) CREATE src/app/debug.service.ts (134 bytes) Let us analyse the content of the DebugService service. import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class DebugService { constructor() { } } Here, @Injectable decorator is attached to DebugService class, which enables the DebugService to be used in Angular component of the application. @Injectable decorator is attached to DebugService class, which enables the DebugService to be used in Angular component of the application. providerIn option and its value, root enables the DebugService to be used in all component of the application. providerIn option and its value, root enables the DebugService to be used in all component of the application. Let us add a method, Info, which will print the message into the browser console. info(message : String) : void { console.log(message); } Let us initialise the service in the ExpenseEntryListComponent and use it to print message. import { Component, OnInit } from '@angular/core'; import { ExpenseEntry } from '../expense-entry'; import { DebugService } from '../debug.service'; @Component({ selector: 'app-expense-entry-list', templateUrl: './expense-entry-list.component.html', styleUrls: ['./expense-entry-list.component.css'] }) export class ExpenseEntryListComponent implements OnInit { title: string; expenseEntries: ExpenseEntry[]; constructor(private debugService: DebugService) { } ngOnInit() { this.debugService.info("Expense Entry List component initialized"); this.title = "Expense Entry List"; this.expenseEntries = this.getExpenseEntries(); } // other coding } Here, DebugService is initialised using constructor parameters. Setting an argument (debugService) of type DebugService will trigger the dependency injection to create a new DebugService object and set it into the ExpenseEntryListComponent component. DebugService is initialised using constructor parameters. Setting an argument (debugService) of type DebugService will trigger the dependency injection to create a new DebugService object and set it into the ExpenseEntryListComponent component. Calling the info method of DebugService in the ngOnInit method prints the message in the browser console. Calling the info method of DebugService in the ngOnInit method prints the message in the browser console. The result can be viewed using developer tools and it looks similar as shown below − Let us extend the application to understand the scope of the service. Let us a create a DebugComponent by using below mentioned command. ng generate component debug CREATE src/app/debug/debug.component.html (20 bytes) CREATE src/app/debug/debug.component.spec.ts (621 bytes) CREATE src/app/debug/debug.component.ts (265 bytes) CREATE src/app/debug/debug.component.css (0 bytes) UPDATE src/app/app.module.ts (392 bytes) Let us remove the DebugService in the root module. // src/app/debug.service.ts import { Injectable } from '@angular/core'; @Injectable() export class DebugService { constructor() { } info(message : String) : void { console.log(message); } } Register the DebugService under ExpenseEntryListComponent component. // src/app/expense-entry-list/expense-entry-list.component.ts @Component({ selector: 'app-expense-entry-list', templateUrl: './expense-entry-list.component.html', styleUrls: ['./expense-entry-list.component.css'] providers: [DebugService] }) Here, we have used providers meta data (ElementInjector) to register the service. Open DebugComponent (src/app/debug/debug.component.ts) and import DebugService and set an instance in the constructor of the component. import { Component, OnInit } from '@angular/core'; import { DebugService } from '../debug.service'; @Component({ selector: 'app-debug', templateUrl: './debug.component.html', styleUrls: ['./debug.component.css'] }) export class DebugComponent implements OnInit { constructor(private debugService: DebugService) { } ngOnInit() { this.debugService.info("Debug component gets service from Parent"); } } Here, we have not registered DebugService. So, DebugService will not be available if used as parent component. When used inside a parent component, the service may available from parent, if the parent has access to the service. Open ExpenseEntryListComponent template (src/app/expense-entry-list/expense-entry-list.component.html) and include a content section as shown below: // existing content <app-debug></app-debug> <ng-content></ng-content> Here, we have included a content section and DebugComponent section. Let us include the debug component as a content inside the ExpenseEntryListComponent component in the AppComponent template. Open AppComponent template and change app-expense-entry-list as below − // navigation code <app-expense-entry-list> <app-debug></app-debug> </app-expense-entry-list> Here, we have included the DebugComponent as content. Let us check the application and it will show DebugService template at the end of the page as shown below − Also, we could able to see two debug information from debug component in the console. This indicate that the debug component gets the service from its parent component. Let us change how the service is injected in the ExpenseEntryListComponent and how it affects the scope of the service. Change providers injector to viewProviders injection. viewProviders does not inject the service into the content child and so, it should fail. viewProviders: [DebugService] Check the application and you will see that the one of the debug component (used as content child) throws error as shown below − Let us remove the debug component in the templates and restore the application. Open ExpenseEntryListComponent template (src/app/expense-entry-list/expense-entry-list.component.html) and remove below content <app-debug></app-debug> <ng-content></ng-content> Open AppComponent template and change app-expense-entry-list as below − // navigation code <app-expense-entry-list> </app-expense-entry-list> Change the viewProviders setting to providers in ExpenseEntryListComponent. providers: [DebugService] Rerun the application and check the result. 16 Lectures 1.5 hours Anadi Sharma 28 Lectures 2.5 hours Anadi Sharma 11 Lectures 7.5 hours SHIVPRASAD KOIRALA 16 Lectures 2.5 hours Frahaan Hussain 69 Lectures 5 hours Senol Atac 53 Lectures 3.5 hours Senol Atac Print Add Notes Bookmark this page
[ { "code": null, "e": 2623, "s": 2388, "text": "As learned earlier, Services provides specific functionality in an Angular application. In a given Angular application, there may be one or more services can be used. Similarly, an Angular component may depend on one or more services." }, { "code": null, "e": 2898, "s": 2623, "text": "Also, Angular services may depend on another services to work properly. Dependency resolution is one of the complex and time consuming activity in developing any application. To reduce the complexity, Angular provides Dependency Injection pattern as one of the core concept." }, { "code": null, "e": 2984, "s": 2898, "text": "Let us learn, how to use Dependency Injection in Angular application in this chapter." }, { "code": null, "e": 3191, "s": 2984, "text": "An Angular service is plain Typescript class having one or more methods (functionality) along with @Injectable decorator. It enables the normal Typescript class to be used as service in Angular application." }, { "code": null, "e": 3304, "s": 3191, "text": "import { Injectable } from '@angular/core'; @Injectable() \nexport class DebugService { \n constructor() { } \n}\n" }, { "code": null, "e": 3388, "s": 3304, "text": "Here, @Injectable decorator converts a plain Typescript class into Angular service." }, { "code": null, "e": 3549, "s": 3388, "text": "To use Dependency Injection, every service needs to be registered into the system. Angular provides multiple option to register a service. They are as follows −" }, { "code": null, "e": 3577, "s": 3549, "text": "ModuleInjector @ root level" }, { "code": null, "e": 3609, "s": 3577, "text": "ModuleInjector @ platform level" }, { "code": null, "e": 3651, "s": 3609, "text": "ElementInjector using providers meta data" }, { "code": null, "e": 3697, "s": 3651, "text": "ElementInjector using viewProviders meta data" }, { "code": null, "e": 3710, "s": 3697, "text": "NullInjector" }, { "code": null, "e": 3901, "s": 3710, "text": "ModuleInjector enforces the service to used only inside a specific module. ProvidedInmeta data available in @Injectable has to be used to specify the module in which the service can be used." }, { "code": null, "e": 4102, "s": 3901, "text": "The value should refer to the one of the registered Angular Module (decorated with @NgModule). root is a special option which refers the root module of the application. The sample code is as follows −" }, { "code": null, "e": 4242, "s": 4102, "text": "import { Injectable } from '@angular/core'; @Injectable({ \n providedIn: 'root', \n})\nexport class DebugService { \n constructor() { } \n}\n" }, { "code": null, "e": 4522, "s": 4242, "text": "Platform Injector is one level higher than ModuleInject and it is only in advanced and rare situation. Every Angular application starts by executing PreformBrowserDynamic().bootstrap method (see main.js), which is responsible for bootstrapping root module of Angular application." }, { "code": null, "e": 4703, "s": 4522, "text": "PreformBrowserDynamic() method creates an injector configured by PlatformModule. We can configure platform level services using platformBrowser() method provided by PlatformModule." }, { "code": null, "e": 4981, "s": 4703, "text": "NullInjector is one level higher than platform level ModuleInjector and is in the top level of the hierarchy. We could not able to register any service in the NullInjector. It resolves when the required service is not found anywhere in the hierarchy and simply throws an error." }, { "code": null, "e": 5274, "s": 4981, "text": "ElementInjector enforces the service to be used only inside some particular components. providers and ViewProviders meta data available in @Component decorator is used to specify the list of services to be visible for the particular component. The sample code to use providers is as follows −" }, { "code": null, "e": 5300, "s": 5274, "text": "ExpenseEntryListComponent" }, { "code": null, "e": 5593, "s": 5300, "text": "// import statement \nimport { DebugService } from '../debug.service'; \n// component decorator \n@Component({ \n selector: 'app-expense-entry-list', \n templateUrl: './expense-entry-list.component.html', \n styleUrls: ['./expense-entry-list.component.css'], \n providers: [DebugService] })\n" }, { "code": null, "e": 5782, "s": 5593, "text": "Here, DebugService will be available only inside the ExpenseEntryListComponent and its view. To make DebugService in other component, simply use providers decorator in necessary component." }, { "code": null, "e": 5938, "s": 5782, "text": "viewProviders is similar to provider except it does not allow the service to be used inside the componentâ€TMs content created using ng-content directive." }, { "code": null, "e": 5964, "s": 5938, "text": "ExpenseEntryListComponent" }, { "code": null, "e": 6258, "s": 5964, "text": "// import statement \nimport { DebugService } from '../debug.service'; \n// component decorator \n@Component({ \n selector: 'app-expense-entry-list', \n templateUrl: './expense-entry-list.component.html', \n styleUrls: ['./expense-entry-list.component.css'], viewProviders: [DebugService] \n})\n" }, { "code": null, "e": 6416, "s": 6258, "text": "Parent component can use a child component either through its view or content. Example of a parent component with child and content view is mentioned below −" }, { "code": null, "e": 6449, "s": 6416, "text": "Parent component view / template" }, { "code": null, "e": 6538, "s": 6449, "text": "<div> \n child template in view \n <child></child> \n</div> \n<ng-content></ng-content>\n" }, { "code": null, "e": 6570, "s": 6538, "text": "child component view / template" }, { "code": null, "e": 6613, "s": 6570, "text": "<div> \n child template in view \n</div> \n" }, { "code": null, "e": 6670, "s": 6613, "text": "Parent component usage in a template (another component)" }, { "code": null, "e": 6749, "s": 6670, "text": "<parent> \n <!-- child template in content -->\n <child></child>\n</parent> \n" }, { "code": null, "e": 6755, "s": 6749, "text": "Here," }, { "code": null, "e": 6854, "s": 6755, "text": "child component is used in two place. One inside the parent’s view. Another inside parent content." }, { "code": null, "e": 6939, "s": 6854, "text": "Services will be available in child component, which is placed inside parent’s view." }, { "code": null, "e": 7031, "s": 6939, "text": "Services will not be available in child component, which is placed inside parent’s content." }, { "code": null, "e": 7110, "s": 7031, "text": "Let us see how a component can resolve a service using the below flow diagram." }, { "code": null, "e": 7116, "s": 7110, "text": "Here," }, { "code": null, "e": 7201, "s": 7116, "text": "First, component tries to find the service registered using viewProviders meta data." }, { "code": null, "e": 7289, "s": 7201, "text": "If not found, component tries to find the service registered using providers meta data." }, { "code": null, "e": 7371, "s": 7289, "text": "If not found, Component tries to find the service registered using ModuleInjector" }, { "code": null, "e": 7455, "s": 7371, "text": "If not found, component tries to find the service registered using PlatformInjector" }, { "code": null, "e": 7563, "s": 7455, "text": "If not found, component tries to find the service registered using NullInjector, which always throws error." }, { "code": null, "e": 7659, "s": 7563, "text": "The hierarchy of the Injector along with work flow of the resolving the service is as follows −" }, { "code": null, "e": 7919, "s": 7659, "text": "As we learn in the previous chapter, the resolution of the service starts from component and stops either when a service is found or NUllInjector is reached. This is the default resolution and it can be changed using Resolution Modifier. They are as follows −" }, { "code": null, "e": 7926, "s": 7919, "text": "Self()" }, { "code": null, "e": 8015, "s": 7926, "text": "Self() start and stops the search for the service in its current ElementInjector itself." }, { "code": null, "e": 8113, "s": 8015, "text": "import { Self } from '@angular/core'; \nconstructor(@Self() public debugService: DebugService) {}\n" }, { "code": null, "e": 8124, "s": 8113, "text": "SkipSelf()" }, { "code": null, "e": 8267, "s": 8124, "text": "SkipSelf() is just opposite to Self(). It skips the current ElementInjector and starts the search for service from its parent ElementInjector." }, { "code": null, "e": 8373, "s": 8267, "text": "import { SkipSelf } from '@angular/core'; \nconstructor(@SkipSelf() public debugService: DebugService) {}\n" }, { "code": null, "e": 8380, "s": 8373, "text": "Host()" }, { "code": null, "e": 8516, "s": 8380, "text": "Host() stop the search for the service in its host ElementInjector. Even if service available up in the higher level, it stops at host." }, { "code": null, "e": 8614, "s": 8516, "text": "import { Host } from '@angular/core'; \nconstructor(@Host() public debugService: DebugService) {}\n" }, { "code": null, "e": 8625, "s": 8614, "text": "Optional()" }, { "code": null, "e": 8701, "s": 8625, "text": "Optional() does not throws the error when the search for the service fails." }, { "code": null, "e": 8901, "s": 8701, "text": "import { Optional } from '@angular/core'; \nconstructor(@Optional() private debugService?: DebugService) { \n if (this.debugService) { \n this.debugService.info(\"Debugger initialized\"); \n } \n}\n" }, { "code": null, "e": 9145, "s": 8901, "text": "Dependency Injector providers serves two purpose. First, it helps in setting a token for the service to be registered. The token will be used to refer and call the service. Second, it helps in creating the service from the given configuration." }, { "code": null, "e": 9203, "s": 9145, "text": "As learned earlier, the simplest provider is as follows −" }, { "code": null, "e": 9232, "s": 9203, "text": "providers: [ DebugService ]\n" }, { "code": null, "e": 9384, "s": 9232, "text": "Here, DebugService is both token as well as the class, with which the service object has to be created. The actual form of the provider is as follows −" }, { "code": null, "e": 9450, "s": 9384, "text": "providers: [ { provides: DebugService, useClass: DebugService }]\n" }, { "code": null, "e": 9544, "s": 9450, "text": "Here, provides is the token and useClass is the class reference to create the service object." }, { "code": null, "e": 9607, "s": 9544, "text": "Angular provides some more providers and they are as follows −" }, { "code": null, "e": 9631, "s": 9607, "text": "Aliased class providers" }, { "code": null, "e": 9694, "s": 9631, "text": "The purpose of the providers is to reuse the existing service." }, { "code": null, "e": 9786, "s": 9694, "text": "providers: [ DebugService, \n { provides: AnotherDebugService, userClass: DebugService }]\n" }, { "code": null, "e": 9851, "s": 9786, "text": "Here, only one instance of DebugService service will be created." }, { "code": null, "e": 9867, "s": 9851, "text": "Value providers" }, { "code": null, "e": 10124, "s": 9867, "text": "The purpose of the Value providers is to supply the value itself instead of asking the DI to create an instance of the service object. It may use existing object as well. The only restriction is that the object should be in the shape of referenced service." }, { "code": null, "e": 10265, "s": 10124, "text": "export class MyCustomService { \n name = \"My Custom Service\" \n} \n[{ provide: MyService, useValue: { name: 'instance of MyCustomService' }]\n" }, { "code": null, "e": 10373, "s": 10265, "text": "Here, DI provider just return the instance set in useValue option instead of creating a new service object." }, { "code": null, "e": 10404, "s": 10373, "text": "Non-class dependency providers" }, { "code": null, "e": 10468, "s": 10404, "text": "It enables string, function or object to be used in Angular DI." }, { "code": null, "e": 10497, "s": 10468, "text": "Let us see a simple example." }, { "code": null, "e": 10910, "s": 10497, "text": "// Create the injectable token \nimport { InjectionToken } from '@angular/core'; \nexport const APP_CONFIG = new InjectionToken<AppConfig>('app.config'); \n// Create value \nexport const MY_CONFIG: AppConfig = { \n title: 'Dependency Injection' \n}; \n// congfigure providers \nproviders: [{ provide: APP_CONFIG, useValue: HERO_DI_CONFIG }] \n// inject the service \nconstructor(@Inject(APP_CONFIG) config: AppConfig) {\n" }, { "code": null, "e": 10928, "s": 10910, "text": "Factory providers" }, { "code": null, "e": 11124, "s": 10928, "text": "Factory Providers enables complex service creation. It delegates the creation of the object to an external function. Factory providers has option to set the dependency for factory object as well." }, { "code": null, "e": 11201, "s": 11124, "text": "{ provide: MyService, useFactory: myServiceFactory, deps: [DebugService] };\n" }, { "code": null, "e": 11259, "s": 11201, "text": "Here, myServiceFactory returns the instance of MyService." }, { "code": null, "e": 11508, "s": 11259, "text": "Now, we know how to create and register Angular Service. Let us see how to use the Angular Service inside a component. Using an Angular service is as simple as setting the type of parameters of the constructor as the token of the service providers." }, { "code": null, "e": 11738, "s": 11508, "text": "export class ExpenseEntryListComponent implements OnInit {\n title = 'Expense List'; \n constructor(private debugService : DebugService) {} \n ngOnInit() { \n this.debugService.info(\"Angular Application starts\"); \n } \n}\n" }, { "code": null, "e": 11744, "s": 11738, "text": "Here," }, { "code": null, "e": 11820, "s": 11744, "text": "ExpenseEntryListComponent constructor set a parameter of type DebugService." }, { "code": null, "e": 11896, "s": 11820, "text": "ExpenseEntryListComponent constructor set a parameter of type DebugService." }, { "code": null, "e": 12140, "s": 11896, "text": "Angular Dependency Injector (DI) will try to find any service registered in the application with type DebugService. If found, it will set an instance of DebugService to ExpenseEntryListComponent component. If not found, it will throw an error." }, { "code": null, "e": 12384, "s": 12140, "text": "Angular Dependency Injector (DI) will try to find any service registered in the application with type DebugService. If found, it will set an instance of DebugService to ExpenseEntryListComponent component. If not found, it will throw an error." }, { "code": null, "e": 12505, "s": 12384, "text": "Let us add a simple Debug service, which will help us to print the debugging information during application development." }, { "code": null, "e": 12556, "s": 12505, "text": "Open command prompt and go to project root folder." }, { "code": null, "e": 12583, "s": 12556, "text": "cd /go/to/expense-manager\n" }, { "code": null, "e": 12606, "s": 12583, "text": "Start the application." }, { "code": null, "e": 12616, "s": 12606, "text": "ng serve\n" }, { "code": null, "e": 12684, "s": 12616, "text": "Run the below command to generate an Angular service, DebugService." }, { "code": null, "e": 12704, "s": 12684, "text": "ng g service debug\n" }, { "code": null, "e": 12790, "s": 12704, "text": "This will create two Typescript files (debug service & its test) as specified below −" }, { "code": null, "e": 12885, "s": 12790, "text": "CREATE src/app/debug.service.spec.ts (328 bytes) \nCREATE src/app/debug.service.ts (134 bytes)\n" }, { "code": null, "e": 12941, "s": 12885, "text": "Let us analyse the content of the DebugService service." }, { "code": null, "e": 13081, "s": 12941, "text": "import { Injectable } from '@angular/core'; @Injectable({ \n providedIn: 'root' \n}) \nexport class DebugService { \n constructor() { } \n}\n" }, { "code": null, "e": 13087, "s": 13081, "text": "Here," }, { "code": null, "e": 13227, "s": 13087, "text": "@Injectable decorator is attached to DebugService class, which enables the DebugService to be used in Angular component of the application." }, { "code": null, "e": 13367, "s": 13227, "text": "@Injectable decorator is attached to DebugService class, which enables the DebugService to be used in Angular component of the application." }, { "code": null, "e": 13478, "s": 13367, "text": "providerIn option and its value, root enables the DebugService to be used in all component of the application." }, { "code": null, "e": 13589, "s": 13478, "text": "providerIn option and its value, root enables the DebugService to be used in all component of the application." }, { "code": null, "e": 13671, "s": 13589, "text": "Let us add a method, Info, which will print the message into the browser console." }, { "code": null, "e": 13733, "s": 13671, "text": "info(message : String) : void { \n console.log(message); \n}\n" }, { "code": null, "e": 13825, "s": 13733, "text": "Let us initialise the service in the ExpenseEntryListComponent and use it to print message." }, { "code": null, "e": 14534, "s": 13825, "text": "import { Component, OnInit } from '@angular/core'; import { ExpenseEntry } from '../expense-entry'; import { DebugService } from '../debug.service'; @Component({ \n selector: 'app-expense-entry-list', \n templateUrl: './expense-entry-list.component.html', styleUrls: ['./expense-entry-list.component.css'] \n}) \nexport class ExpenseEntryListComponent implements OnInit { \n title: string; \n expenseEntries: ExpenseEntry[]; \n constructor(private debugService: DebugService) { } \n ngOnInit() { \n this.debugService.info(\"Expense Entry List \n component initialized\"); \n this.title = \"Expense Entry List\"; \n this.expenseEntries = this.getExpenseEntries(); \n } \n // other coding \n}\n" }, { "code": null, "e": 14540, "s": 14534, "text": "Here," }, { "code": null, "e": 14785, "s": 14540, "text": "DebugService is initialised using constructor parameters. Setting an argument (debugService) of type DebugService will trigger the dependency injection to create a new DebugService object and set it into the ExpenseEntryListComponent component." }, { "code": null, "e": 15030, "s": 14785, "text": "DebugService is initialised using constructor parameters. Setting an argument (debugService) of type DebugService will trigger the dependency injection to create a new DebugService object and set it into the ExpenseEntryListComponent component." }, { "code": null, "e": 15136, "s": 15030, "text": "Calling the info method of DebugService in the ngOnInit method prints the message in the browser console." }, { "code": null, "e": 15242, "s": 15136, "text": "Calling the info method of DebugService in the ngOnInit method prints the message in the browser console." }, { "code": null, "e": 15327, "s": 15242, "text": "The result can be viewed using developer tools and it looks similar as shown below −" }, { "code": null, "e": 15397, "s": 15327, "text": "Let us extend the application to understand the scope of the service." }, { "code": null, "e": 15464, "s": 15397, "text": "Let us a create a DebugComponent by using below mentioned command." }, { "code": null, "e": 15748, "s": 15464, "text": "ng generate component debug\nCREATE src/app/debug/debug.component.html (20 bytes) CREATE src/app/debug/debug.component.spec.ts (621 bytes) \nCREATE src/app/debug/debug.component.ts (265 bytes) CREATE src/app/debug/debug.component.css (0 bytes) UPDATE src/app/app.module.ts (392 bytes)\n" }, { "code": null, "e": 15799, "s": 15748, "text": "Let us remove the DebugService in the root module." }, { "code": null, "e": 16017, "s": 15799, "text": "// src/app/debug.service.ts\nimport { Injectable } from '@angular/core'; @Injectable() \nexport class DebugService { \n constructor() { \n }\n info(message : String) : void { \n console.log(message); \n } \n}" }, { "code": null, "e": 16086, "s": 16017, "text": "Register the DebugService under ExpenseEntryListComponent component." }, { "code": null, "e": 16345, "s": 16086, "text": "// src/app/expense-entry-list/expense-entry-list.component.ts @Component({ \n selector: 'app-expense-entry-list', \n templateUrl: './expense-entry-list.component.html', \n styleUrls: ['./expense-entry-list.component.css'] \n providers: [DebugService] \n})" }, { "code": null, "e": 16427, "s": 16345, "text": "Here, we have used providers meta data (ElementInjector) to register the service." }, { "code": null, "e": 16563, "s": 16427, "text": "Open DebugComponent (src/app/debug/debug.component.ts) and import DebugService and set an instance in the constructor of the component." }, { "code": null, "e": 16998, "s": 16563, "text": "import { Component, OnInit } from '@angular/core'; import { DebugService } from '../debug.service'; \n@Component({ \n selector: 'app-debug', \n templateUrl: './debug.component.html', \n styleUrls: ['./debug.component.css'] \n}) \nexport class DebugComponent implements OnInit { \n constructor(private debugService: DebugService) { } \n ngOnInit() { \n this.debugService.info(\"Debug component gets service from Parent\"); \n } \n}" }, { "code": null, "e": 17226, "s": 16998, "text": "Here, we have not registered DebugService. So, DebugService will not be available if used as parent component. When used inside a parent component, the service may available from parent, if the parent has access to the service." }, { "code": null, "e": 17375, "s": 17226, "text": "Open ExpenseEntryListComponent template (src/app/expense-entry-list/expense-entry-list.component.html) and include a content section as shown below:" }, { "code": null, "e": 17447, "s": 17375, "text": "// existing content \n<app-debug></app-debug>\n<ng-content></ng-content>\n" }, { "code": null, "e": 17516, "s": 17447, "text": "Here, we have included a content section and DebugComponent section." }, { "code": null, "e": 17713, "s": 17516, "text": "Let us include the debug component as a content inside the ExpenseEntryListComponent component in the AppComponent template. Open AppComponent template and change app-expense-entry-list as below −" }, { "code": null, "e": 17808, "s": 17713, "text": "// navigation code\n<app-expense-entry-list>\n<app-debug></app-debug>\n</app-expense-entry-list>\n" }, { "code": null, "e": 17862, "s": 17808, "text": "Here, we have included the DebugComponent as content." }, { "code": null, "e": 17970, "s": 17862, "text": "Let us check the application and it will show DebugService template at the end of the page as shown below −" }, { "code": null, "e": 18139, "s": 17970, "text": "Also, we could able to see two debug information from debug component in the console. This indicate that the debug component gets the service from its parent component." }, { "code": null, "e": 18402, "s": 18139, "text": "Let us change how the service is injected in the ExpenseEntryListComponent and how it affects the scope of the service. Change providers injector to viewProviders injection. viewProviders does not inject the service into the content child and so, it should fail." }, { "code": null, "e": 18433, "s": 18402, "text": "viewProviders: [DebugService]\n" }, { "code": null, "e": 18562, "s": 18433, "text": "Check the application and you will see that the one of the debug component (used as content child) throws error as shown below −" }, { "code": null, "e": 18642, "s": 18562, "text": "Let us remove the debug component in the templates and restore the application." }, { "code": null, "e": 18770, "s": 18642, "text": "Open ExpenseEntryListComponent template (src/app/expense-entry-list/expense-entry-list.component.html) and remove below content" }, { "code": null, "e": 18823, "s": 18770, "text": " \n<app-debug></app-debug>\n<ng-content></ng-content>\n" }, { "code": null, "e": 18895, "s": 18823, "text": "Open AppComponent template and change app-expense-entry-list as below −" }, { "code": null, "e": 18966, "s": 18895, "text": "// navigation code\n<app-expense-entry-list>\n</app-expense-entry-list>\n" }, { "code": null, "e": 19042, "s": 18966, "text": "Change the viewProviders setting to providers in ExpenseEntryListComponent." }, { "code": null, "e": 19069, "s": 19042, "text": "providers: [DebugService]\n" }, { "code": null, "e": 19113, "s": 19069, "text": "Rerun the application and check the result." }, { "code": null, "e": 19148, "s": 19113, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 19162, "s": 19148, "text": " Anadi Sharma" }, { "code": null, "e": 19197, "s": 19162, "text": "\n 28 Lectures \n 2.5 hours \n" }, { "code": null, "e": 19211, "s": 19197, "text": " Anadi Sharma" }, { "code": null, "e": 19246, "s": 19211, "text": "\n 11 Lectures \n 7.5 hours \n" }, { "code": null, "e": 19266, "s": 19246, "text": " SHIVPRASAD KOIRALA" }, { "code": null, "e": 19301, "s": 19266, "text": "\n 16 Lectures \n 2.5 hours \n" }, { "code": null, "e": 19318, "s": 19301, "text": " Frahaan Hussain" }, { "code": null, "e": 19351, "s": 19318, "text": "\n 69 Lectures \n 5 hours \n" }, { "code": null, "e": 19363, "s": 19351, "text": " Senol Atac" }, { "code": null, "e": 19398, "s": 19363, "text": "\n 53 Lectures \n 3.5 hours \n" }, { "code": null, "e": 19410, "s": 19398, "text": " Senol Atac" }, { "code": null, "e": 19417, "s": 19410, "text": " Print" }, { "code": null, "e": 19428, "s": 19417, "text": " Add Notes" } ]
How to perform scenario analysis of a financial portfolio in Python | by Gianluca Malato | Towards Data Science
Financial investors know that nobody can predict the future, but they also know that they must make at least a probabilistic idea of what the future can be. That’s why scenario analysis is a very powerful tool in an investor’s toolbox. Scenario analysis is a discipline that tries to give a probabilistic view of the possible future scenarios that may happen in relationship to a phenomenon. In a previous article, I’ve shown you how to perform portfolio optimization in R using a genetic algorithm. While portfolio optimization is a science, scenario analysis is almost like an art. It often starts from some assumptions and then simulates many future scenarios using Monte Carlo techniques. The higher the number of simulated scenarios, the higher the precision. Finally, the results of all the simulations are analyzed. For example, typical scenario analysis of a financial portfolio can be related to risk (e.g. what’s the probability that our portfolio will lose 3% within 30 days). In this article, I’ll show you how to apply scenario analysis to a financial portfolio. For this example, we’ll simulate a portfolio made by Microsoft (50%), Apple (20%) and Google (30%) stocks using their daily historical data from January 1 2010 to December 31 2019. We’ll correct their average return in a more pessimistic way than it was in the past and calculate the cumulative expected return of our portfolio, a confidence interval and the expected Sharpe ratio. Everything will be done in Python. You can get the full notebook on GitHub here: https://github.com/gianlucamalato/machinelearning/blob/master/Portfolio_scenario_analysis.ipynb First of all, we need to install the yfinance library. It allows us to download the stock prices directly from our notebook. !pip install yfinance Then we can import some useful libraries: import yfinanceimport pandas as pdimport numpy as npimport matplotlib.pyplot as plt For each stock, we want to calculate the daily return of the close price P from day t to day t+1, which is defined as Fortunately, Python series provide the useful pct_change method that calculates this formula for us. Let’s define the portfolio composition and the loop that fills a pandas data frame with the daily returns of each stock. portfolio_composition = [('MSFT',0.5),('AAPL',0.2),('GOOG',0.3)]returns = pd.DataFrame({})for t in portfolio_composition: name = t[0] ticker = yfinance.Ticker(name) data = ticker.history(interval="1d", start="2010-01-01",end="2019-12-31") data['return_%s' % (name)] = data['Close'].pct_change(1) returns = returns.join(data[['return_%s' % (name)]], how="outer").dropna() The returns data frame looks as follows: Now we are ready to simulate our data. If we want to simulate m days in the future we just have to: Take the original returns time series of a stock Select m values with replacement, taken randomly and uniformly That’s it. It’s very similar to bootstrap, which is a resampling technique. This method assumes that the future returns are a random resampling from the past returns. It’s a strong approximation, but it can be a good start point. This simulation can be easily performed with a single line of code as in the following function: def simulate_returns(historical_returns,forecast_days): return historical_returns.sample(n = forecast_days, replace = True).reset_index(drop = True) If we try to simulate 1000 days, we get: simulate_returns(returns['return_AAPL'],1000) Let’s now create the necessary function for simulating a portfolio. A portfolio is a combination of returns and weights. Given the returns Ri of the i-th stock and given the weight wi of each stock in the portfolio (all the weights must sum up to 1), the portfolio return R can be expressed as: that is the weighted sum of the stock returns. This is the function that performs all the calculations starting from the returns data frame we have created before: def simulate_portfolio(historical_returns, composition, forecast_days): result = 0 for t in composition: name,weight = t[0],t[1] s = simulate_returns(historical_returns['return_%s' % (name)], forecast_days) result = result + s * weight return(result) Let’s see what happens if we simulate 10 days of our portfolio: simulate_portfolio(returns,portfolio_composition,10) This may be enough for portfolio simulation, but we want something more, that is the what-if analysis. If we perform portfolio simulation as shown before, we are simply saying that the future returns are a random sample of the past returns. We already know this isn’t completely true. Moreover, maybe we are performing scenario analysis because we want to know what happens if certain conditions will occur. For example, what happens if the average daily return of each stock is lower than its historical value? The historical average returns are: Let’s try to simulate what happens if the average returns drop by -0.0001 for MSFT, -0.001 for AAPL and -0.0005 for GOOG. We must subtract these quantities from each stock and then simulate the future portfolios with the new, modified data. We’ll add these corrections directly to the portfolio_composition list (they are the third component of each tuple): portfolio_composition = [ ('MSFT', 0.5,-0.0001), ('AAPL', 0.2,-0.001), ('GOOG', 0.3,-0.0005)] We can then redefine all the previously defined function. This is the function that simulates the modified stocks: def simulate_modified_returns( historical_returns, forecast_days, correct_mean_by): h = historical_returns.copy() new_series = h + correct_mean_by return new_series.sample(n=forecast_days, replace = True).reset_index(drop=True) This is the function that simulates the modified portfolio: def simulate_modified_portfolio( historical_returns, composition, forecast_days): result = 0 for t in composition: name,weight,correction = t[0],t[1],t[2] s = simulate_modified_returns( historical_returns['return_%s' % (name)], forecast_days,correction ) result = result + s * weight return(result) Finally, we can define a function that performs portfolio simulation many times, generating many possible scenarios: def simulation( historical_returns, composition, forecast_days, n_iterations): simulated_portfolios = None for i in range(n_iterations): sim = simulate_modified_portfolio( historical_returns, composition, forecast_days ) sim_port = pd.DataFrame({'returns_%d' % (i) : sim}) if simulated_portfolios is None: simulated_portfolios = sim_port else: simulated_portfolios = simulated_portfolios.join(sim_port) return simulated_portfolios Now we are ready to start our simulations and analyze the results. Let’s simulate 20 days in the future calculating our statistics on 200 different scenarios. forecast_days = 20n_iterations = 200 We can now run the simulations: simulated_portfolios = simulation(returns, portfolio_composition,forecast_days,n_iterations) This function may take some seconds or even minutes if the number of iterations is high. This is the result: Each column is a scenario of a simulated portfolio and each row is a single day in the future. Taken the daily returns of a portfolio, we can build the return after N days with the compound interest formula: Since the returns are quite small numbers, we can approximate this expression as follows: That is, the return after N days is the sum of the returns of the N days. We can now calculate some observables from this dataset. Scenario analysis can be used as a risk management tool. For this purpose, we may want to calculate the 5th and the 95th percentile of the future cumulative return. The former tells you that there’s a 5% chance that our portfolio will underperform this value, the latter tells you there’s a 5% chance your portfolio will outperform this value. We also want to check how the average portfolio will perform. Here follows the code that calculates these 3 curves. percentile_5th = simulated_portfolios.cumsum().apply(lambda x : np.percentile(x,5),axis=1)percentile_95th = simulated_portfolios.cumsum().apply(lambda x : np.percentile(x,95),axis=1)average_port = simulated_portfolios.cumsum().apply(lambda x : np.mean(x),axis=1) And here’s the plot. The bands are the percentiles and the solid line is the average portfolio. As you can see, after 20 days there’s a 5% probability that our portfolio will lose 5.3% (lower band) and there’s a 5% probability that our portfolio return will be greater than 8.3% (upper band). On average, we expect our portfolio to have a 1% return (solid line). Another kind of analysis we can perform is the probability that our portfolio will outperform a target return as a function of the day in the future. Since probability is an observable value, we’d like to calculate its standard error too. If we have a sample probability p (that is, the number of positive occurrences divided by the number N of scenarios), an estimate of its standard error is: We can use this value, calculated day by day, to show the error bars in our chart. Let’s assume we have a 2% target. The probability of beating this target is calculated by: target_return = 0.02target_prob_port = simulated_portfolios.cumsum().apply( lambda x : np.mean(x > target_return) ,axis=1) The size of the error bars is calculated with the standard error formula: err_bars = np.sqrt( target_prob_port * (1-target_prob_port) / n_iterations) Finally, we can plot the results: As you can see, the probability of overperforming our target return increases with time (that’s obviously true since our portfolio has a positive average return). After 20 days, our portfolio will outperform the 2% target with a 38.0 +/- 3.4% probability. Finally, we can calculate some statistics related to Sharpe ratio. It’s a very popular performance metric of a portfolio and, for this example, we can calculate the Sharpe ratio of the returns R of a portfolio as follows: where E(x) is the expected value and Var(x) is the variance. Each of our 200 portfolio scenarios has its own Sharpe ratio, so we can calculate it for each one of them. Then we can plot a histogram and calculate the average value. sharpe_indices = simulated_portfolios.apply( lambda x : np.mean(x)/np.std(x)) The histogram is: The mean value is: In this article, I’ve shown you how to perform a simple scenario analysis for a financial portfolio in Python. This approach can be adapted to many problems and scenarios (e.g. increasing volatility, black swans, a crisis of some industries) in order to assess the possible future risk of a portfolio and its ability to grow up. This tool could be easily mixed with portfolio optimization in order to assess a complete analysis of financial asset allocation. [1] Gianluca Malato. Portfolio optimization in R using a Genetic Algorithm. The Trading Scientist. https://medium.com/the-trading-scientist/portfolio-optimization-in-r-using-a-genetic-algorithm-8726ec985b6f [2] Gianluca Malato. The bootstrap. The Swiss army knife of any data scientist. Data Science Reporter. https://medium.com/data-science-reporter/the-bootstrap-the-swiss-army-knife-of-any-data-scientist-acd6e592be13 [3] Binomial distribution page. Wikipedia. https://en.wikipedia.org/wiki/Binomial_distribution [4] Sharpe ratio page. Wikipedia. https://en.wikipedia.org/wiki/Sharpe_ratio
[ { "code": null, "e": 408, "s": 172, "text": "Financial investors know that nobody can predict the future, but they also know that they must make at least a probabilistic idea of what the future can be. That’s why scenario analysis is a very powerful tool in an investor’s toolbox." }, { "code": null, "e": 564, "s": 408, "text": "Scenario analysis is a discipline that tries to give a probabilistic view of the possible future scenarios that may happen in relationship to a phenomenon." }, { "code": null, "e": 1160, "s": 564, "text": "In a previous article, I’ve shown you how to perform portfolio optimization in R using a genetic algorithm. While portfolio optimization is a science, scenario analysis is almost like an art. It often starts from some assumptions and then simulates many future scenarios using Monte Carlo techniques. The higher the number of simulated scenarios, the higher the precision. Finally, the results of all the simulations are analyzed. For example, typical scenario analysis of a financial portfolio can be related to risk (e.g. what’s the probability that our portfolio will lose 3% within 30 days)." }, { "code": null, "e": 1630, "s": 1160, "text": "In this article, I’ll show you how to apply scenario analysis to a financial portfolio. For this example, we’ll simulate a portfolio made by Microsoft (50%), Apple (20%) and Google (30%) stocks using their daily historical data from January 1 2010 to December 31 2019. We’ll correct their average return in a more pessimistic way than it was in the past and calculate the cumulative expected return of our portfolio, a confidence interval and the expected Sharpe ratio." }, { "code": null, "e": 1807, "s": 1630, "text": "Everything will be done in Python. You can get the full notebook on GitHub here: https://github.com/gianlucamalato/machinelearning/blob/master/Portfolio_scenario_analysis.ipynb" }, { "code": null, "e": 1932, "s": 1807, "text": "First of all, we need to install the yfinance library. It allows us to download the stock prices directly from our notebook." }, { "code": null, "e": 1954, "s": 1932, "text": "!pip install yfinance" }, { "code": null, "e": 1996, "s": 1954, "text": "Then we can import some useful libraries:" }, { "code": null, "e": 2080, "s": 1996, "text": "import yfinanceimport pandas as pdimport numpy as npimport matplotlib.pyplot as plt" }, { "code": null, "e": 2198, "s": 2080, "text": "For each stock, we want to calculate the daily return of the close price P from day t to day t+1, which is defined as" }, { "code": null, "e": 2299, "s": 2198, "text": "Fortunately, Python series provide the useful pct_change method that calculates this formula for us." }, { "code": null, "e": 2420, "s": 2299, "text": "Let’s define the portfolio composition and the loop that fills a pandas data frame with the daily returns of each stock." }, { "code": null, "e": 2806, "s": 2420, "text": "portfolio_composition = [('MSFT',0.5),('AAPL',0.2),('GOOG',0.3)]returns = pd.DataFrame({})for t in portfolio_composition: name = t[0] ticker = yfinance.Ticker(name) data = ticker.history(interval=\"1d\", start=\"2010-01-01\",end=\"2019-12-31\") data['return_%s' % (name)] = data['Close'].pct_change(1) returns = returns.join(data[['return_%s' % (name)]], how=\"outer\").dropna()" }, { "code": null, "e": 2847, "s": 2806, "text": "The returns data frame looks as follows:" }, { "code": null, "e": 2886, "s": 2847, "text": "Now we are ready to simulate our data." }, { "code": null, "e": 2947, "s": 2886, "text": "If we want to simulate m days in the future we just have to:" }, { "code": null, "e": 2996, "s": 2947, "text": "Take the original returns time series of a stock" }, { "code": null, "e": 3059, "s": 2996, "text": "Select m values with replacement, taken randomly and uniformly" }, { "code": null, "e": 3289, "s": 3059, "text": "That’s it. It’s very similar to bootstrap, which is a resampling technique. This method assumes that the future returns are a random resampling from the past returns. It’s a strong approximation, but it can be a good start point." }, { "code": null, "e": 3386, "s": 3289, "text": "This simulation can be easily performed with a single line of code as in the following function:" }, { "code": null, "e": 3552, "s": 3386, "text": "def simulate_returns(historical_returns,forecast_days): return historical_returns.sample(n = forecast_days, replace = True).reset_index(drop = True)" }, { "code": null, "e": 3593, "s": 3552, "text": "If we try to simulate 1000 days, we get:" }, { "code": null, "e": 3639, "s": 3593, "text": "simulate_returns(returns['return_AAPL'],1000)" }, { "code": null, "e": 3707, "s": 3639, "text": "Let’s now create the necessary function for simulating a portfolio." }, { "code": null, "e": 3934, "s": 3707, "text": "A portfolio is a combination of returns and weights. Given the returns Ri of the i-th stock and given the weight wi of each stock in the portfolio (all the weights must sum up to 1), the portfolio return R can be expressed as:" }, { "code": null, "e": 3981, "s": 3934, "text": "that is the weighted sum of the stock returns." }, { "code": null, "e": 4098, "s": 3981, "text": "This is the function that performs all the calculations starting from the returns data frame we have created before:" }, { "code": null, "e": 4375, "s": 4098, "text": "def simulate_portfolio(historical_returns, composition, forecast_days): result = 0 for t in composition: name,weight = t[0],t[1] s = simulate_returns(historical_returns['return_%s' % (name)], forecast_days) result = result + s * weight return(result)" }, { "code": null, "e": 4439, "s": 4375, "text": "Let’s see what happens if we simulate 10 days of our portfolio:" }, { "code": null, "e": 4492, "s": 4439, "text": "simulate_portfolio(returns,portfolio_composition,10)" }, { "code": null, "e": 4595, "s": 4492, "text": "This may be enough for portfolio simulation, but we want something more, that is the what-if analysis." }, { "code": null, "e": 5004, "s": 4595, "text": "If we perform portfolio simulation as shown before, we are simply saying that the future returns are a random sample of the past returns. We already know this isn’t completely true. Moreover, maybe we are performing scenario analysis because we want to know what happens if certain conditions will occur. For example, what happens if the average daily return of each stock is lower than its historical value?" }, { "code": null, "e": 5040, "s": 5004, "text": "The historical average returns are:" }, { "code": null, "e": 5281, "s": 5040, "text": "Let’s try to simulate what happens if the average returns drop by -0.0001 for MSFT, -0.001 for AAPL and -0.0005 for GOOG. We must subtract these quantities from each stock and then simulate the future portfolios with the new, modified data." }, { "code": null, "e": 5398, "s": 5281, "text": "We’ll add these corrections directly to the portfolio_composition list (they are the third component of each tuple):" }, { "code": null, "e": 5500, "s": 5398, "text": "portfolio_composition = [ ('MSFT', 0.5,-0.0001), ('AAPL', 0.2,-0.001), ('GOOG', 0.3,-0.0005)]" }, { "code": null, "e": 5558, "s": 5500, "text": "We can then redefine all the previously defined function." }, { "code": null, "e": 5615, "s": 5558, "text": "This is the function that simulates the modified stocks:" }, { "code": null, "e": 5867, "s": 5615, "text": "def simulate_modified_returns( historical_returns, forecast_days, correct_mean_by): h = historical_returns.copy() new_series = h + correct_mean_by return new_series.sample(n=forecast_days, replace = True).reset_index(drop=True)" }, { "code": null, "e": 5927, "s": 5867, "text": "This is the function that simulates the modified portfolio:" }, { "code": null, "e": 6270, "s": 5927, "text": "def simulate_modified_portfolio( historical_returns, composition, forecast_days): result = 0 for t in composition: name,weight,correction = t[0],t[1],t[2] s = simulate_modified_returns( historical_returns['return_%s' % (name)], forecast_days,correction ) result = result + s * weight return(result)" }, { "code": null, "e": 6387, "s": 6270, "text": "Finally, we can define a function that performs portfolio simulation many times, generating many possible scenarios:" }, { "code": null, "e": 6892, "s": 6387, "text": "def simulation( historical_returns, composition, forecast_days, n_iterations): simulated_portfolios = None for i in range(n_iterations): sim = simulate_modified_portfolio( historical_returns, composition, forecast_days ) sim_port = pd.DataFrame({'returns_%d' % (i) : sim}) if simulated_portfolios is None: simulated_portfolios = sim_port else: simulated_portfolios = simulated_portfolios.join(sim_port) return simulated_portfolios" }, { "code": null, "e": 6959, "s": 6892, "text": "Now we are ready to start our simulations and analyze the results." }, { "code": null, "e": 7051, "s": 6959, "text": "Let’s simulate 20 days in the future calculating our statistics on 200 different scenarios." }, { "code": null, "e": 7088, "s": 7051, "text": "forecast_days = 20n_iterations = 200" }, { "code": null, "e": 7120, "s": 7088, "text": "We can now run the simulations:" }, { "code": null, "e": 7216, "s": 7120, "text": "simulated_portfolios = simulation(returns, portfolio_composition,forecast_days,n_iterations)" }, { "code": null, "e": 7305, "s": 7216, "text": "This function may take some seconds or even minutes if the number of iterations is high." }, { "code": null, "e": 7325, "s": 7305, "text": "This is the result:" }, { "code": null, "e": 7420, "s": 7325, "text": "Each column is a scenario of a simulated portfolio and each row is a single day in the future." }, { "code": null, "e": 7533, "s": 7420, "text": "Taken the daily returns of a portfolio, we can build the return after N days with the compound interest formula:" }, { "code": null, "e": 7623, "s": 7533, "text": "Since the returns are quite small numbers, we can approximate this expression as follows:" }, { "code": null, "e": 7697, "s": 7623, "text": "That is, the return after N days is the sum of the returns of the N days." }, { "code": null, "e": 7754, "s": 7697, "text": "We can now calculate some observables from this dataset." }, { "code": null, "e": 8160, "s": 7754, "text": "Scenario analysis can be used as a risk management tool. For this purpose, we may want to calculate the 5th and the 95th percentile of the future cumulative return. The former tells you that there’s a 5% chance that our portfolio will underperform this value, the latter tells you there’s a 5% chance your portfolio will outperform this value. We also want to check how the average portfolio will perform." }, { "code": null, "e": 8214, "s": 8160, "text": "Here follows the code that calculates these 3 curves." }, { "code": null, "e": 8477, "s": 8214, "text": "percentile_5th = simulated_portfolios.cumsum().apply(lambda x : np.percentile(x,5),axis=1)percentile_95th = simulated_portfolios.cumsum().apply(lambda x : np.percentile(x,95),axis=1)average_port = simulated_portfolios.cumsum().apply(lambda x : np.mean(x),axis=1)" }, { "code": null, "e": 8498, "s": 8477, "text": "And here’s the plot." }, { "code": null, "e": 8840, "s": 8498, "text": "The bands are the percentiles and the solid line is the average portfolio. As you can see, after 20 days there’s a 5% probability that our portfolio will lose 5.3% (lower band) and there’s a 5% probability that our portfolio return will be greater than 8.3% (upper band). On average, we expect our portfolio to have a 1% return (solid line)." }, { "code": null, "e": 8990, "s": 8840, "text": "Another kind of analysis we can perform is the probability that our portfolio will outperform a target return as a function of the day in the future." }, { "code": null, "e": 9079, "s": 8990, "text": "Since probability is an observable value, we’d like to calculate its standard error too." }, { "code": null, "e": 9235, "s": 9079, "text": "If we have a sample probability p (that is, the number of positive occurrences divided by the number N of scenarios), an estimate of its standard error is:" }, { "code": null, "e": 9318, "s": 9235, "text": "We can use this value, calculated day by day, to show the error bars in our chart." }, { "code": null, "e": 9409, "s": 9318, "text": "Let’s assume we have a 2% target. The probability of beating this target is calculated by:" }, { "code": null, "e": 9539, "s": 9409, "text": "target_return = 0.02target_prob_port = simulated_portfolios.cumsum().apply( lambda x : np.mean(x > target_return) ,axis=1)" }, { "code": null, "e": 9613, "s": 9539, "text": "The size of the error bars is calculated with the standard error formula:" }, { "code": null, "e": 9691, "s": 9613, "text": "err_bars = np.sqrt( target_prob_port * (1-target_prob_port) / n_iterations)" }, { "code": null, "e": 9725, "s": 9691, "text": "Finally, we can plot the results:" }, { "code": null, "e": 9981, "s": 9725, "text": "As you can see, the probability of overperforming our target return increases with time (that’s obviously true since our portfolio has a positive average return). After 20 days, our portfolio will outperform the 2% target with a 38.0 +/- 3.4% probability." }, { "code": null, "e": 10203, "s": 9981, "text": "Finally, we can calculate some statistics related to Sharpe ratio. It’s a very popular performance metric of a portfolio and, for this example, we can calculate the Sharpe ratio of the returns R of a portfolio as follows:" }, { "code": null, "e": 10264, "s": 10203, "text": "where E(x) is the expected value and Var(x) is the variance." }, { "code": null, "e": 10433, "s": 10264, "text": "Each of our 200 portfolio scenarios has its own Sharpe ratio, so we can calculate it for each one of them. Then we can plot a histogram and calculate the average value." }, { "code": null, "e": 10513, "s": 10433, "text": "sharpe_indices = simulated_portfolios.apply( lambda x : np.mean(x)/np.std(x))" }, { "code": null, "e": 10531, "s": 10513, "text": "The histogram is:" }, { "code": null, "e": 10550, "s": 10531, "text": "The mean value is:" }, { "code": null, "e": 10879, "s": 10550, "text": "In this article, I’ve shown you how to perform a simple scenario analysis for a financial portfolio in Python. This approach can be adapted to many problems and scenarios (e.g. increasing volatility, black swans, a crisis of some industries) in order to assess the possible future risk of a portfolio and its ability to grow up." }, { "code": null, "e": 11009, "s": 10879, "text": "This tool could be easily mixed with portfolio optimization in order to assess a complete analysis of financial asset allocation." }, { "code": null, "e": 11216, "s": 11009, "text": "[1] Gianluca Malato. Portfolio optimization in R using a Genetic Algorithm. The Trading Scientist. https://medium.com/the-trading-scientist/portfolio-optimization-in-r-using-a-genetic-algorithm-8726ec985b6f" }, { "code": null, "e": 11430, "s": 11216, "text": "[2] Gianluca Malato. The bootstrap. The Swiss army knife of any data scientist. Data Science Reporter. https://medium.com/data-science-reporter/the-bootstrap-the-swiss-army-knife-of-any-data-scientist-acd6e592be13" }, { "code": null, "e": 11525, "s": 11430, "text": "[3] Binomial distribution page. Wikipedia. https://en.wikipedia.org/wiki/Binomial_distribution" } ]
SWING - MouseListener Interface
The class which processes the MouseEvent should implement this interface. The object of that class must be registered with a component. The object can be registered using the addMouseListener() method. Following is the declaration for java.awt.event.MouseListener interface − public interface MouseListener extends EventListener void mouseClicked(MouseEvent e) Invoked when the mouse button has been clicked (pressed and released) on a component. void mouseEntered(MouseEvent e) Invoked when the mouse enters a component. void mouseExited(MouseEvent e) Invoked when the mouse exits a component. void mousePressed(MouseEvent e) Invoked when a mouse button has been pressed on a component. void mouseReleased(MouseEvent e) Invoked when a mouse button has been released on a component. This interface inherits methods from the following interfaces − java.awt.EventListener java.awt.EventListener Create the following Java program using any editor of your choice in say D:/ > SWING > com > tutorialspoint > gui > SwingListenerDemo.java package com.tutorialspoint.gui; import java.awt.*; import java.awt.event.*; import javax.swing.*; public class SwingListenerDemo { private JFrame mainFrame; private JLabel headerLabel; private JLabel statusLabel; private JPanel controlPanel; public SwingListenerDemo(){ prepareGUI(); } public static void main(String[] args){ SwingListenerDemo swingListenerDemo = new SwingListenerDemo(); swingListenerDemo.showMouseListenerDemo(); } private void prepareGUI(){ mainFrame = new JFrame("Java SWING Examples"); mainFrame.setSize(400,400); mainFrame.setLayout(new GridLayout(3, 1)); headerLabel = new JLabel("",JLabel.CENTER ); statusLabel = new JLabel("",JLabel.CENTER); statusLabel.setSize(350,100); mainFrame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent windowEvent){ System.exit(0); } }); controlPanel = new JPanel(); controlPanel.setLayout(new FlowLayout()); mainFrame.add(headerLabel); mainFrame.add(controlPanel); mainFrame.add(statusLabel); mainFrame.setVisible(true); } private void showMouseListenerDemo(){ headerLabel.setText("Listener in action: MouseListener"); JPanel panel = new JPanel(); panel.setBackground(Color.magenta); panel.setLayout(new FlowLayout()); panel.addMouseListener(new CustomMouseListener()); JLabel msglabel = new JLabel("Welcome to TutorialsPoint SWING Tutorial.",JLabel.CENTER); panel.add(msglabel); msglabel.addMouseListener(new CustomMouseListener()); panel.add(msglabel); controlPanel.add(panel); mainFrame.setVisible(true); } class CustomMouseListener implements MouseListener { public void mouseClicked(MouseEvent e) { statusLabel.setText("Mouse Clicked: ("+e.getX()+", "+e.getY() +")"); } public void mousePressed(MouseEvent e) { } public void mouseReleased(MouseEvent e) { } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } } } Compile the program using the command prompt. Go to D:/ > SWING and type the following command. D:\SWING>javac com\tutorialspoint\gui\SwingListenerDemo.java If no error occurs, it means the compilation is successful. Run the program using the following command. D:\SWING>java com.tutorialspoint.gui.SwingListenerDemo Verify the following output. 30 Lectures 3.5 hours Pranjal Srivastava 13 Lectures 1 hours Pranjal Srivastava 25 Lectures 4.5 hours Emenwa Global, Ejike IfeanyiChukwu 14 Lectures 1.5 hours Travis Rose 14 Lectures 1 hours Travis Rose Print Add Notes Bookmark this page
[ { "code": null, "e": 1965, "s": 1763, "text": "The class which processes the MouseEvent should implement this interface. The object of that class must be registered with a component. The object can be registered using the addMouseListener() method." }, { "code": null, "e": 2039, "s": 1965, "text": "Following is the declaration for java.awt.event.MouseListener interface −" }, { "code": null, "e": 2096, "s": 2039, "text": "public interface MouseListener\n extends EventListener\n" }, { "code": null, "e": 2128, "s": 2096, "text": "void mouseClicked(MouseEvent e)" }, { "code": null, "e": 2214, "s": 2128, "text": "Invoked when the mouse button has been clicked (pressed and released) on a component." }, { "code": null, "e": 2246, "s": 2214, "text": "void mouseEntered(MouseEvent e)" }, { "code": null, "e": 2289, "s": 2246, "text": "Invoked when the mouse enters a component." }, { "code": null, "e": 2320, "s": 2289, "text": "void mouseExited(MouseEvent e)" }, { "code": null, "e": 2362, "s": 2320, "text": "Invoked when the mouse exits a component." }, { "code": null, "e": 2394, "s": 2362, "text": "void mousePressed(MouseEvent e)" }, { "code": null, "e": 2455, "s": 2394, "text": "Invoked when a mouse button has been pressed on a component." }, { "code": null, "e": 2488, "s": 2455, "text": "void mouseReleased(MouseEvent e)" }, { "code": null, "e": 2550, "s": 2488, "text": "Invoked when a mouse button has been released on a component." }, { "code": null, "e": 2614, "s": 2550, "text": "This interface inherits methods from the following interfaces −" }, { "code": null, "e": 2637, "s": 2614, "text": "java.awt.EventListener" }, { "code": null, "e": 2660, "s": 2637, "text": "java.awt.EventListener" }, { "code": null, "e": 2776, "s": 2660, "text": "Create the following Java program using any editor of your choice in say D:/ > SWING > com > tutorialspoint > gui >" }, { "code": null, "e": 2799, "s": 2776, "text": "SwingListenerDemo.java" }, { "code": null, "e": 5022, "s": 2799, "text": "package com.tutorialspoint.gui;\n\nimport java.awt.*;\nimport java.awt.event.*;\nimport javax.swing.*;\n\npublic class SwingListenerDemo {\n private JFrame mainFrame;\n private JLabel headerLabel;\n private JLabel statusLabel;\n private JPanel controlPanel;\n\n public SwingListenerDemo(){\n prepareGUI();\n }\n public static void main(String[] args){\n SwingListenerDemo swingListenerDemo = new SwingListenerDemo(); \n swingListenerDemo.showMouseListenerDemo();\n }\n private void prepareGUI(){\n mainFrame = new JFrame(\"Java SWING Examples\");\n mainFrame.setSize(400,400);\n mainFrame.setLayout(new GridLayout(3, 1));\n\n headerLabel = new JLabel(\"\",JLabel.CENTER );\n statusLabel = new JLabel(\"\",JLabel.CENTER); \n statusLabel.setSize(350,100);\n \n mainFrame.addWindowListener(new WindowAdapter() {\n public void windowClosing(WindowEvent windowEvent){\n System.exit(0);\n } \n }); \n controlPanel = new JPanel();\n controlPanel.setLayout(new FlowLayout());\n\n mainFrame.add(headerLabel);\n mainFrame.add(controlPanel);\n mainFrame.add(statusLabel);\n mainFrame.setVisible(true); \n }\n private void showMouseListenerDemo(){\n headerLabel.setText(\"Listener in action: MouseListener\"); \n\n JPanel panel = new JPanel(); \n panel.setBackground(Color.magenta);\n panel.setLayout(new FlowLayout()); \n panel.addMouseListener(new CustomMouseListener());\n\n JLabel msglabel = \n new JLabel(\"Welcome to TutorialsPoint SWING Tutorial.\",JLabel.CENTER); \n panel.add(msglabel);\n\n msglabel.addMouseListener(new CustomMouseListener());\n panel.add(msglabel);\n\n controlPanel.add(panel);\n mainFrame.setVisible(true); \n }\n class CustomMouseListener implements MouseListener {\n public void mouseClicked(MouseEvent e) {\n statusLabel.setText(\"Mouse Clicked: (\"+e.getX()+\", \"+e.getY() +\")\");\n }\n public void mousePressed(MouseEvent e) {\n }\n public void mouseReleased(MouseEvent e) {\n }\n public void mouseEntered(MouseEvent e) {\n }\n public void mouseExited(MouseEvent e) {\n }\n }\n}" }, { "code": null, "e": 5118, "s": 5022, "text": "Compile the program using the command prompt. Go to D:/ > SWING and type the following command." }, { "code": null, "e": 5180, "s": 5118, "text": "D:\\SWING>javac com\\tutorialspoint\\gui\\SwingListenerDemo.java\n" }, { "code": null, "e": 5285, "s": 5180, "text": "If no error occurs, it means the compilation is successful. Run the program using the following command." }, { "code": null, "e": 5341, "s": 5285, "text": "D:\\SWING>java com.tutorialspoint.gui.SwingListenerDemo\n" }, { "code": null, "e": 5370, "s": 5341, "text": "Verify the following output." }, { "code": null, "e": 5405, "s": 5370, "text": "\n 30 Lectures \n 3.5 hours \n" }, { "code": null, "e": 5425, "s": 5405, "text": " Pranjal Srivastava" }, { "code": null, "e": 5458, "s": 5425, "text": "\n 13 Lectures \n 1 hours \n" }, { "code": null, "e": 5478, "s": 5458, "text": " Pranjal Srivastava" }, { "code": null, "e": 5513, "s": 5478, "text": "\n 25 Lectures \n 4.5 hours \n" }, { "code": null, "e": 5549, "s": 5513, "text": " Emenwa Global, Ejike IfeanyiChukwu" }, { "code": null, "e": 5584, "s": 5549, "text": "\n 14 Lectures \n 1.5 hours \n" }, { "code": null, "e": 5597, "s": 5584, "text": " Travis Rose" }, { "code": null, "e": 5630, "s": 5597, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 5643, "s": 5630, "text": " Travis Rose" }, { "code": null, "e": 5650, "s": 5643, "text": " Print" }, { "code": null, "e": 5661, "s": 5650, "text": " Add Notes" } ]
How to Create Marquee Text in Android? - GeeksforGeeks
31 Mar, 2021 In this article, we are going to create Marquee Text in Android Studio. Marquee is a scrolling piece of text that is displayed either horizontally or vertically. It is used to show some important notice or headlines. It makes app UI much attractive. Note that we are going to use Java as the programming language. A sample GIF is given below to get an idea about what we are going to do in this article. Step 1: Create a New Project To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that you have to select Java as the programming language. Step 2: Working with the activity_main.xml file Navigate to the app > res > layout > activity_main.xml and add the below code to that file. TextView is used here to add the text which we want to display on the screen. Here we have used android:ellipsize=”marquee” to add a marquee to our text and android:singleLine=”true” so that our text will show only in one line. Also, we have used android:marqueeRepeatLimit=”marquee_forever” so that marquee will repeat infinitely and one more attribute that I have used here is android:scrollHorizontally=”true” so that text will scroll horizontally. XML <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <!-- Textview is used here to add the text which we want to display on the screen.Here important attributes are: i) android:singleLine="true"... so that our text will show only in one line ii) android:ellipsize="marquee"... to add marquee to our text iii) android:marqueeRepeatLimit="marquee_forever"...so that marquee will repeat infinitely iv) android:scrollHorizontally="true"... so that text will scroll horizontally --> <TextView android:id="@+id/marqueeText" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="25sp" android:ellipsize="marquee" android:marqueeRepeatLimit="marquee_forever" android:padding="10dp" android:scrollHorizontally="true" android:singleLine="true" android:text="Hello guys !! Welcome to GeeksforGeeks Portal !!" android:textSize="20sp" android:textStyle="bold" /> </RelativeLayout> Step 3: Working with the MainActivity.java file Go to MainActivity.java Class. We have called the setSelected() method and passing the boolean value as true so that our marquee will get started. Below is the code for the MainActivity.java file. Java import android.os.Bundle;import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { TextView txtMarquee; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // casting of textview txtMarquee = (TextView) findViewById(R.id.marqueeText); // Now we will call setSelected() method // and pass boolean value as true txtMarquee.setSelected(true); }} Step 4: Working with colors.xml file Navigate to the app > res > values > colors.xml. You can add as many colors as you need for your app. You have to just give a color code and put the color name. In this app, we have kept the app bar color as green with the color-code “#0F9D58”. XML <?xml version="1.0" encoding="utf-8"?><resources> <color name="Green">#0F9D58</color> <color name="purple_500">#FF6200EE</color> <color name="purple_700">#FF3700B3</color> <color name="teal_200">#FF03DAC5</color> <color name="teal_700">#FF018786</color> <color name="black">#FF000000</color> <color name="white">#FFFFFFFF</color></resources> Step 5: Working with themes.xml Navigate to the app > res > values > themes.xml and choose the theme of your choice. We have used parent=”Theme.MaterialComponents.DayNight.DarkActionBar” that is DayNight theme with dark ActionBar. You can add parent=”Theme.AppCompat.Light.DarkActionBar” to get light theme with dark action bar and parent=”Theme.AppCompat.Light.DarkActionBar” for light theme with dark action bar. XML <resources xmlns:tools="http://schemas.android.com/tools"> <!-- Base application theme. --> <style name="Theme.MarqueeText" parent="Theme.MaterialComponents.DayNight.DarkActionBar"> <!-- Primary brand color. --> <item name="colorPrimary">@color/Green</item> <item name="colorPrimaryVariant">@color/Green</item> <item name="colorOnPrimary">@color/white</item> <!-- Secondary brand color. --> <item name="colorSecondary">@color/teal_200</item> <item name="colorSecondaryVariant">@color/teal_700</item> <item name="colorOnSecondary">@color/black</item> <!-- Status bar color. --> <item name="android:statusBarColor" tools:targetApi="l">?attr/colorPrimaryVariant</item> <!-- Customize your theme here. --> </style></resources> Step 6: Working with strings.xml Navigate to the app > res > values > strings.xml. Here you can add an app bar title. We have set “GFG | MarqueeText” as a title. XML <resources> <string name="app_name">GFG | MarqueeText</string></resources> Output: Android-Misc Android Java Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Flutter - Custom Bottom Navigation Bar How to Read Data from SQLite Database in Android? How to Post Data to API using Retrofit in Android? Android Listview in Java with Example Retrofit with Kotlin Coroutine in Android Arrays in Java Split() String method in Java with examples For-each loop in Java Reverse a string in Java Arrays.sort() in Java with examples
[ { "code": null, "e": 24749, "s": 24721, "text": "\n31 Mar, 2021" }, { "code": null, "e": 25153, "s": 24749, "text": "In this article, we are going to create Marquee Text in Android Studio. Marquee is a scrolling piece of text that is displayed either horizontally or vertically. It is used to show some important notice or headlines. It makes app UI much attractive. Note that we are going to use Java as the programming language. A sample GIF is given below to get an idea about what we are going to do in this article." }, { "code": null, "e": 25182, "s": 25153, "text": "Step 1: Create a New Project" }, { "code": null, "e": 25357, "s": 25182, "text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that you have to select Java as the programming language. " }, { "code": null, "e": 25405, "s": 25357, "text": "Step 2: Working with the activity_main.xml file" }, { "code": null, "e": 25957, "s": 25405, "text": "Navigate to the app > res > layout > activity_main.xml and add the below code to that file. TextView is used here to add the text which we want to display on the screen. Here we have used android:ellipsize=”marquee” to add a marquee to our text and android:singleLine=”true” so that our text will show only in one line. Also, we have used android:marqueeRepeatLimit=”marquee_forever” so that marquee will repeat infinitely and one more attribute that I have used here is android:scrollHorizontally=”true” so that text will scroll horizontally. " }, { "code": null, "e": 25961, "s": 25957, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <!-- Textview is used here to add the text which we want to display on the screen.Here important attributes are: i) android:singleLine=\"true\"... so that our text will show only in one line ii) android:ellipsize=\"marquee\"... to add marquee to our text iii) android:marqueeRepeatLimit=\"marquee_forever\"...so that marquee will repeat infinitely iv) android:scrollHorizontally=\"true\"... so that text will scroll horizontally --> <TextView android:id=\"@+id/marqueeText\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"25sp\" android:ellipsize=\"marquee\" android:marqueeRepeatLimit=\"marquee_forever\" android:padding=\"10dp\" android:scrollHorizontally=\"true\" android:singleLine=\"true\" android:text=\"Hello guys !! Welcome to GeeksforGeeks Portal !!\" android:textSize=\"20sp\" android:textStyle=\"bold\" /> </RelativeLayout>", "e": 27224, "s": 25961, "text": null }, { "code": null, "e": 27272, "s": 27224, "text": "Step 3: Working with the MainActivity.java file" }, { "code": null, "e": 27469, "s": 27272, "text": "Go to MainActivity.java Class. We have called the setSelected() method and passing the boolean value as true so that our marquee will get started. Below is the code for the MainActivity.java file." }, { "code": null, "e": 27474, "s": 27469, "text": "Java" }, { "code": "import android.os.Bundle;import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { TextView txtMarquee; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // casting of textview txtMarquee = (TextView) findViewById(R.id.marqueeText); // Now we will call setSelected() method // and pass boolean value as true txtMarquee.setSelected(true); }}", "e": 28064, "s": 27474, "text": null }, { "code": null, "e": 28101, "s": 28064, "text": "Step 4: Working with colors.xml file" }, { "code": null, "e": 28347, "s": 28101, "text": "Navigate to the app > res > values > colors.xml. You can add as many colors as you need for your app. You have to just give a color code and put the color name. In this app, we have kept the app bar color as green with the color-code “#0F9D58”. " }, { "code": null, "e": 28351, "s": 28347, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><resources> <color name=\"Green\">#0F9D58</color> <color name=\"purple_500\">#FF6200EE</color> <color name=\"purple_700\">#FF3700B3</color> <color name=\"teal_200\">#FF03DAC5</color> <color name=\"teal_700\">#FF018786</color> <color name=\"black\">#FF000000</color> <color name=\"white\">#FFFFFFFF</color></resources>", "e": 28714, "s": 28351, "text": null }, { "code": null, "e": 28746, "s": 28714, "text": "Step 5: Working with themes.xml" }, { "code": null, "e": 29129, "s": 28746, "text": "Navigate to the app > res > values > themes.xml and choose the theme of your choice. We have used parent=”Theme.MaterialComponents.DayNight.DarkActionBar” that is DayNight theme with dark ActionBar. You can add parent=”Theme.AppCompat.Light.DarkActionBar” to get light theme with dark action bar and parent=”Theme.AppCompat.Light.DarkActionBar” for light theme with dark action bar." }, { "code": null, "e": 29133, "s": 29129, "text": "XML" }, { "code": "<resources xmlns:tools=\"http://schemas.android.com/tools\"> <!-- Base application theme. --> <style name=\"Theme.MarqueeText\" parent=\"Theme.MaterialComponents.DayNight.DarkActionBar\"> <!-- Primary brand color. --> <item name=\"colorPrimary\">@color/Green</item> <item name=\"colorPrimaryVariant\">@color/Green</item> <item name=\"colorOnPrimary\">@color/white</item> <!-- Secondary brand color. --> <item name=\"colorSecondary\">@color/teal_200</item> <item name=\"colorSecondaryVariant\">@color/teal_700</item> <item name=\"colorOnSecondary\">@color/black</item> <!-- Status bar color. --> <item name=\"android:statusBarColor\" tools:targetApi=\"l\">?attr/colorPrimaryVariant</item> <!-- Customize your theme here. --> </style></resources>", "e": 29949, "s": 29133, "text": null }, { "code": null, "e": 29982, "s": 29949, "text": "Step 6: Working with strings.xml" }, { "code": null, "e": 30111, "s": 29982, "text": "Navigate to the app > res > values > strings.xml. Here you can add an app bar title. We have set “GFG | MarqueeText” as a title." }, { "code": null, "e": 30115, "s": 30111, "text": "XML" }, { "code": "<resources> <string name=\"app_name\">GFG | MarqueeText</string></resources>", "e": 30193, "s": 30115, "text": null }, { "code": null, "e": 30201, "s": 30193, "text": "Output:" }, { "code": null, "e": 30214, "s": 30201, "text": "Android-Misc" }, { "code": null, "e": 30222, "s": 30214, "text": "Android" }, { "code": null, "e": 30227, "s": 30222, "text": "Java" }, { "code": null, "e": 30232, "s": 30227, "text": "Java" }, { "code": null, "e": 30240, "s": 30232, "text": "Android" }, { "code": null, "e": 30338, "s": 30240, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30347, "s": 30338, "text": "Comments" }, { "code": null, "e": 30360, "s": 30347, "text": "Old Comments" }, { "code": null, "e": 30399, "s": 30360, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 30449, "s": 30399, "text": "How to Read Data from SQLite Database in Android?" }, { "code": null, "e": 30500, "s": 30449, "text": "How to Post Data to API using Retrofit in Android?" }, { "code": null, "e": 30538, "s": 30500, "text": "Android Listview in Java with Example" }, { "code": null, "e": 30580, "s": 30538, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 30595, "s": 30580, "text": "Arrays in Java" }, { "code": null, "e": 30639, "s": 30595, "text": "Split() String method in Java with examples" }, { "code": null, "e": 30661, "s": 30639, "text": "For-each loop in Java" }, { "code": null, "e": 30686, "s": 30661, "text": "Reverse a string in Java" } ]
Python - Elements frequency in Tuple - GeeksforGeeks
04 Sep, 2021 Given a Tuple, find frequency of each element. Input : test_tup = (4, 5, 4, 5, 6, 6, 5) Output : {4: 2, 5: 3, 6: 2} Explanation : Frequency of 4 is 2 and so on..Input : test_tup = (4, 5, 4, 5, 6, 6, 6) Output : {4: 2, 5: 2, 6: 3} Explanation : Frequency of 4 is 2 and so on.. Method #1 Using defaultdict() In this, we perform task of getting all elements and assigning frequency using defaultdict which maps each element with key and then frequency can be incremented. Python3 # Python3 code to demonstrate working of# Elements frequency in Tuple# Using defaultdict()from collections import defaultdict # initializing tupletest_tup = (4, 5, 4, 5, 6, 6, 5, 5, 4) # printing original tupleprint("The original tuple is : " + str(test_tup)) res = defaultdict(int)for ele in test_tup: # incrementing frequency res[ele] += 1 # printing resultprint("Tuple elements frequency is : " + str(dict(res))) The original tuple is : (4, 5, 4, 5, 6, 6, 5, 5, 4) Tuple elements frequency is : {4: 3, 5: 4, 6: 2} Method #2 : Using Counter() This is straight forward way to solve this problem. In this, we just employ this function and it returns frequency of elements in container, in this case tuple. Python3 # Python3 code to demonstrate working of# Elements frequency in Tuple# Using Counter()from collections import Counter # initializing tupletest_tup = (4, 5, 4, 5, 6, 6, 5, 5, 4) # printing original tupleprint("The original tuple is : " + str(test_tup)) # converting result back from defaultdict to dictres = dict(Counter(test_tup)) # printing resultprint("Tuple elements frequency is : " + str(res)) The original tuple is : (4, 5, 4, 5, 6, 6, 5, 5, 4) Tuple elements frequency is : {4: 3, 5: 4, 6: 2} sooda367 Python tuple-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary How to print without newline in Python?
[ { "code": null, "e": 25537, "s": 25509, "text": "\n04 Sep, 2021" }, { "code": null, "e": 25584, "s": 25537, "text": "Given a Tuple, find frequency of each element." }, { "code": null, "e": 25815, "s": 25584, "text": "Input : test_tup = (4, 5, 4, 5, 6, 6, 5) Output : {4: 2, 5: 3, 6: 2} Explanation : Frequency of 4 is 2 and so on..Input : test_tup = (4, 5, 4, 5, 6, 6, 6) Output : {4: 2, 5: 2, 6: 3} Explanation : Frequency of 4 is 2 and so on.. " }, { "code": null, "e": 25846, "s": 25815, "text": "Method #1 Using defaultdict()" }, { "code": null, "e": 26009, "s": 25846, "text": "In this, we perform task of getting all elements and assigning frequency using defaultdict which maps each element with key and then frequency can be incremented." }, { "code": null, "e": 26017, "s": 26009, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of# Elements frequency in Tuple# Using defaultdict()from collections import defaultdict # initializing tupletest_tup = (4, 5, 4, 5, 6, 6, 5, 5, 4) # printing original tupleprint(\"The original tuple is : \" + str(test_tup)) res = defaultdict(int)for ele in test_tup: # incrementing frequency res[ele] += 1 # printing resultprint(\"Tuple elements frequency is : \" + str(dict(res)))", "e": 26444, "s": 26017, "text": null }, { "code": null, "e": 26545, "s": 26444, "text": "The original tuple is : (4, 5, 4, 5, 6, 6, 5, 5, 4)\nTuple elements frequency is : {4: 3, 5: 4, 6: 2}" }, { "code": null, "e": 26573, "s": 26545, "text": "Method #2 : Using Counter()" }, { "code": null, "e": 26734, "s": 26573, "text": "This is straight forward way to solve this problem. In this, we just employ this function and it returns frequency of elements in container, in this case tuple." }, { "code": null, "e": 26742, "s": 26734, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of# Elements frequency in Tuple# Using Counter()from collections import Counter # initializing tupletest_tup = (4, 5, 4, 5, 6, 6, 5, 5, 4) # printing original tupleprint(\"The original tuple is : \" + str(test_tup)) # converting result back from defaultdict to dictres = dict(Counter(test_tup)) # printing resultprint(\"Tuple elements frequency is : \" + str(res))", "e": 27141, "s": 26742, "text": null }, { "code": null, "e": 27242, "s": 27141, "text": "The original tuple is : (4, 5, 4, 5, 6, 6, 5, 5, 4)\nTuple elements frequency is : {4: 3, 5: 4, 6: 2}" }, { "code": null, "e": 27251, "s": 27242, "text": "sooda367" }, { "code": null, "e": 27273, "s": 27251, "text": "Python tuple-programs" }, { "code": null, "e": 27280, "s": 27273, "text": "Python" }, { "code": null, "e": 27296, "s": 27280, "text": "Python Programs" }, { "code": null, "e": 27394, "s": 27296, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27426, "s": 27394, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27468, "s": 27426, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27510, "s": 27468, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27537, "s": 27510, "text": "Python Classes and Objects" }, { "code": null, "e": 27593, "s": 27537, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27615, "s": 27593, "text": "Defaultdict in Python" }, { "code": null, "e": 27654, "s": 27615, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 27700, "s": 27654, "text": "Python | Split string into list of characters" }, { "code": null, "e": 27738, "s": 27700, "text": "Python | Convert a list to dictionary" } ]
C++ Program For Sorting An Array Of 0s, 1s and 2s - GeeksforGeeks
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 1: 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:C++C++// C++ program to sort an array// with 0, 1 and 2 in a single pass#include <bits/stdc++.h>using namespace std; // Function to 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; // Iterate till all the elements // are sorted while (mid <= hi) { switch (a[mid]) { // If the element is 0 case 0: swap(a[lo++], a[mid++]); break; // If the element is 1 . case 1: mid++; break; // If the element is 2 case 2: swap(a[mid], a[hi--]); break; } }} // Function to print array arr[]void printArray(int arr[], int arr_size){ // Iterate and print every element for (int i = 0; i < arr_size; i++) cout << arr[i] << " ";} // Driver Codeint main(){ int arr[] = {0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1}; int n = sizeof(arr) / sizeof(arr[0]); sort012(arr, n); cout << "array after segregation "; printArray(arr, n); return 0;}// This code is contributed by Shivi_AggarwalOutput: 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.Method 2:Approach: Count the number of 0s, 1s and 2s in the given array. Then store all the 0s in the beginning followed by all the 1s then all the 2s.Algorithm: Keep three counter c0 to count 0s, c1 to count 1s and c2 to count 2sTraverse through the array and increase the count of c0 if the element is 0,increase the count of c1 if the element is 1 and increase the count of c2 if the element is 2Now again traverse the array and replace first c0 elements with 0, next c1 elements with 1 and next c2 elements with 2.Implementation:C++C++// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Utility function to print the // contents of an arrayvoid printArr(int arr[], int n){ for (int i = 0; i < n; i++) cout << arr[i] << " ";} // Function to sort the array of // 0s, 1s and 2svoid sortArr(int arr[], int n){ int i, cnt0 = 0, cnt1 = 0, cnt2 = 0; // Count the number of 0s, 1s and // 2s in the array for (i = 0; i < n; i++) { switch (arr[i]) { case 0: cnt0++; break; case 1: cnt1++; break; case 2: cnt2++; break; } } // Update the array i = 0; // Store all the 0s in the // beginning while (cnt0 > 0) { arr[i++] = 0; cnt0--; } // Then all the 1s while (cnt1 > 0) { arr[i++] = 1; cnt1--; } // Finally all the 2s while (cnt2 > 0) { arr[i++] = 2; cnt2--; } // Print the sorted array printArr(arr, n);} // Driver codeint main(){ int arr[] = {0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1}; int n = sizeof(arr) / sizeof(int); sortArr(arr, n); return 0;}Output:0 0 0 0 0 1 1 1 1 1 2 2Complexity Analysis:Time Complexity: O(n). Only two traversals of the array is needed.Space Complexity: O(1). As 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:C++C++// C++ program to sort an array// with 0, 1 and 2 in a single pass#include <bits/stdc++.h>using namespace std; // Function to 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; // Iterate till all the elements // are sorted while (mid <= hi) { switch (a[mid]) { // If the element is 0 case 0: swap(a[lo++], a[mid++]); break; // If the element is 1 . case 1: mid++; break; // If the element is 2 case 2: swap(a[mid], a[hi--]); break; } }} // Function to print array arr[]void printArray(int arr[], int arr_size){ // Iterate and print every element for (int i = 0; i < arr_size; i++) cout << arr[i] << " ";} // Driver Codeint main(){ int arr[] = {0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1}; int n = sizeof(arr) / sizeof(arr[0]); sort012(arr, n); cout << "array after segregation "; printArray(arr, n); return 0;}// This code is contributed by Shivi_AggarwalOutput: 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.Method 2:Approach: Count the number of 0s, 1s and 2s in the given array. Then store all the 0s in the beginning followed by all the 1s then all the 2s.Algorithm: Keep three counter c0 to count 0s, c1 to count 1s and c2 to count 2sTraverse through the array and increase the count of c0 if the element is 0,increase the count of c1 if the element is 1 and increase the count of c2 if the element is 2Now again traverse the array and replace first c0 elements with 0, next c1 elements with 1 and next c2 elements with 2.Implementation:C++C++// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Utility function to print the // contents of an arrayvoid printArr(int arr[], int n){ for (int i = 0; i < n; i++) cout << arr[i] << " ";} // Function to sort the array of // 0s, 1s and 2svoid sortArr(int arr[], int n){ int i, cnt0 = 0, cnt1 = 0, cnt2 = 0; // Count the number of 0s, 1s and // 2s in the array for (i = 0; i < n; i++) { switch (arr[i]) { case 0: cnt0++; break; case 1: cnt1++; break; case 2: cnt2++; break; } } // Update the array i = 0; // Store all the 0s in the // beginning while (cnt0 > 0) { arr[i++] = 0; cnt0--; } // Then all the 1s while (cnt1 > 0) { arr[i++] = 1; cnt1--; } // Finally all the 2s while (cnt2 > 0) { arr[i++] = 2; cnt2--; } // Print the sorted array printArr(arr, n);} // Driver codeint main(){ int arr[] = {0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1}; int n = sizeof(arr) / sizeof(int); sortArr(arr, n); return 0;}Output:0 0 0 0 0 1 1 1 1 1 2 2Complexity Analysis:Time Complexity: O(n). Only two traversals of the array is needed.Space Complexity: O(1). As 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:C++C++// C++ program to sort an array// with 0, 1 and 2 in a single pass#include <bits/stdc++.h>using namespace std; // Function to 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; // Iterate till all the elements // are sorted while (mid <= hi) { switch (a[mid]) { // If the element is 0 case 0: swap(a[lo++], a[mid++]); break; // If the element is 1 . case 1: mid++; break; // If the element is 2 case 2: swap(a[mid], a[hi--]); break; } }} // Function to print array arr[]void printArray(int arr[], int arr_size){ // Iterate and print every element for (int i = 0; i < arr_size; i++) cout << arr[i] << " ";} // Driver Codeint main(){ int arr[] = {0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1}; int n = sizeof(arr) / sizeof(arr[0]); sort012(arr, n); cout << "array after segregation "; printArray(arr, n); return 0;}// This code is contributed by Shivi_AggarwalOutput: 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.Method 2:Approach: Count the number of 0s, 1s and 2s in the given array. Then store all the 0s in the beginning followed by all the 1s then all the 2s.Algorithm: Keep three counter c0 to count 0s, c1 to count 1s and c2 to count 2sTraverse through the array and increase the count of c0 if the element is 0,increase the count of c1 if the element is 1 and increase the count of c2 if the element is 2Now again traverse the array and replace first c0 elements with 0, next c1 elements with 1 and next c2 elements with 2.Implementation:C++C++// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Utility function to print the // contents of an arrayvoid printArr(int arr[], int n){ for (int i = 0; i < n; i++) cout << arr[i] << " ";} // Function to sort the array of // 0s, 1s and 2svoid sortArr(int arr[], int n){ int i, cnt0 = 0, cnt1 = 0, cnt2 = 0; // Count the number of 0s, 1s and // 2s in the array for (i = 0; i < n; i++) { switch (arr[i]) { case 0: cnt0++; break; case 1: cnt1++; break; case 2: cnt2++; break; } } // Update the array i = 0; // Store all the 0s in the // beginning while (cnt0 > 0) { arr[i++] = 0; cnt0--; } // Then all the 1s while (cnt1 > 0) { arr[i++] = 1; cnt1--; } // Finally all the 2s while (cnt2 > 0) { arr[i++] = 2; cnt2--; } // Print the sorted array printArr(arr, n);} // Driver codeint main(){ int arr[] = {0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1}; int n = sizeof(arr) / sizeof(int); sortArr(arr, n); return 0;}Output:0 0 0 0 0 1 1 1 1 1 2 2Complexity Analysis:Time Complexity: O(n). Only two traversals of the array is needed.Space Complexity: O(1). As 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:C++C++// C++ program to sort an array// with 0, 1 and 2 in a single pass#include <bits/stdc++.h>using namespace std; // Function to 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; // Iterate till all the elements // are sorted while (mid <= hi) { switch (a[mid]) { // If the element is 0 case 0: swap(a[lo++], a[mid++]); break; // If the element is 1 . case 1: mid++; break; // If the element is 2 case 2: swap(a[mid], a[hi--]); break; } }} // Function to print array arr[]void printArray(int arr[], int arr_size){ // Iterate and print every element for (int i = 0; i < arr_size; i++) cout << arr[i] << " ";} // Driver Codeint main(){ int arr[] = {0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1}; int n = sizeof(arr) / sizeof(arr[0]); sort012(arr, n); cout << "array after segregation "; printArray(arr, n); return 0;}// This code is contributed by Shivi_AggarwalOutput: 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.Method 2:Approach: Count the number of 0s, 1s and 2s in the given array. Then store all the 0s in the beginning followed by all the 1s then all the 2s.Algorithm: Keep three counter c0 to count 0s, c1 to count 1s and c2 to count 2sTraverse through the array and increase the count of c0 if the element is 0,increase the count of c1 if the element is 1 and increase the count of c2 if the element is 2Now again traverse the array and replace first c0 elements with 0, next c1 elements with 1 and next c2 elements with 2.Implementation:C++C++// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Utility function to print the // contents of an arrayvoid printArr(int arr[], int n){ for (int i = 0; i < n; i++) cout << arr[i] << " ";} // Function to sort the array of // 0s, 1s and 2svoid sortArr(int arr[], int n){ int i, cnt0 = 0, cnt1 = 0, cnt2 = 0; // Count the number of 0s, 1s and // 2s in the array for (i = 0; i < n; i++) { switch (arr[i]) { case 0: cnt0++; break; case 1: cnt1++; break; case 2: cnt2++; break; } } // Update the array i = 0; // Store all the 0s in the // beginning while (cnt0 > 0) { arr[i++] = 0; cnt0--; } // Then all the 1s while (cnt1 > 0) { arr[i++] = 1; cnt1--; } // Finally all the 2s while (cnt2 > 0) { arr[i++] = 2; cnt2--; } // Print the sorted array printArr(arr, n);} // Driver codeint main(){ int arr[] = {0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1}; int n = sizeof(arr) / sizeof(int); sortArr(arr, n); return 0;}Output:0 0 0 0 0 1 1 1 1 1 2 2Complexity Analysis:Time Complexity: O(n). Only two traversals of the array is needed.Space Complexity: O(1). As 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 <bits/stdc++.h>using namespace std; // Function to 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; // Iterate till all the elements // are sorted while (mid <= hi) { switch (a[mid]) { // If the element is 0 case 0: swap(a[lo++], a[mid++]); break; // If the element is 1 . case 1: mid++; break; // If the element is 2 case 2: swap(a[mid], a[hi--]); break; } }} // Function to print array arr[]void printArray(int arr[], int arr_size){ // Iterate and print every element for (int i = 0; i < arr_size; i++) cout << arr[i] << " ";} // Driver Codeint main(){ int arr[] = {0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1}; int n = sizeof(arr) / sizeof(arr[0]); sort012(arr, n); cout << "array after segregation "; printArray(arr, n); return 0;}// This code is contributed by Shivi_Aggarwal 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.Method 2:Approach: Count the number of 0s, 1s and 2s in the given array. Then store all the 0s in the beginning followed by all the 1s then all the 2s.Algorithm: Keep three counter c0 to count 0s, c1 to count 1s and c2 to count 2sTraverse through the array and increase the count of c0 if the element is 0,increase the count of c1 if the element is 1 and increase the count of c2 if the element is 2Now again traverse the array and replace first c0 elements with 0, next c1 elements with 1 and next c2 elements with 2.Implementation:C++C++// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Utility function to print the // contents of an arrayvoid printArr(int arr[], int n){ for (int i = 0; i < n; i++) cout << arr[i] << " ";} // Function to sort the array of // 0s, 1s and 2svoid sortArr(int arr[], int n){ int i, cnt0 = 0, cnt1 = 0, cnt2 = 0; // Count the number of 0s, 1s and // 2s in the array for (i = 0; i < n; i++) { switch (arr[i]) { case 0: cnt0++; break; case 1: cnt1++; break; case 2: cnt2++; break; } } // Update the array i = 0; // Store all the 0s in the // beginning while (cnt0 > 0) { arr[i++] = 0; cnt0--; } // Then all the 1s while (cnt1 > 0) { arr[i++] = 1; cnt1--; } // Finally all the 2s while (cnt2 > 0) { arr[i++] = 2; cnt2--; } // Print the sorted array printArr(arr, n);} // Driver codeint main(){ int arr[] = {0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1}; int n = sizeof(arr) / sizeof(int); sortArr(arr, n); return 0;}Output:0 0 0 0 0 1 1 1 1 1 2 2Complexity Analysis:Time Complexity: O(n). Only two traversals of the array is needed.Space Complexity: O(1). As 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 Method 2: Approach: Count the number of 0s, 1s and 2s in the given array. Then store all the 0s in the beginning followed by all the 1s then all the 2s. Algorithm: Keep three counter c0 to count 0s, c1 to count 1s and c2 to count 2sTraverse through the array and increase the count of c0 if the element is 0,increase the count of c1 if the element is 1 and increase the count of c2 if the element is 2Now again traverse the array and replace first c0 elements with 0, next c1 elements with 1 and next c2 elements with 2. Keep three counter c0 to count 0s, c1 to count 1s and c2 to count 2s Traverse through the array and increase the count of c0 if the element is 0,increase the count of c1 if the element is 1 and increase the count of c2 if the element is 2 Now again traverse the array and replace first c0 elements with 0, next c1 elements with 1 and next c2 elements with 2. Implementation: C++ // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Utility function to print the // contents of an arrayvoid printArr(int arr[], int n){ for (int i = 0; i < n; i++) cout << arr[i] << " ";} // Function to sort the array of // 0s, 1s and 2svoid sortArr(int arr[], int n){ int i, cnt0 = 0, cnt1 = 0, cnt2 = 0; // Count the number of 0s, 1s and // 2s in the array for (i = 0; i < n; i++) { switch (arr[i]) { case 0: cnt0++; break; case 1: cnt1++; break; case 2: cnt2++; break; } } // Update the array i = 0; // Store all the 0s in the // beginning while (cnt0 > 0) { arr[i++] = 0; cnt0--; } // Then all the 1s while (cnt1 > 0) { arr[i++] = 1; cnt1--; } // Finally all the 2s while (cnt2 > 0) { arr[i++] = 2; cnt2--; } // Print the sorted array printArr(arr, n);} // Driver codeint main(){ int arr[] = {0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1}; int n = sizeof(arr) / sizeof(int); sortArr(arr, n); return 0;} Output: 0 0 0 0 0 1 1 1 1 1 2 2 Complexity Analysis: Time Complexity: O(n). Only two traversals of the array is needed. Space Complexity: O(1). As 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. Count pairs with given sum Chocolate Distribution Problem Window Sliding Technique Reversal algorithm for array rotation Next Greater Element Header files in C/C++ and its uses Program to print ASCII Value of a character How to return multiple values from a function in C or C++? C++ Program for QuickSort Sorting a Map by value in C++ STL
[ { "code": null, "e": 26041, "s": 26013, "text": "\n16 Dec, 2021" }, { "code": null, "e": 26226, "s": 26041, "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": 26369, "s": 26226, "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": 26473, "s": 26369, "text": "A simple solution is discussed in this(Sort an array of 0s, 1s and 2s (Simple Counting)) post.Method 1:" }, { "code": null, "e": 26740, "s": 26473, "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": 31670, "s": 26740, "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:C++C++// C++ program to sort an array// with 0, 1 and 2 in a single pass#include <bits/stdc++.h>using namespace std; // Function to 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; // Iterate till all the elements // are sorted while (mid <= hi) { switch (a[mid]) { // If the element is 0 case 0: swap(a[lo++], a[mid++]); break; // If the element is 1 . case 1: mid++; break; // If the element is 2 case 2: swap(a[mid], a[hi--]); break; } }} // Function to print array arr[]void printArray(int arr[], int arr_size){ // Iterate and print every element for (int i = 0; i < arr_size; i++) cout << arr[i] << \" \";} // Driver Codeint main(){ int arr[] = {0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1}; int n = sizeof(arr) / sizeof(arr[0]); sort012(arr, n); cout << \"array after segregation \"; printArray(arr, n); return 0;}// This code is contributed by Shivi_AggarwalOutput: 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.Method 2:Approach: Count the number of 0s, 1s and 2s in the given array. Then store all the 0s in the beginning followed by all the 1s then all the 2s.Algorithm: Keep three counter c0 to count 0s, c1 to count 1s and c2 to count 2sTraverse through the array and increase the count of c0 if the element is 0,increase the count of c1 if the element is 1 and increase the count of c2 if the element is 2Now again traverse the array and replace first c0 elements with 0, next c1 elements with 1 and next c2 elements with 2.Implementation:C++C++// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Utility function to print the // contents of an arrayvoid printArr(int arr[], int n){ for (int i = 0; i < n; i++) cout << arr[i] << \" \";} // Function to sort the array of // 0s, 1s and 2svoid sortArr(int arr[], int n){ int i, cnt0 = 0, cnt1 = 0, cnt2 = 0; // Count the number of 0s, 1s and // 2s in the array for (i = 0; i < n; i++) { switch (arr[i]) { case 0: cnt0++; break; case 1: cnt1++; break; case 2: cnt2++; break; } } // Update the array i = 0; // Store all the 0s in the // beginning while (cnt0 > 0) { arr[i++] = 0; cnt0--; } // Then all the 1s while (cnt1 > 0) { arr[i++] = 1; cnt1--; } // Finally all the 2s while (cnt2 > 0) { arr[i++] = 2; cnt2--; } // Print the sorted array printArr(arr, n);} // Driver codeint main(){ int arr[] = {0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1}; int n = sizeof(arr) / sizeof(int); sortArr(arr, n); return 0;}Output:0 0 0 0 0 1 1 1 1 1 2 2Complexity Analysis:Time Complexity: O(n). Only two traversals of the array is needed.Space Complexity: O(1). As 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": 31694, "s": 31670, "text": "a[1..Lo-1] zeroes (red)" }, { "code": null, "e": 31720, "s": 31694, "text": "a[Lo..Mid-1] ones (white)" }, { "code": null, "e": 31739, "s": 31720, "text": "a[Mid..Hi] unknown" }, { "code": null, "e": 31762, "s": 31739, "text": "a[Hi+1..N] twos (blue)" }, { "code": null, "e": 31860, "s": 31762, "text": "If the ith element is 0 then swap the element to the low range, thus shrinking the unknown range." }, { "code": null, "e": 31943, "s": 31860, "text": "Similarly, if the element is 1 then keep it as it is but shrink the unknown range." }, { "code": null, "e": 36606, "s": 31943, "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:C++C++// C++ program to sort an array// with 0, 1 and 2 in a single pass#include <bits/stdc++.h>using namespace std; // Function to 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; // Iterate till all the elements // are sorted while (mid <= hi) { switch (a[mid]) { // If the element is 0 case 0: swap(a[lo++], a[mid++]); break; // If the element is 1 . case 1: mid++; break; // If the element is 2 case 2: swap(a[mid], a[hi--]); break; } }} // Function to print array arr[]void printArray(int arr[], int arr_size){ // Iterate and print every element for (int i = 0; i < arr_size; i++) cout << arr[i] << \" \";} // Driver Codeint main(){ int arr[] = {0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1}; int n = sizeof(arr) / sizeof(arr[0]); sort012(arr, n); cout << \"array after segregation \"; printArray(arr, n); return 0;}// This code is contributed by Shivi_AggarwalOutput: 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.Method 2:Approach: Count the number of 0s, 1s and 2s in the given array. Then store all the 0s in the beginning followed by all the 1s then all the 2s.Algorithm: Keep three counter c0 to count 0s, c1 to count 1s and c2 to count 2sTraverse through the array and increase the count of c0 if the element is 0,increase the count of c1 if the element is 1 and increase the count of c2 if the element is 2Now again traverse the array and replace first c0 elements with 0, next c1 elements with 1 and next c2 elements with 2.Implementation:C++C++// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Utility function to print the // contents of an arrayvoid printArr(int arr[], int n){ for (int i = 0; i < n; i++) cout << arr[i] << \" \";} // Function to sort the array of // 0s, 1s and 2svoid sortArr(int arr[], int n){ int i, cnt0 = 0, cnt1 = 0, cnt2 = 0; // Count the number of 0s, 1s and // 2s in the array for (i = 0; i < n; i++) { switch (arr[i]) { case 0: cnt0++; break; case 1: cnt1++; break; case 2: cnt2++; break; } } // Update the array i = 0; // Store all the 0s in the // beginning while (cnt0 > 0) { arr[i++] = 0; cnt0--; } // Then all the 1s while (cnt1 > 0) { arr[i++] = 1; cnt1--; } // Finally all the 2s while (cnt2 > 0) { arr[i++] = 2; cnt2--; } // Print the sorted array printArr(arr, n);} // Driver codeint main(){ int arr[] = {0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1}; int n = sizeof(arr) / sizeof(int); sortArr(arr, n); return 0;}Output:0 0 0 0 0 1 1 1 1 1 2 2Complexity Analysis:Time Complexity: O(n). Only two traversals of the array is needed.Space Complexity: O(1). As 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": 36618, "s": 36606, "text": "Algorithm: " }, { "code": null, "e": 41207, "s": 36618, "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:C++C++// C++ program to sort an array// with 0, 1 and 2 in a single pass#include <bits/stdc++.h>using namespace std; // Function to 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; // Iterate till all the elements // are sorted while (mid <= hi) { switch (a[mid]) { // If the element is 0 case 0: swap(a[lo++], a[mid++]); break; // If the element is 1 . case 1: mid++; break; // If the element is 2 case 2: swap(a[mid], a[hi--]); break; } }} // Function to print array arr[]void printArray(int arr[], int arr_size){ // Iterate and print every element for (int i = 0; i < arr_size; i++) cout << arr[i] << \" \";} // Driver Codeint main(){ int arr[] = {0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1}; int n = sizeof(arr) / sizeof(arr[0]); sort012(arr, n); cout << \"array after segregation \"; printArray(arr, n); return 0;}// This code is contributed by Shivi_AggarwalOutput: 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.Method 2:Approach: Count the number of 0s, 1s and 2s in the given array. Then store all the 0s in the beginning followed by all the 1s then all the 2s.Algorithm: Keep three counter c0 to count 0s, c1 to count 1s and c2 to count 2sTraverse through the array and increase the count of c0 if the element is 0,increase the count of c1 if the element is 1 and increase the count of c2 if the element is 2Now again traverse the array and replace first c0 elements with 0, next c1 elements with 1 and next c2 elements with 2.Implementation:C++C++// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Utility function to print the // contents of an arrayvoid printArr(int arr[], int n){ for (int i = 0; i < n; i++) cout << arr[i] << \" \";} // Function to sort the array of // 0s, 1s and 2svoid sortArr(int arr[], int n){ int i, cnt0 = 0, cnt1 = 0, cnt2 = 0; // Count the number of 0s, 1s and // 2s in the array for (i = 0; i < n; i++) { switch (arr[i]) { case 0: cnt0++; break; case 1: cnt1++; break; case 2: cnt2++; break; } } // Update the array i = 0; // Store all the 0s in the // beginning while (cnt0 > 0) { arr[i++] = 0; cnt0--; } // Then all the 1s while (cnt1 > 0) { arr[i++] = 1; cnt1--; } // Finally all the 2s while (cnt2 > 0) { arr[i++] = 2; cnt2--; } // Print the sorted array printArr(arr, n);} // Driver codeint main(){ int arr[] = {0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1}; int n = sizeof(arr) / sizeof(int); sortArr(arr, n); return 0;}Output:0 0 0 0 0 1 1 1 1 1 2 2Complexity Analysis:Time Complexity: O(n). Only two traversals of the array is needed.Space Complexity: O(1). As 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": 41447, "s": 41207, "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": 41531, "s": 41447, "text": "Traverse the array from start to end and mid is less than high. (Loop counter is i)" }, { "code": null, "e": 41646, "s": 41531, "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": 41692, "s": 41646, "text": "If the element is 1 then update mid = mid + 1" }, { "code": null, "e": 41854, "s": 41692, "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": 45801, "s": 41854, "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:C++C++// C++ program to sort an array// with 0, 1 and 2 in a single pass#include <bits/stdc++.h>using namespace std; // Function to 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; // Iterate till all the elements // are sorted while (mid <= hi) { switch (a[mid]) { // If the element is 0 case 0: swap(a[lo++], a[mid++]); break; // If the element is 1 . case 1: mid++; break; // If the element is 2 case 2: swap(a[mid], a[hi--]); break; } }} // Function to print array arr[]void printArray(int arr[], int arr_size){ // Iterate and print every element for (int i = 0; i < arr_size; i++) cout << arr[i] << \" \";} // Driver Codeint main(){ int arr[] = {0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1}; int n = sizeof(arr) / sizeof(arr[0]); sort012(arr, n); cout << \"array after segregation \"; printArray(arr, n); return 0;}// This code is contributed by Shivi_AggarwalOutput: 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.Method 2:Approach: Count the number of 0s, 1s and 2s in the given array. Then store all the 0s in the beginning followed by all the 1s then all the 2s.Algorithm: Keep three counter c0 to count 0s, c1 to count 1s and c2 to count 2sTraverse through the array and increase the count of c0 if the element is 0,increase the count of c1 if the element is 1 and increase the count of c2 if the element is 2Now again traverse the array and replace first c0 elements with 0, next c1 elements with 1 and next c2 elements with 2.Implementation:C++C++// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Utility function to print the // contents of an arrayvoid printArr(int arr[], int n){ for (int i = 0; i < n; i++) cout << arr[i] << \" \";} // Function to sort the array of // 0s, 1s and 2svoid sortArr(int arr[], int n){ int i, cnt0 = 0, cnt1 = 0, cnt2 = 0; // Count the number of 0s, 1s and // 2s in the array for (i = 0; i < n; i++) { switch (arr[i]) { case 0: cnt0++; break; case 1: cnt1++; break; case 2: cnt2++; break; } } // Update the array i = 0; // Store all the 0s in the // beginning while (cnt0 > 0) { arr[i++] = 0; cnt0--; } // Then all the 1s while (cnt1 > 0) { arr[i++] = 1; cnt1--; } // Finally all the 2s while (cnt2 > 0) { arr[i++] = 2; cnt2--; } // Print the sorted array printArr(arr, n);} // Driver codeint main(){ int arr[] = {0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1}; int n = sizeof(arr) / sizeof(int); sortArr(arr, n); return 0;}Output:0 0 0 0 0 1 1 1 1 1 2 2Complexity Analysis:Time Complexity: O(n). Only two traversals of the array is needed.Space Complexity: O(1). As 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": 45990, "s": 45801, "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": 46139, "s": 45990, "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": 46171, "s": 46139, "text": "Case (1) a[Mid] is white, Mid++" }, { "code": null, "e": 46223, "s": 46171, "text": "Case (2) a[Mid] is blue, swap a[Mid] and a[Hi]; Hi–" }, { "code": null, "e": 46246, "s": 46223, "text": "Continue until Mid>Hi." }, { "code": null, "e": 46262, "s": 46246, "text": "Implementation:" }, { "code": null, "e": 46266, "s": 46262, "text": "C++" }, { "code": "// C++ program to sort an array// with 0, 1 and 2 in a single pass#include <bits/stdc++.h>using namespace std; // Function to 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; // Iterate till all the elements // are sorted while (mid <= hi) { switch (a[mid]) { // If the element is 0 case 0: swap(a[lo++], a[mid++]); break; // If the element is 1 . case 1: mid++; break; // If the element is 2 case 2: swap(a[mid], a[hi--]); break; } }} // Function to print array arr[]void printArray(int arr[], int arr_size){ // Iterate and print every element for (int i = 0; i < arr_size; i++) cout << arr[i] << \" \";} // Driver Codeint main(){ int arr[] = {0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1}; int n = sizeof(arr) / sizeof(arr[0]); sort012(arr, n); cout << \"array after segregation \"; printArray(arr, n); return 0;}// This code is contributed by Shivi_Aggarwal", "e": 47476, "s": 46266, "text": null }, { "code": null, "e": 47485, "s": 47476, "text": "Output: " }, { "code": null, "e": 47535, "s": 47485, "text": "array after segregation\n 0 0 0 0 0 1 1 1 1 1 2 2 " }, { "code": null, "e": 47557, "s": 47535, "text": "Complexity Analysis: " }, { "code": null, "e": 47623, "s": 47557, "text": "Time Complexity: O(n). Only one traversal of the array is needed." }, { "code": null, "e": 49734, "s": 47623, "text": "Space Complexity: O(1). No extra space is required.Method 2:Approach: Count the number of 0s, 1s and 2s in the given array. Then store all the 0s in the beginning followed by all the 1s then all the 2s.Algorithm: Keep three counter c0 to count 0s, c1 to count 1s and c2 to count 2sTraverse through the array and increase the count of c0 if the element is 0,increase the count of c1 if the element is 1 and increase the count of c2 if the element is 2Now again traverse the array and replace first c0 elements with 0, next c1 elements with 1 and next c2 elements with 2.Implementation:C++C++// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Utility function to print the // contents of an arrayvoid printArr(int arr[], int n){ for (int i = 0; i < n; i++) cout << arr[i] << \" \";} // Function to sort the array of // 0s, 1s and 2svoid sortArr(int arr[], int n){ int i, cnt0 = 0, cnt1 = 0, cnt2 = 0; // Count the number of 0s, 1s and // 2s in the array for (i = 0; i < n; i++) { switch (arr[i]) { case 0: cnt0++; break; case 1: cnt1++; break; case 2: cnt2++; break; } } // Update the array i = 0; // Store all the 0s in the // beginning while (cnt0 > 0) { arr[i++] = 0; cnt0--; } // Then all the 1s while (cnt1 > 0) { arr[i++] = 1; cnt1--; } // Finally all the 2s while (cnt2 > 0) { arr[i++] = 2; cnt2--; } // Print the sorted array printArr(arr, n);} // Driver codeint main(){ int arr[] = {0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1}; int n = sizeof(arr) / sizeof(int); sortArr(arr, n); return 0;}Output:0 0 0 0 0 1 1 1 1 1 2 2Complexity Analysis:Time Complexity: O(n). Only two traversals of the array is needed.Space Complexity: O(1). As 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": 49744, "s": 49734, "text": "Method 2:" }, { "code": null, "e": 49887, "s": 49744, "text": "Approach: Count the number of 0s, 1s and 2s in the given array. Then store all the 0s in the beginning followed by all the 1s then all the 2s." }, { "code": null, "e": 49899, "s": 49887, "text": "Algorithm: " }, { "code": null, "e": 50256, "s": 49899, "text": "Keep three counter c0 to count 0s, c1 to count 1s and c2 to count 2sTraverse through the array and increase the count of c0 if the element is 0,increase the count of c1 if the element is 1 and increase the count of c2 if the element is 2Now again traverse the array and replace first c0 elements with 0, next c1 elements with 1 and next c2 elements with 2." }, { "code": null, "e": 50325, "s": 50256, "text": "Keep three counter c0 to count 0s, c1 to count 1s and c2 to count 2s" }, { "code": null, "e": 50495, "s": 50325, "text": "Traverse through the array and increase the count of c0 if the element is 0,increase the count of c1 if the element is 1 and increase the count of c2 if the element is 2" }, { "code": null, "e": 50615, "s": 50495, "text": "Now again traverse the array and replace first c0 elements with 0, next c1 elements with 1 and next c2 elements with 2." }, { "code": null, "e": 50631, "s": 50615, "text": "Implementation:" }, { "code": null, "e": 50635, "s": 50631, "text": "C++" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Utility function to print the // contents of an arrayvoid printArr(int arr[], int n){ for (int i = 0; i < n; i++) cout << arr[i] << \" \";} // Function to sort the array of // 0s, 1s and 2svoid sortArr(int arr[], int n){ int i, cnt0 = 0, cnt1 = 0, cnt2 = 0; // Count the number of 0s, 1s and // 2s in the array for (i = 0; i < n; i++) { switch (arr[i]) { case 0: cnt0++; break; case 1: cnt1++; break; case 2: cnt2++; break; } } // Update the array i = 0; // Store all the 0s in the // beginning while (cnt0 > 0) { arr[i++] = 0; cnt0--; } // Then all the 1s while (cnt1 > 0) { arr[i++] = 1; cnt1--; } // Finally all the 2s while (cnt2 > 0) { arr[i++] = 2; cnt2--; } // Print the sorted array printArr(arr, n);} // Driver codeint main(){ int arr[] = {0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1}; int n = sizeof(arr) / sizeof(int); sortArr(arr, n); return 0;}", "e": 51870, "s": 50635, "text": null }, { "code": null, "e": 51878, "s": 51870, "text": "Output:" }, { "code": null, "e": 51902, "s": 51878, "text": "0 0 0 0 0 1 1 1 1 1 2 2" }, { "code": null, "e": 51923, "s": 51902, "text": "Complexity Analysis:" }, { "code": null, "e": 51990, "s": 51923, "text": "Time Complexity: O(n). Only two traversals of the array is needed." }, { "code": null, "e": 52045, "s": 51990, "text": "Space Complexity: O(1). As no extra space is required." }, { "code": null, "e": 52127, "s": 52045, "text": "Please refer complete article on Sort an array of 0s, 1s and 2s for more details!" }, { "code": null, "e": 52133, "s": 52127, "text": "Adobe" }, { "code": null, "e": 52140, "s": 52133, "text": "Amazon" }, { "code": null, "e": 52145, "s": 52140, "text": "Hike" }, { "code": null, "e": 52156, "s": 52145, "text": "MakeMyTrip" }, { "code": null, "e": 52169, "s": 52156, "text": "MAQ Software" }, { "code": null, "e": 52179, "s": 52169, "text": "Microsoft" }, { "code": null, "e": 52194, "s": 52179, "text": "Morgan Stanley" }, { "code": null, "e": 52203, "s": 52194, "text": "Ola Cabs" }, { "code": null, "e": 52209, "s": 52203, "text": "Paytm" }, { "code": null, "e": 52218, "s": 52209, "text": "Qualcomm" }, { "code": null, "e": 52227, "s": 52218, "text": "SAP Labs" }, { "code": null, "e": 52236, "s": 52227, "text": "Snapdeal" }, { "code": null, "e": 52244, "s": 52236, "text": "Walmart" }, { "code": null, "e": 52254, "s": 52244, "text": "Yatra.com" }, { "code": null, "e": 52261, "s": 52254, "text": "Arrays" }, { "code": null, "e": 52274, "s": 52261, "text": "C++ Programs" }, { "code": null, "e": 52282, "s": 52274, "text": "Sorting" }, { "code": null, "e": 52288, "s": 52282, "text": "Paytm" }, { "code": null, "e": 52303, "s": 52288, "text": "Morgan Stanley" }, { "code": null, "e": 52310, "s": 52303, "text": "Amazon" }, { "code": null, "e": 52320, "s": 52310, "text": "Microsoft" }, { "code": null, "e": 52329, "s": 52320, "text": "Snapdeal" }, { "code": null, "e": 52334, "s": 52329, "text": "Hike" }, { "code": null, "e": 52345, "s": 52334, "text": "MakeMyTrip" }, { "code": null, "e": 52354, "s": 52345, "text": "Ola Cabs" }, { "code": null, "e": 52362, "s": 52354, "text": "Walmart" }, { "code": null, "e": 52375, "s": 52362, "text": "MAQ Software" }, { "code": null, "e": 52381, "s": 52375, "text": "Adobe" }, { "code": null, "e": 52391, "s": 52381, "text": "Yatra.com" }, { "code": null, "e": 52400, "s": 52391, "text": "SAP Labs" }, { "code": null, "e": 52409, "s": 52400, "text": "Qualcomm" }, { "code": null, "e": 52416, "s": 52409, "text": "Arrays" }, { "code": null, "e": 52424, "s": 52416, "text": "Sorting" }, { "code": null, "e": 52522, "s": 52424, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 52549, "s": 52522, "text": "Count pairs with given sum" }, { "code": null, "e": 52580, "s": 52549, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 52605, "s": 52580, "text": "Window Sliding Technique" }, { "code": null, "e": 52643, "s": 52605, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 52664, "s": 52643, "text": "Next Greater Element" }, { "code": null, "e": 52699, "s": 52664, "text": "Header files in C/C++ and its uses" }, { "code": null, "e": 52743, "s": 52699, "text": "Program to print ASCII Value of a character" }, { "code": null, "e": 52802, "s": 52743, "text": "How to return multiple values from a function in C or C++?" }, { "code": null, "e": 52828, "s": 52802, "text": "C++ Program for QuickSort" } ]
Python - Johnson SB Distribution in Statistics - GeeksforGeeks
10 Jan, 2020 scipy.stats.johnsonsb() is a Johnson SB continuous random variable that is defined with a standard format and some shape parameters to complete its specification. Parameters : q : lower and upper tail probabilityx : quantilesloc : [optional]location parameter. Default = 0scale : [optional]scale parameter. Default = 1size : [tuple of ints, optional] shape or random variates.moments : [optional] composed of letters [‘mvsk’]; ‘m’ = mean, ‘v’ = variance, ‘s’ = Fisher’s skew and ‘k’ = Fisher’s kurtosis. (default = ‘mv’). Results : Johnson SB continuous random variable Code #1 : Creating Johnson SB continuous random variable # importing library from scipy.stats import johnsonsb numargs = johnsonsb.numargs a, b = 4.32, 3.18rv = johnsonsb(a, b) print ("RV : \n", rv) Output : RV : scipy.stats._distn_infrastructure.rv_frozen object at 0x000002A9D50286C8 Code #2 : Johnson SB continuous variates and probability distribution import numpy as np quantile = np.arange (0.01, 1, 0.1) # Random Variates R = johnsonsb.rvs(a, b, scale = 2, size = 10) print ("Random Variates : \n", R) # PDF R = johnsonsb.pdf(a, b, quantile, loc = 0, scale = 1) print ("\nProbability Distribution : \n", R) Output : Random Variates : [0.42212956 0.60876766 0.35494705 0.42892958 0.25316345 0.51872977 0.2355019 0.44657975 0.54971277 0.36683771] Probability Distribution : [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.] Code #3 : Graphical Representation. import numpy as np import matplotlib.pyplot as plt distribution = np.linspace(0, np.minimum(rv.dist.b, 3)) print("Distribution : \n", distribution) plot = plt.plot(distribution, rv.pdf(distribution)) Output : Distribution : [0. 0.02040816 0.04081633 0.06122449 0.08163265 0.10204082 0.12244898 0.14285714 0.16326531 0.18367347 0.20408163 0.2244898 0.24489796 0.26530612 0.28571429 0.30612245 0.32653061 0.34693878 0.36734694 0.3877551 0.40816327 0.42857143 0.44897959 0.46938776 0.48979592 0.51020408 0.53061224 0.55102041 0.57142857 0.59183673 0.6122449 0.63265306 0.65306122 0.67346939 0.69387755 0.71428571 0.73469388 0.75510204 0.7755102 0.79591837 0.81632653 0.83673469 0.85714286 0.87755102 0.89795918 0.91836735 0.93877551 0.95918367 0.97959184 1. ] Code #4 : Varying Positional Arguments import matplotlib.pyplot as plt import numpy as np x = np.linspace(0, 5, 100) # Varying positional arguments y1 = johnsonsb .pdf(x, 1, 3) y2 = johnsonsb .pdf(x, 1, 4) plt.plot(x, y1, "*", x, y2, "r--") Output : Python scipy-stats-functions 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": 25547, "s": 25519, "text": "\n10 Jan, 2020" }, { "code": null, "e": 25710, "s": 25547, "text": "scipy.stats.johnsonsb() is a Johnson SB continuous random variable that is defined with a standard format and some shape parameters to complete its specification." }, { "code": null, "e": 25723, "s": 25710, "text": "Parameters :" }, { "code": null, "e": 26069, "s": 25723, "text": "q : lower and upper tail probabilityx : quantilesloc : [optional]location parameter. Default = 0scale : [optional]scale parameter. Default = 1size : [tuple of ints, optional] shape or random variates.moments : [optional] composed of letters [‘mvsk’]; ‘m’ = mean, ‘v’ = variance, ‘s’ = Fisher’s skew and ‘k’ = Fisher’s kurtosis. (default = ‘mv’)." }, { "code": null, "e": 26117, "s": 26069, "text": "Results : Johnson SB continuous random variable" }, { "code": null, "e": 26174, "s": 26117, "text": "Code #1 : Creating Johnson SB continuous random variable" }, { "code": "# importing library from scipy.stats import johnsonsb numargs = johnsonsb.numargs a, b = 4.32, 3.18rv = johnsonsb(a, b) print (\"RV : \\n\", rv) ", "e": 26328, "s": 26174, "text": null }, { "code": null, "e": 26337, "s": 26328, "text": "Output :" }, { "code": null, "e": 26418, "s": 26337, "text": "RV : \n scipy.stats._distn_infrastructure.rv_frozen object at 0x000002A9D50286C8\n" }, { "code": null, "e": 26488, "s": 26418, "text": "Code #2 : Johnson SB continuous variates and probability distribution" }, { "code": "import numpy as np quantile = np.arange (0.01, 1, 0.1) # Random Variates R = johnsonsb.rvs(a, b, scale = 2, size = 10) print (\"Random Variates : \\n\", R) # PDF R = johnsonsb.pdf(a, b, quantile, loc = 0, scale = 1) print (\"\\nProbability Distribution : \\n\", R) ", "e": 26752, "s": 26488, "text": null }, { "code": null, "e": 26761, "s": 26752, "text": "Output :" }, { "code": null, "e": 26957, "s": 26761, "text": "Random Variates : \n [0.42212956 0.60876766 0.35494705 0.42892958 0.25316345 0.51872977\n 0.2355019 0.44657975 0.54971277 0.36683771]\n\nProbability Distribution : \n [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]\n" }, { "code": null, "e": 26993, "s": 26957, "text": "Code #3 : Graphical Representation." }, { "code": "import numpy as np import matplotlib.pyplot as plt distribution = np.linspace(0, np.minimum(rv.dist.b, 3)) print(\"Distribution : \\n\", distribution) plot = plt.plot(distribution, rv.pdf(distribution)) ", "e": 27204, "s": 26993, "text": null }, { "code": null, "e": 27213, "s": 27204, "text": "Output :" }, { "code": null, "e": 27791, "s": 27213, "text": "Distribution : \n [0. 0.02040816 0.04081633 0.06122449 0.08163265 0.10204082\n 0.12244898 0.14285714 0.16326531 0.18367347 0.20408163 0.2244898\n 0.24489796 0.26530612 0.28571429 0.30612245 0.32653061 0.34693878\n 0.36734694 0.3877551 0.40816327 0.42857143 0.44897959 0.46938776\n 0.48979592 0.51020408 0.53061224 0.55102041 0.57142857 0.59183673\n 0.6122449 0.63265306 0.65306122 0.67346939 0.69387755 0.71428571\n 0.73469388 0.75510204 0.7755102 0.79591837 0.81632653 0.83673469\n 0.85714286 0.87755102 0.89795918 0.91836735 0.93877551 0.95918367\n 0.97959184 1. ]\n " }, { "code": null, "e": 27830, "s": 27791, "text": "Code #4 : Varying Positional Arguments" }, { "code": "import matplotlib.pyplot as plt import numpy as np x = np.linspace(0, 5, 100) # Varying positional arguments y1 = johnsonsb .pdf(x, 1, 3) y2 = johnsonsb .pdf(x, 1, 4) plt.plot(x, y1, \"*\", x, y2, \"r--\") ", "e": 28043, "s": 27830, "text": null }, { "code": null, "e": 28052, "s": 28043, "text": "Output :" }, { "code": null, "e": 28081, "s": 28052, "text": "Python scipy-stats-functions" }, { "code": null, "e": 28088, "s": 28081, "text": "Python" }, { "code": null, "e": 28186, "s": 28088, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28204, "s": 28186, "text": "Python Dictionary" }, { "code": null, "e": 28239, "s": 28204, "text": "Read a file line by line in Python" }, { "code": null, "e": 28271, "s": 28239, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28293, "s": 28271, "text": "Enumerate() in Python" }, { "code": null, "e": 28335, "s": 28293, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28365, "s": 28335, "text": "Iterate over a list in Python" }, { "code": null, "e": 28391, "s": 28365, "text": "Python String | replace()" }, { "code": null, "e": 28420, "s": 28391, "text": "*args and **kwargs in Python" }, { "code": null, "e": 28464, "s": 28420, "text": "Reading and Writing to text files in Python" } ]
How to check the given path is file or directory in node.js ? - GeeksforGeeks
27 Feb, 2020 Sometimes there is a need to check whether the given path is file or directory so that different operations can be performed based on the result. For instance, to log the information of the directory and file separately.In Node.js, file handling is handled by fs module. You can read more about it here. We can check the path for file or directory in Node.js in both Synchronous and Asynchronous way. Note: Asynchronous version is usually preferable if you care about application performance. Synchronous method: Synchronous operations are great for performing one-time file/directory operations before returning a module. To check the path in synchronous mode in fs module, we can use statSync() method. The fs.statSync(path) method returns the instance of fs.Stats which is assigned to variable stats. A fs.Stats object provides information about a file. The stats.isFile() method returns true if the file path is File, otherwise returns false. The stats.isDirectory() method returns true if file path is Directory, otherwise returns false. Example 1: // Require the given module var fs = require('fs'); // Use statSync() method to store the returned// instance into variable named statsvar stats = fs.statSync("/Users/divyarani/Documents/geekforgeeks/geeks.js"); // Use isFile() method to log the result to screenconsole.log('is file ? ' + stats.isFile()); var stats = fs.statSync("/Users/divyarani/Documents/geekforgeeks/geek"); // Use isDirectory() method to log the result to screenconsole.log('is directory ? ' + stats.isDirectory()); Output: is file ? true is directory ? true Example 2: // Require the given module var fs = require('fs'); // Use statSync() method to store the returned// instance into variable named statsvar stats = fs.statSync("/Users/divyarani/Documents/geekforgeeks/geek"); // Use isFile() method to log the result to the screenconsole.log('is file ? ' + stats.isFile()); var stats = fs.statSync("/Users/divyarani/Documents/geekforgeeks/geeks.js"); // Use isDirectory() method to log the result to screenconsole.log('is directory ? ' + stats.isDirectory()); Output: is file ? false is directory ? false Asynchronous method: In the Asynchronous version, the code block within the function will be mostly non-blocking to the end-user and user will not be prevented to perform different actions for various sub-processes. To check the path in asynchronous mode in the fs module we can use fs.stat() method. The fs.stat() method takes two parameters, first parameter is the path and the second is the callback function with two parameters, one is for error in case error occurred and the second parameter is the data retrieved by calling fs.stat() method which is stored in stats variable. The stats.isFile() method returns true if the file path is File, otherwise returns false. The stats.isDirectory() method returns true if file path is Directory, otherwise returns false. Example 1: // Require the given module var fs = require('fs'),path = "/Users/divyarani/Documents/geekforgeeks/geek" // Use stat() methodfs.stat(path, (err, stats) => { if( !err ){ if(stats.isFile()){ console.log('is file ? ' + stats.isFile()); } else if(stats.isDirectory()){ console.log('is directory? ' + stats.isDirectory()); } } else throw err; }); Output: is directory? true Example 2: // Require the given modulevar fs = require('fs'),path = "/Users/divyarani/Documents/geekforgeeks/geeks.js" // Use stat() methodfs.stat(path, (err, stats) => { if( !err ){ if(stats.isFile()){ console.log('is file ? ' + stats.isFile()); } else if(stats.isDirectory()){ console.log('is directory? ' + stats.isDirectory()); } } else throw err; }); Output: is file ? true Node.js-Misc Picked Node.js Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to connect Node.js with React.js ? Node.js Export Module Difference between dependencies, devDependencies and peerDependencies Mongoose Populate() Method Mongoose find() Function Remove elements from a JavaScript Array 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 Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26267, "s": 26239, "text": "\n27 Feb, 2020" }, { "code": null, "e": 26668, "s": 26267, "text": "Sometimes there is a need to check whether the given path is file or directory so that different operations can be performed based on the result. For instance, to log the information of the directory and file separately.In Node.js, file handling is handled by fs module. You can read more about it here. We can check the path for file or directory in Node.js in both Synchronous and Asynchronous way." }, { "code": null, "e": 26760, "s": 26668, "text": "Note: Asynchronous version is usually preferable if you care about application performance." }, { "code": null, "e": 27310, "s": 26760, "text": "Synchronous method: Synchronous operations are great for performing one-time file/directory operations before returning a module. To check the path in synchronous mode in fs module, we can use statSync() method. The fs.statSync(path) method returns the instance of fs.Stats which is assigned to variable stats. A fs.Stats object provides information about a file. The stats.isFile() method returns true if the file path is File, otherwise returns false. The stats.isDirectory() method returns true if file path is Directory, otherwise returns false." }, { "code": null, "e": 27321, "s": 27310, "text": "Example 1:" }, { "code": "// Require the given module var fs = require('fs'); // Use statSync() method to store the returned// instance into variable named statsvar stats = fs.statSync(\"/Users/divyarani/Documents/geekforgeeks/geeks.js\"); // Use isFile() method to log the result to screenconsole.log('is file ? ' + stats.isFile()); var stats = fs.statSync(\"/Users/divyarani/Documents/geekforgeeks/geek\"); // Use isDirectory() method to log the result to screenconsole.log('is directory ? ' + stats.isDirectory());", "e": 27816, "s": 27321, "text": null }, { "code": null, "e": 27824, "s": 27816, "text": "Output:" }, { "code": null, "e": 27859, "s": 27824, "text": "is file ? true\nis directory ? true" }, { "code": null, "e": 27870, "s": 27859, "text": "Example 2:" }, { "code": "// Require the given module var fs = require('fs'); // Use statSync() method to store the returned// instance into variable named statsvar stats = fs.statSync(\"/Users/divyarani/Documents/geekforgeeks/geek\"); // Use isFile() method to log the result to the screenconsole.log('is file ? ' + stats.isFile()); var stats = fs.statSync(\"/Users/divyarani/Documents/geekforgeeks/geeks.js\"); // Use isDirectory() method to log the result to screenconsole.log('is directory ? ' + stats.isDirectory());", "e": 28371, "s": 27870, "text": null }, { "code": null, "e": 28379, "s": 28371, "text": "Output:" }, { "code": null, "e": 28416, "s": 28379, "text": "is file ? false\nis directory ? false" }, { "code": null, "e": 29185, "s": 28416, "text": "Asynchronous method: In the Asynchronous version, the code block within the function will be mostly non-blocking to the end-user and user will not be prevented to perform different actions for various sub-processes. To check the path in asynchronous mode in the fs module we can use fs.stat() method. The fs.stat() method takes two parameters, first parameter is the path and the second is the callback function with two parameters, one is for error in case error occurred and the second parameter is the data retrieved by calling fs.stat() method which is stored in stats variable. The stats.isFile() method returns true if the file path is File, otherwise returns false. The stats.isDirectory() method returns true if file path is Directory, otherwise returns false." }, { "code": null, "e": 29196, "s": 29185, "text": "Example 1:" }, { "code": "// Require the given module var fs = require('fs'),path = \"/Users/divyarani/Documents/geekforgeeks/geek\" // Use stat() methodfs.stat(path, (err, stats) => { if( !err ){ if(stats.isFile()){ console.log('is file ? ' + stats.isFile()); } else if(stats.isDirectory()){ console.log('is directory? ' + stats.isDirectory()); } } else throw err; });", "e": 29618, "s": 29196, "text": null }, { "code": null, "e": 29626, "s": 29618, "text": "Output:" }, { "code": null, "e": 29645, "s": 29626, "text": "is directory? true" }, { "code": null, "e": 29656, "s": 29645, "text": "Example 2:" }, { "code": "// Require the given modulevar fs = require('fs'),path = \"/Users/divyarani/Documents/geekforgeeks/geeks.js\" // Use stat() methodfs.stat(path, (err, stats) => { if( !err ){ if(stats.isFile()){ console.log('is file ? ' + stats.isFile()); } else if(stats.isDirectory()){ console.log('is directory? ' + stats.isDirectory()); } } else throw err; });", "e": 30058, "s": 29656, "text": null }, { "code": null, "e": 30066, "s": 30058, "text": "Output:" }, { "code": null, "e": 30081, "s": 30066, "text": "is file ? true" }, { "code": null, "e": 30094, "s": 30081, "text": "Node.js-Misc" }, { "code": null, "e": 30101, "s": 30094, "text": "Picked" }, { "code": null, "e": 30109, "s": 30101, "text": "Node.js" }, { "code": null, "e": 30126, "s": 30109, "text": "Web Technologies" }, { "code": null, "e": 30153, "s": 30126, "text": "Web technologies Questions" }, { "code": null, "e": 30251, "s": 30153, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30290, "s": 30251, "text": "How to connect Node.js with React.js ?" }, { "code": null, "e": 30312, "s": 30290, "text": "Node.js Export Module" }, { "code": null, "e": 30382, "s": 30312, "text": "Difference between dependencies, devDependencies and peerDependencies" }, { "code": null, "e": 30409, "s": 30382, "text": "Mongoose Populate() Method" }, { "code": null, "e": 30434, "s": 30409, "text": "Mongoose find() Function" }, { "code": null, "e": 30474, "s": 30434, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 30519, "s": 30474, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 30562, "s": 30519, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 30624, "s": 30562, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
Minimum sum of product of two arrays - GeeksforGeeks
20 Apr, 2022 Find the minimum sum of Products of two arrays of the same size, given that k modifications are allowed on the first array. In each modification, one array element of the first array can either be increased or decreased by 2.Examples: Input : a[] = {1, 2, -3} b[] = {-2, 3, -5} k = 5 Output : -31 Explanation: Here n = 3 and k = 5. So, we modified a[2], which is -3 and increased it by 10 (as 5 modifications are allowed). Final sum will be : (1 * -2) + (2 * 3) + (7 * -5) -2 + 6 - 35 -31 (which is the minimum sum of the array with given conditions) Input : a[] = {2, 3, 4, 5, 4} b[] = {3, 4, 2, 3, 2} k = 3 Output : 25 Explanation: Here, total numbers are 5 and total modifications allowed are 3. So, modify a[1], which is 3 and decreased it by 6 (as 3 modifications are allowed). Final sum will be : (2 * 3) + (-3 * 4) + (4 * 2) + (5 * 3) + (4 * 2) 6 – 12 + 8 + 15 + 8 25 (which is the minimum sum of the array with given conditions) Since we need to minimize the product sum, we find the maximum product and reduce it. By taking some examples, we observe that making 2*k changes to only one element is enough to get the minimum sum. Based on this observation, we consider every element as the element on which we apply all k operations and keep track of the element that reduces result to minimum. C++ C Java Python3 C# PHP Javascript // CPP program to find minimum sum of product of two arrays// with k operations allowed on first array.#include <bits/stdc++.h>using namespace std; // Function to find the minimum productint minproduct(int a[], int b[], int n, int k){ int diff = 0, res = 0; int temp; for (int i = 0; i < n; i++) { // Find product of current elements and update // result. int pro = a[i] * b[i]; res = res + pro; // If both product and b[i] are negative, we must // increase value of a[i] to minimize result. if (pro < 0 && b[i] < 0) temp = (a[i] + 2 * k) * b[i]; // If both product and a[i] are negative, we must // decrease value of a[i] to minimize result. else if (pro < 0 && a[i] < 0) temp = (a[i] - 2 * k) * b[i]; // Similar to above two cases for positive product. else if (pro > 0 && a[i] < 0) temp = (a[i] + 2 * k) * b[i]; else if (pro > 0 && a[i] > 0) temp = (a[i] - 2 * k) * b[i]; // Check if current difference becomes higher than // the maximum difference so far. int d = abs(pro - temp); if (d > diff) diff = d; } return res - diff;} // Driver functionint main(){ int a[] = { 2, 3, 4, 5, 4 }; int b[] = { 3, 4, 2, 3, 2 }; int n = 5, k = 3; cout << minproduct(a, b, n, k) << endl; return 0;} // This code is contributed by Sania Kumari Gupta // C program to find minimum sum of product// of two arrays with k operations allowed on// first array.#include <stdio.h>#include<stdlib.h> // Function to find the minimum productint minproduct(int a[], int b[], int n, int k){ int diff = 0, res = 0; int temp; for (int i = 0; i < n; i++) { // Find product of current elements and update // result. int pro = a[i] * b[i]; res = res + pro; // If both product and b[i] are negative, we must // increase value of a[i] to minimize result. if (pro < 0 && b[i] < 0) temp = (a[i] + 2 * k) * b[i]; // If both product and a[i] are negative, we must // decrease value of a[i] to minimize result. else if (pro < 0 && a[i] < 0) temp = (a[i] - 2 * k) * b[i]; // Similar to above two cases for positive product. else if (pro > 0 && a[i] < 0) temp = (a[i] + 2 * k) * b[i]; else if (pro > 0 && a[i] > 0) temp = (a[i] - 2 * k) * b[i]; // Check if current difference becomes higher than // the maximum difference so far. int d = abs(pro - temp); if (d > diff) diff = d; } return res - diff;} // Driver functionint main(){ int a[] = { 2, 3, 4, 5, 4 }; int b[] = { 3, 4, 2, 3, 2 }; int n = 5, k = 3; printf("%d ",minproduct(a, b, n, k)); return 0;} // This code is contributed by Sania Kumari Gupta // Java program to find minimum sum of product of two arrays// with k operations allowed on first array.import java.math.*; class GFG { // Function to find the minimum product static int minproduct(int a[], int b[], int n, int k) { int diff = 0, res = 0; int temp = 0; for (int i = 0; i < n; i++) { // Find product of current elements and update // result. int pro = a[i] * b[i]; res = res + pro; // If both product and b[i] are negative, we // must increase value of a[i] to minimize // result. if (pro < 0 && b[i] < 0) temp = (a[i] + 2 * k) * b[i]; // If both product and a[i] are negative, we // must decrease value of a[i] to minimize // result. else if (pro < 0 && a[i] < 0) temp = (a[i] - 2 * k) * b[i]; // Similar to above two cases for positive // product. else if (pro > 0 && a[i] < 0) temp = (a[i] + 2 * k) * b[i]; else if (pro > 0 && a[i] > 0) temp = (a[i] - 2 * k) * b[i]; // Check if current difference becomes higher // than the maximum difference so far. int d = Math.abs(pro - temp); if (d > diff) diff = d; } return res - diff; } // Driver function public static void main(String[] args) { int a[] = { 2, 3, 4, 5, 4 }; int b[] = { 3, 4, 2, 3, 2 }; int n = 5, k = 3; System.out.println(minproduct(a, b, n, k)); }} // This code is contributed by Sania Kumari Gupta # Python program to find# minimum sum of product# of two arrays with k# operations allowed on# first array. # Function to find the minimum productdef minproduct(a,b,n,k): diff = 0 res = 0 for i in range(n): # Find product of current # elements and update result. pro = a[i] * b[i] res = res + pro # If both product and # b[i] are negative, # we must increase value # of a[i] to minimize result. if (pro < 0 and b[i] < 0): temp = (a[i] + 2 * k) * b[i] # If both product and # a[i] are negative, # we must decrease value # of a[i] to minimize result. elif (pro < 0 and a[i] < 0): temp = (a[i] - 2 * k) * b[i] # Similar to above two cases # for positive product. elif (pro > 0 and a[i] < 0): temp = (a[i] + 2 * k) * b[i] elif (pro > 0 and a[i] > 0): temp = (a[i] - 2 * k) * b[i] # Check if current difference # becomes higher # than the maximum difference so far. d = abs(pro - temp) if (d > diff): diff = d return res - diff # Driver functiona = [ 2, 3, 4, 5, 4 ]b = [ 3, 4, 2, 3, 2 ]n = 5k = 3 print(minproduct(a, b, n, k)) # This code is contributed# by Azkia Anam. // C# program to find minimum sum// of product of two arrays with k// operations allowed on first array.using System; class GFG { // Function to find the minimum product static int minproduct(int []a, int []b, int n, int k) { int diff = 0, res = 0; int temp = 0; for (int i = 0; i < n; i++) { // Find product of current elements // and update result. int pro = a[i] * b[i]; res = res + pro; // If both product and b[i] are // negative, we must increase value // of a[i] to minimize result. if (pro < 0 && b[i] < 0) temp = (a[i] + 2 * k) * b[i]; // If both product and a[i] are // negative, we must decrease value // of a[i] to minimize result. else if (pro < 0 && a[i] < 0) temp = (a[i] - 2 * k) * b[i]; // Similar to above two cases // for positive product. else if (pro > 0 && a[i] < 0) temp = (a[i] + 2 * k) * b[i]; else if (pro > 0 && a[i] > 0) temp = (a[i] - 2 * k) * b[i]; // Check if current difference // becomes higher than the maximum // difference so far. int d = Math.Abs(pro - temp); if (d > diff) diff = d; } return res - diff; } // Driver function public static void Main() { int []a = { 2, 3, 4, 5, 4 }; int []b = { 3, 4, 2, 3, 2 }; int n = 5, k = 3; Console.WriteLine(minproduct(a, b, n, k)); }} // This code is contributed by vt_m. <?php// PHP program to find minimum sum of product// of two arrays with k operations allowed on// first array. // Function to find the minimum productfunction minproduct( $a, $b, $n, $k){ $diff = 0; $res = 0; $temp; for ( $i = 0; $i < $n; $i++) { // Find product of current // elements and update // result. $pro = $a[$i] * $b[$i]; $res = $res + $pro; // If both product and b[i] // are negative, we must // increase value of a[i] // to minimize result. if ($pro < 0 and $b[$i] < 0) $temp = ($a[$i] + 2 * $k) * $b[$i]; // If both product and // a[i] are negative, // we must decrease value // of a[i] to minimize // result. else if ($pro < 0 and $a[$i] < 0) $temp = ($a[$i] - 2 * $k) * $b[$i]; // Similar to above two // cases for positive // product. else if ($pro > 0 and $a[$i] < 0) $temp = ($a[$i] + 2 * $k) * $b[$i]; else if ($pro > 0 and $a[$i] > 0) $temp = ($a[$i] - 2 * $k) * $b[$i]; // Check if current difference becomes higher // than the maximum difference so far. $d = abs($pro - $temp); if ($d > $diff) $diff = $d; } return $res - $diff;} // Driver Code $a = array(2, 3, 4, 5, 4 ,0); $b =array(3, 4, 2, 3, 2); $n = 5; $k = 3; echo minproduct($a, $b, $n, $k); // This code is contributed by anuj_67.?> <script>// Javascript program to find minimum sum// of product of two arrays with k// operations allowed on first array. // Function to find the minimum productfunction minproduct(a, b, n, k){ let diff = 0, res = 0; let temp = 0; for (let i = 0; i < n; i++) { // Find product of current elements // and update result. let pro = a[i] * b[i]; res = res + pro; // If both product and b[i] are // negative, we must increase value // of a[i] to minimize result. if (pro < 0 && b[i] < 0) temp = (a[i] + 2 * k) * b[i]; // If both product and a[i] are // negative, we must decrease value // of a[i] to minimize result. else if (pro < 0 && a[i] < 0) temp = (a[i] - 2 * k) * b[i]; // Similar to above two cases // for positive product. else if (pro > 0 && a[i] < 0) temp = (a[i] + 2 * k) * b[i]; else if (pro > 0 && a[i] > 0) temp = (a[i] - 2 * k) * b[i]; // Check if current difference // becomes higher than the maximum // difference so far. let d = Math.abs(pro - temp); if (d > diff) diff = d; } return res - diff;} // Driver code let a = [ 2, 3, 4, 5, 4 ]; let b = [ 3, 4, 2, 3, 2 ]; let n = 5, k = 3; document.write(minproduct(a, b, n, k)); // This code is contributed by sanjoy_62.</script> Output : 25 This article is contributed by Abhishek Sharma. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. vt_m firoz_baba sanjoy_62 arunabhguptamin20 krisania804 Arrays Greedy Technical Scripter Arrays Greedy 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 Dijkstra's shortest path algorithm | Greedy Algo-7 Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5 Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2 Write a program to print all permutations of a given string Huffman Coding | Greedy Algo-3
[ { "code": null, "e": 26571, "s": 26543, "text": "\n20 Apr, 2022" }, { "code": null, "e": 26807, "s": 26571, "text": "Find the minimum sum of Products of two arrays of the same size, given that k modifications are allowed on the first array. In each modification, one array element of the first array can either be increased or decreased by 2.Examples: " }, { "code": null, "e": 27633, "s": 26807, "text": "Input : a[] = {1, 2, -3}\n b[] = {-2, 3, -5}\n k = 5\nOutput : -31\nExplanation:\nHere n = 3 and k = 5. \nSo, we modified a[2], which is -3 and \nincreased it by 10 (as 5 modifications \nare allowed).\nFinal sum will be :\n(1 * -2) + (2 * 3) + (7 * -5)\n -2 + 6 - 35\n -31\n(which is the minimum sum of the array \nwith given conditions)\n\nInput : a[] = {2, 3, 4, 5, 4}\n b[] = {3, 4, 2, 3, 2}\n k = 3\nOutput : 25\nExplanation: \nHere, total numbers are 5 and total \nmodifications allowed are 3. So, modify \na[1], which is 3 and decreased it by 6 \n(as 3 modifications are allowed).\nFinal sum will be :\n(2 * 3) + (-3 * 4) + (4 * 2) + (5 * 3) + (4 * 2)\n 6 – 12 + 8 + 15 + 8\n 25\n(which is the minimum sum of the array with \ngiven conditions)" }, { "code": null, "e": 28000, "s": 27633, "text": "Since we need to minimize the product sum, we find the maximum product and reduce it. By taking some examples, we observe that making 2*k changes to only one element is enough to get the minimum sum. Based on this observation, we consider every element as the element on which we apply all k operations and keep track of the element that reduces result to minimum. " }, { "code": null, "e": 28004, "s": 28000, "text": "C++" }, { "code": null, "e": 28006, "s": 28004, "text": "C" }, { "code": null, "e": 28011, "s": 28006, "text": "Java" }, { "code": null, "e": 28019, "s": 28011, "text": "Python3" }, { "code": null, "e": 28022, "s": 28019, "text": "C#" }, { "code": null, "e": 28026, "s": 28022, "text": "PHP" }, { "code": null, "e": 28037, "s": 28026, "text": "Javascript" }, { "code": "// CPP program to find minimum sum of product of two arrays// with k operations allowed on first array.#include <bits/stdc++.h>using namespace std; // Function to find the minimum productint minproduct(int a[], int b[], int n, int k){ int diff = 0, res = 0; int temp; for (int i = 0; i < n; i++) { // Find product of current elements and update // result. int pro = a[i] * b[i]; res = res + pro; // If both product and b[i] are negative, we must // increase value of a[i] to minimize result. if (pro < 0 && b[i] < 0) temp = (a[i] + 2 * k) * b[i]; // If both product and a[i] are negative, we must // decrease value of a[i] to minimize result. else if (pro < 0 && a[i] < 0) temp = (a[i] - 2 * k) * b[i]; // Similar to above two cases for positive product. else if (pro > 0 && a[i] < 0) temp = (a[i] + 2 * k) * b[i]; else if (pro > 0 && a[i] > 0) temp = (a[i] - 2 * k) * b[i]; // Check if current difference becomes higher than // the maximum difference so far. int d = abs(pro - temp); if (d > diff) diff = d; } return res - diff;} // Driver functionint main(){ int a[] = { 2, 3, 4, 5, 4 }; int b[] = { 3, 4, 2, 3, 2 }; int n = 5, k = 3; cout << minproduct(a, b, n, k) << endl; return 0;} // This code is contributed by Sania Kumari Gupta", "e": 29485, "s": 28037, "text": null }, { "code": "// C program to find minimum sum of product// of two arrays with k operations allowed on// first array.#include <stdio.h>#include<stdlib.h> // Function to find the minimum productint minproduct(int a[], int b[], int n, int k){ int diff = 0, res = 0; int temp; for (int i = 0; i < n; i++) { // Find product of current elements and update // result. int pro = a[i] * b[i]; res = res + pro; // If both product and b[i] are negative, we must // increase value of a[i] to minimize result. if (pro < 0 && b[i] < 0) temp = (a[i] + 2 * k) * b[i]; // If both product and a[i] are negative, we must // decrease value of a[i] to minimize result. else if (pro < 0 && a[i] < 0) temp = (a[i] - 2 * k) * b[i]; // Similar to above two cases for positive product. else if (pro > 0 && a[i] < 0) temp = (a[i] + 2 * k) * b[i]; else if (pro > 0 && a[i] > 0) temp = (a[i] - 2 * k) * b[i]; // Check if current difference becomes higher than // the maximum difference so far. int d = abs(pro - temp); if (d > diff) diff = d; } return res - diff;} // Driver functionint main(){ int a[] = { 2, 3, 4, 5, 4 }; int b[] = { 3, 4, 2, 3, 2 }; int n = 5, k = 3; printf(\"%d \",minproduct(a, b, n, k)); return 0;} // This code is contributed by Sania Kumari Gupta", "e": 30922, "s": 29485, "text": null }, { "code": "// Java program to find minimum sum of product of two arrays// with k operations allowed on first array.import java.math.*; class GFG { // Function to find the minimum product static int minproduct(int a[], int b[], int n, int k) { int diff = 0, res = 0; int temp = 0; for (int i = 0; i < n; i++) { // Find product of current elements and update // result. int pro = a[i] * b[i]; res = res + pro; // If both product and b[i] are negative, we // must increase value of a[i] to minimize // result. if (pro < 0 && b[i] < 0) temp = (a[i] + 2 * k) * b[i]; // If both product and a[i] are negative, we // must decrease value of a[i] to minimize // result. else if (pro < 0 && a[i] < 0) temp = (a[i] - 2 * k) * b[i]; // Similar to above two cases for positive // product. else if (pro > 0 && a[i] < 0) temp = (a[i] + 2 * k) * b[i]; else if (pro > 0 && a[i] > 0) temp = (a[i] - 2 * k) * b[i]; // Check if current difference becomes higher // than the maximum difference so far. int d = Math.abs(pro - temp); if (d > diff) diff = d; } return res - diff; } // Driver function public static void main(String[] args) { int a[] = { 2, 3, 4, 5, 4 }; int b[] = { 3, 4, 2, 3, 2 }; int n = 5, k = 3; System.out.println(minproduct(a, b, n, k)); }} // This code is contributed by Sania Kumari Gupta", "e": 32592, "s": 30922, "text": null }, { "code": "# Python program to find# minimum sum of product# of two arrays with k# operations allowed on# first array. # Function to find the minimum productdef minproduct(a,b,n,k): diff = 0 res = 0 for i in range(n): # Find product of current # elements and update result. pro = a[i] * b[i] res = res + pro # If both product and # b[i] are negative, # we must increase value # of a[i] to minimize result. if (pro < 0 and b[i] < 0): temp = (a[i] + 2 * k) * b[i] # If both product and # a[i] are negative, # we must decrease value # of a[i] to minimize result. elif (pro < 0 and a[i] < 0): temp = (a[i] - 2 * k) * b[i] # Similar to above two cases # for positive product. elif (pro > 0 and a[i] < 0): temp = (a[i] + 2 * k) * b[i] elif (pro > 0 and a[i] > 0): temp = (a[i] - 2 * k) * b[i] # Check if current difference # becomes higher # than the maximum difference so far. d = abs(pro - temp) if (d > diff): diff = d return res - diff # Driver functiona = [ 2, 3, 4, 5, 4 ]b = [ 3, 4, 2, 3, 2 ]n = 5k = 3 print(minproduct(a, b, n, k)) # This code is contributed# by Azkia Anam.", "e": 33899, "s": 32592, "text": null }, { "code": "// C# program to find minimum sum// of product of two arrays with k// operations allowed on first array.using System; class GFG { // Function to find the minimum product static int minproduct(int []a, int []b, int n, int k) { int diff = 0, res = 0; int temp = 0; for (int i = 0; i < n; i++) { // Find product of current elements // and update result. int pro = a[i] * b[i]; res = res + pro; // If both product and b[i] are // negative, we must increase value // of a[i] to minimize result. if (pro < 0 && b[i] < 0) temp = (a[i] + 2 * k) * b[i]; // If both product and a[i] are // negative, we must decrease value // of a[i] to minimize result. else if (pro < 0 && a[i] < 0) temp = (a[i] - 2 * k) * b[i]; // Similar to above two cases // for positive product. else if (pro > 0 && a[i] < 0) temp = (a[i] + 2 * k) * b[i]; else if (pro > 0 && a[i] > 0) temp = (a[i] - 2 * k) * b[i]; // Check if current difference // becomes higher than the maximum // difference so far. int d = Math.Abs(pro - temp); if (d > diff) diff = d; } return res - diff; } // Driver function public static void Main() { int []a = { 2, 3, 4, 5, 4 }; int []b = { 3, 4, 2, 3, 2 }; int n = 5, k = 3; Console.WriteLine(minproduct(a, b, n, k)); }} // This code is contributed by vt_m.", "e": 35625, "s": 33899, "text": null }, { "code": "<?php// PHP program to find minimum sum of product// of two arrays with k operations allowed on// first array. // Function to find the minimum productfunction minproduct( $a, $b, $n, $k){ $diff = 0; $res = 0; $temp; for ( $i = 0; $i < $n; $i++) { // Find product of current // elements and update // result. $pro = $a[$i] * $b[$i]; $res = $res + $pro; // If both product and b[i] // are negative, we must // increase value of a[i] // to minimize result. if ($pro < 0 and $b[$i] < 0) $temp = ($a[$i] + 2 * $k) * $b[$i]; // If both product and // a[i] are negative, // we must decrease value // of a[i] to minimize // result. else if ($pro < 0 and $a[$i] < 0) $temp = ($a[$i] - 2 * $k) * $b[$i]; // Similar to above two // cases for positive // product. else if ($pro > 0 and $a[$i] < 0) $temp = ($a[$i] + 2 * $k) * $b[$i]; else if ($pro > 0 and $a[$i] > 0) $temp = ($a[$i] - 2 * $k) * $b[$i]; // Check if current difference becomes higher // than the maximum difference so far. $d = abs($pro - $temp); if ($d > $diff) $diff = $d; } return $res - $diff;} // Driver Code $a = array(2, 3, 4, 5, 4 ,0); $b =array(3, 4, 2, 3, 2); $n = 5; $k = 3; echo minproduct($a, $b, $n, $k); // This code is contributed by anuj_67.?>", "e": 37146, "s": 35625, "text": null }, { "code": "<script>// Javascript program to find minimum sum// of product of two arrays with k// operations allowed on first array. // Function to find the minimum productfunction minproduct(a, b, n, k){ let diff = 0, res = 0; let temp = 0; for (let i = 0; i < n; i++) { // Find product of current elements // and update result. let pro = a[i] * b[i]; res = res + pro; // If both product and b[i] are // negative, we must increase value // of a[i] to minimize result. if (pro < 0 && b[i] < 0) temp = (a[i] + 2 * k) * b[i]; // If both product and a[i] are // negative, we must decrease value // of a[i] to minimize result. else if (pro < 0 && a[i] < 0) temp = (a[i] - 2 * k) * b[i]; // Similar to above two cases // for positive product. else if (pro > 0 && a[i] < 0) temp = (a[i] + 2 * k) * b[i]; else if (pro > 0 && a[i] > 0) temp = (a[i] - 2 * k) * b[i]; // Check if current difference // becomes higher than the maximum // difference so far. let d = Math.abs(pro - temp); if (d > diff) diff = d; } return res - diff;} // Driver code let a = [ 2, 3, 4, 5, 4 ]; let b = [ 3, 4, 2, 3, 2 ]; let n = 5, k = 3; document.write(minproduct(a, b, n, k)); // This code is contributed by sanjoy_62.</script>", "e": 38595, "s": 37146, "text": null }, { "code": null, "e": 38604, "s": 38595, "text": "Output :" }, { "code": null, "e": 38607, "s": 38604, "text": "25" }, { "code": null, "e": 39031, "s": 38607, "text": "This article is contributed by Abhishek Sharma. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 39036, "s": 39031, "text": "vt_m" }, { "code": null, "e": 39047, "s": 39036, "text": "firoz_baba" }, { "code": null, "e": 39057, "s": 39047, "text": "sanjoy_62" }, { "code": null, "e": 39075, "s": 39057, "text": "arunabhguptamin20" }, { "code": null, "e": 39087, "s": 39075, "text": "krisania804" }, { "code": null, "e": 39094, "s": 39087, "text": "Arrays" }, { "code": null, "e": 39101, "s": 39094, "text": "Greedy" }, { "code": null, "e": 39120, "s": 39101, "text": "Technical Scripter" }, { "code": null, "e": 39127, "s": 39120, "text": "Arrays" }, { "code": null, "e": 39134, "s": 39127, "text": "Greedy" }, { "code": null, "e": 39232, "s": 39134, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 39300, "s": 39232, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 39344, "s": 39300, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 39392, "s": 39344, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 39415, "s": 39392, "text": "Introduction to Arrays" }, { "code": null, "e": 39447, "s": 39415, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 39498, "s": 39447, "text": "Dijkstra's shortest path algorithm | Greedy Algo-7" }, { "code": null, "e": 39549, "s": 39498, "text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5" }, { "code": null, "e": 39607, "s": 39549, "text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2" }, { "code": null, "e": 39667, "s": 39607, "text": "Write a program to print all permutations of a given string" } ]
Count ways to reach a score using 1 and 2 with no consecutive 2s - GeeksforGeeks
28 Sep, 2021 A cricket player has to score N runs, with condition he can take either 1 or 2 runs only and consecutive runs should not be 2. Find all the possible combination he can take.Examples: Input : N = 4 Output : 4 1+1+1+1, 1+2+1, 2+1+1, 1+1+2 Input : N = 5 Output : 6 Source :Oracle Interview On campus This problem is a variation of count number of ways to reach given score in a game and can be solved in O(n) time and constant auxiliary space. First run scored could be either : a) 1. Now the player has to score N-1 runs. b) or 2. Since 2’s can not be consecutive runs, next run scored has to be 1. After that, the player has to score N-(2+1) runs.Below is the recursive solution of above problem. Recursion relation would be: CountWays(N) = CountWays(N-1) + CountWays(N-2) Following recursive solution takes exponential time and space (similar to Fibonacci numbers). C++ Java Python3 C# PHP Javascript // A simple recursive implementation for// counting ways to reach a score using 1 and 2 with// consecutive 2 allowed#include <iostream>using namespace std; int CountWays(int n){ // base cases if (n == 0) { return 1; } if (n == 1) { return 1; } if (n == 2) { return 1 + 1; } // For cases n > 2 return CountWays(n - 1) + CountWays(n - 3);} // Driver codeint main(){ int n = 10; cout << CountWays(n); return 0;} // A simple recursive implementation for// counting ways to reach a score using 1 and 2 with// consecutive 2 allowed import java.io.*; class GFG { static int CountWays(int n) { // base cases if (n == 0) { return 1; } if (n == 1) { return 1; } if (n == 2) { return 1 + 1; } // For cases n > 2 return CountWays(n - 1) + CountWays(n - 3); } // Driver code public static void main(String[] args) { int n = 5; System.out.println(CountWays(n)); }} # A simple recursive implementation for# counting ways to reach a score using 1 and 2 with# consecutive 2 allowed def CountWays(n): # base case if n == 0: return 1 if n == 1: return 1 if n == 2: return 1 + 1 # For cases n > 2 return CountWays(n - 1) + CountWays(n - 3) # Driver codeif __name__ == '__main__': n = 5 print(CountWays(n)) // A simple recursive implementation// for counting ways to reach a score// using 1 and 2 with consecutive 2 allowedusing System; class GFG { static int CountWays(int n) { // base cases if (n == 0) { return 1; } if (n == 1) { return 1; } if (n == 2) { return 1 + 1; } // For cases n > 2 return CountWays(n - 1) + CountWays(n - 3); } // Driver Code static public void Main() { int n = 5; Console.WriteLine(CountWays(n)); }} <?php// A simple recursive implementation// for counting ways to reach a score// using 1 and 2 with consecutive 2 allowed function CountWays($n){ // base cases if ($n == 0) { return 1; } if ($n == 1) { return 1; } if ($n == 2) { return 1 + 1; } // For cases n > 2 return CountWays($n - 1) + CountWays($n - 3);} // Driver Code$n = 5;echo CountWays($n);?> <script> // A simple recursive implementation for// counting ways to reach a score using 1 and 2 with// consecutive 2 allowed function CountWays(n, flag){ // base cases if (n == 0) { return 1; } if (n == 1) { return 1; } if (n == 2) { return 1 + 1; } // For cases n > 2 return CountWays(n - 1) + CountWays(n - 3);} // Driver code let n = 5;document.write(CountWays(n, false)); </script> 6 We can store intermediate values and solve it in O(n) time and O(n) space. C++ Java Python3 C# Javascript // Bottom up approach for// counting ways to reach a score using 1 and 2 with// consecutive 2 allowed#include <iostream>using namespace std; int CountWays(int n){ // noOfWays[i] will store count for value i. // 3 extra values are to take care of corner case n = 0 int noOfWays[n + 3]; noOfWays[0] = 1; noOfWays[1] = 1; noOfWays[2] = 1 + 1; // Loop till "n+1" to compute value for "n" for (int i=3; i<n+1; i++) { noOfWays[i] = // number of ways if first run is 1 noOfWays[i-1] // number of ways if first run is 2 // and second run is 1 + noOfWays[i-3]; } return noOfWays[n];} int main(){ int n = 0; cout << CountWays(n); return 0;} import java.util.Arrays; // Bottom up approach for// counting ways to reach a score using// 1 and 2 with consecutive 2 allowedclass GfG { static int CountWays(int n) { // noOfWays[i] will store count for value i. // 3 extra values are to take care of cornser case n // = 0 int noOfWays[] = new int[n + 3]; noOfWays[0] = 1; noOfWays[1] = 1; noOfWays[2] = 1 + 1; // Loop till "n+1" to compute value for "n" for (int i = 3; i < n + 1; i++) { noOfWays[i] = // number of ways if first run is 1 noOfWays[i - 1] // number of ways if first run is 2 // and second run is 1 + noOfWays[i - 3]; } return noOfWays[n]; } public static void main(String[] args) { int n = 5; System.out.println(CountWays(n)); }} # Bottom up approach for# counting ways to reach a score using# 1 and 2 with consecutive 2 allowed def CountWays(n): # noOfWays[i] will store count for value i. # 3 extra values are to take care of corner case n = 0 noOfWays = [0] * (n + 3) noOfWays[0] = 1 noOfWays[1] = 1 noOfWays[2] = 1 + 1 # Loop till "n+1" to compute value for "n" for i in range(3, n+1): # number of ways if first run is 1 # + # number of ways if first run is 2 # and second run is 1 noOfWays[i] = noOfWays[i-1] + noOfWays[i-3] return noOfWays[n] # Driver Codeif __name__ == '__main__': n = 5 print(CountWays(n)) // Bottom up approach for// counting ways to reach a score using// 1 and 2 with consecutive 2 allowedusing System; class GfG{ static int CountWays(int n) { // if this state is already visited return // its value if (dp[n, flag] != -1) { return dp[n, flag]; } // base case if (n == 0) { return 1; } // 2 is not scored last time so we can // score either 2 or 1 int sum = 0; if (flag == 0 && n > 1) { sum = sum + CountWays(n - 1, 0) + CountWays(n - 2, 1); } // 2 is scored last time so we can only score 1 else { sum = sum + CountWays(n - 1, 0); } return dp[n,flag] = sum; } // Driver code public static void Main(String[] args) { int n = 5; for (int i = 0; i <dp.GetLength(0); i++) for (int j = 0; j < dp.GetLength(1); j++) dp[i,j]=-1; Console.WriteLine(CountWays(n, 0)); }} // This code has been contributed by 29AjayKumar <script> // Bottom up approach for// counting ways to reach a score using// 1 and 2 with consecutive 2 allowed function CountWays(n) { // noOfWays[i] will store count for value i. // 3 extra values are to take care of cornser case n // = 0 var noOfWays = Array(n + 3).fill(0); noOfWays[0] = 1; noOfWays[1] = 1; noOfWays[2] = 1 + 1; // Loop till "n+1" to compute value for "n" for (var i = 3; i < n + 1; i++) { // number of ways if first run is 1 // number of ways if first run is 2 // and second run is 1 noOfWays[i] = noOfWays[i - 1] + noOfWays[i - 3]; } return noOfWays[n]; } // Driver code var n = 5; document.write(CountWays(n)); // This code is contributed by gauravrajput1</script> 6 This can be further improved to O(n) time and constant space by storing only last 3 values. C++ Java Python3 C# Javascript // Bottom up approach for// counting ways to reach a score using 1 and 2 with// consecutive 2 allowed#include <iostream>using namespace std; int CountWays(int n){ // noOfWays[i] will store count // for last 3 values before i. int noOfWays[3]; noOfWays[0] = 1; noOfWays[1] = 1; noOfWays[2] = 1 + 1; // Loop till "n+1" to compute value for "n" for (int i=3; i<n+1; i++) { noOfWays[i] = // number of ways if first run is 1 noOfWays[3-1] // number of ways if first run is 2 // and second run is 1 + noOfWays[3-3]; // Remember last 3 values noOfWays[0] = noOfWays[1]; noOfWays[1] = noOfWays[2]; noOfWays[2] = noOfWays[i]; } return noOfWays[n];} int main(){ int n = 5; cout << CountWays(n); return 0;} // Bottom up approach for// counting ways to reach a score using 1 and 2 with// consecutive 2 allowedimport java.io.*;class GFG{ static int CountWays(int n){ // noOfWays[i] will store count // for last 3 values before i. int noOfWays[] = new int[n + 3]; noOfWays[0] = 1; noOfWays[1] = 1; noOfWays[2] = 1 + 1; // Loop till "n+1" to compute value for "n" for (int i=3; i<n+1; i++) { noOfWays[i] = // number of ways if first run is 1 noOfWays[3-1] // number of ways if first run is 2 // and second run is 1 + noOfWays[3-3]; // Remember last 3 values noOfWays[0] = noOfWays[1]; noOfWays[1] = noOfWays[2]; noOfWays[2] = noOfWays[i]; } return noOfWays[n];} // Driver codepublic static void main (String[] args) { int n = 5; System.out.println(CountWays(n));}} // This code is contributed by shivanisinghss2110 # Bottom up approach for# counting ways to reach a score using 1 and 2 with# consecutive 2 alloweddef CountWays(n): # noOfWays[i] will store count # for last 3 values before i. noOfWays = [0] * (n+1) noOfWays[0] = 1 noOfWays[1] = 1 noOfWays[2] = 1 + 1 # Loop till "n+1" to compute value for "n" for i in range(3, n+1): # number of ways if first run is 1 # number of ways if first run is 2 # and second run is 1 noOfWays[i] = noOfWays[3-1] + noOfWays[3-3] # Remember last 3 values noOfWays[0] = noOfWays[1] noOfWays[1] = noOfWays[2] noOfWays[2] = noOfWays[i] return noOfWays[n] if __name__ == '__main__': n = 5 print(CountWays(n)) # this code is contributed by shivanisingh2110 // Bottom up approach for// counting ways to reach a score using 1 and 2 with// consecutive 2 allowedusing System;using System.Collections.Generic;public class GFG { static int CountWays(int n) { // noOfWays[i] will store count // for last 3 values before i. int []noOfWays = new int[n + 3]; noOfWays[0] = 1; noOfWays[1] = 1; noOfWays[2] = 1 + 1; // Loop till "n+1" to compute value for "n" for (int i = 3; i < n + 1; i++) { noOfWays[i] = // number of ways if first run is 1 noOfWays[3 - 1] // number of ways if first run is 2 // and second run is 1 + noOfWays[3 - 3]; // Remember last 3 values noOfWays[0] = noOfWays[1]; noOfWays[1] = noOfWays[2]; noOfWays[2] = noOfWays[i]; } return noOfWays[n]; } // Driver code public static void Main(String[] args) { int n = 5; Console.WriteLine(CountWays(n)); }} // This code is contributed by umadevi9616 <script>// Bottom up approach for// counting ways to reach a score using 1 and 2 with// consecutive 2 allowedfunction CountWays(n){ // noOfWays[i] will store count // for last 3 values before i. var noOfWays = Array(3).fill(0); noOfWays[0] = 1; noOfWays[1] = 1; noOfWays[2] = 1 + 1; // Loop till "n+1" to compute value for "n" for (var i = 3; i < n + 1; i++) { noOfWays[i] = // number of ways if first run is 1 noOfWays[3-1] // number of ways if first run is 2 // and second run is 1 + noOfWays[3-3]; // Remember last 3 values noOfWays[0] = noOfWays[1]; noOfWays[1] = noOfWays[2]; noOfWays[2] = noOfWays[i]; } return noOfWays[n];} var n = 5;document.write(CountWays(n)); // This code is contributed by shivanisinghss2110</script> 6 shrikanth13 Sach_Code SURENDRA_GANGWAR princiraj1992 29AjayKumar surbhityagi15 SoumikMondal puneetgarg80 GauravRajput1 shivanisinghss2110 umadevi9616 Oracle Technical Scripter 2018 Dynamic Programming Recursion Oracle Dynamic Programming Recursion Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Bellman–Ford Algorithm | DP-23 Floyd Warshall Algorithm | DP-16 Subset Sum Problem | DP-25 Matrix Chain Multiplication | DP-8 Longest Palindromic Substring | Set 1 Write a program to print all permutations of a given string Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Recursion Program for Tower of Hanoi Backtracking | Introduction
[ { "code": null, "e": 26195, "s": 26167, "text": "\n28 Sep, 2021" }, { "code": null, "e": 26380, "s": 26195, "text": "A cricket player has to score N runs, with condition he can take either 1 or 2 runs only and consecutive runs should not be 2. Find all the possible combination he can take.Examples: " }, { "code": null, "e": 26461, "s": 26380, "text": "Input : N = 4 \nOutput : 4\n1+1+1+1, 1+2+1, 2+1+1, 1+1+2\n\nInput : N = 5\nOutput : 6" }, { "code": null, "e": 26497, "s": 26461, "text": "Source :Oracle Interview On campus " }, { "code": null, "e": 26641, "s": 26497, "text": "This problem is a variation of count number of ways to reach given score in a game and can be solved in O(n) time and constant auxiliary space." }, { "code": null, "e": 26676, "s": 26641, "text": "First run scored could be either :" }, { "code": null, "e": 26720, "s": 26676, "text": "a) 1. Now the player has to score N-1 runs." }, { "code": null, "e": 26897, "s": 26720, "text": "b) or 2. Since 2’s can not be consecutive runs, next run scored has to be 1. After that, the player has to score N-(2+1) runs.Below is the recursive solution of above problem. " }, { "code": null, "e": 26926, "s": 26897, "text": "Recursion relation would be:" }, { "code": null, "e": 26973, "s": 26926, "text": "CountWays(N) = CountWays(N-1) + CountWays(N-2)" }, { "code": null, "e": 27069, "s": 26973, "text": "Following recursive solution takes exponential time and space (similar to Fibonacci numbers). " }, { "code": null, "e": 27073, "s": 27069, "text": "C++" }, { "code": null, "e": 27078, "s": 27073, "text": "Java" }, { "code": null, "e": 27086, "s": 27078, "text": "Python3" }, { "code": null, "e": 27089, "s": 27086, "text": "C#" }, { "code": null, "e": 27093, "s": 27089, "text": "PHP" }, { "code": null, "e": 27104, "s": 27093, "text": "Javascript" }, { "code": "// A simple recursive implementation for// counting ways to reach a score using 1 and 2 with// consecutive 2 allowed#include <iostream>using namespace std; int CountWays(int n){ // base cases if (n == 0) { return 1; } if (n == 1) { return 1; } if (n == 2) { return 1 + 1; } // For cases n > 2 return CountWays(n - 1) + CountWays(n - 3);} // Driver codeint main(){ int n = 10; cout << CountWays(n); return 0;}", "e": 27571, "s": 27104, "text": null }, { "code": "// A simple recursive implementation for// counting ways to reach a score using 1 and 2 with// consecutive 2 allowed import java.io.*; class GFG { static int CountWays(int n) { // base cases if (n == 0) { return 1; } if (n == 1) { return 1; } if (n == 2) { return 1 + 1; } // For cases n > 2 return CountWays(n - 1) + CountWays(n - 3); } // Driver code public static void main(String[] args) { int n = 5; System.out.println(CountWays(n)); }}", "e": 28146, "s": 27571, "text": null }, { "code": "# A simple recursive implementation for# counting ways to reach a score using 1 and 2 with# consecutive 2 allowed def CountWays(n): # base case if n == 0: return 1 if n == 1: return 1 if n == 2: return 1 + 1 # For cases n > 2 return CountWays(n - 1) + CountWays(n - 3) # Driver codeif __name__ == '__main__': n = 5 print(CountWays(n))", "e": 28530, "s": 28146, "text": null }, { "code": "// A simple recursive implementation// for counting ways to reach a score// using 1 and 2 with consecutive 2 allowedusing System; class GFG { static int CountWays(int n) { // base cases if (n == 0) { return 1; } if (n == 1) { return 1; } if (n == 2) { return 1 + 1; } // For cases n > 2 return CountWays(n - 1) + CountWays(n - 3); } // Driver Code static public void Main() { int n = 5; Console.WriteLine(CountWays(n)); }}", "e": 29086, "s": 28530, "text": null }, { "code": "<?php// A simple recursive implementation// for counting ways to reach a score// using 1 and 2 with consecutive 2 allowed function CountWays($n){ // base cases if ($n == 0) { return 1; } if ($n == 1) { return 1; } if ($n == 2) { return 1 + 1; } // For cases n > 2 return CountWays($n - 1) + CountWays($n - 3);} // Driver Code$n = 5;echo CountWays($n);?>", "e": 29491, "s": 29086, "text": null }, { "code": "<script> // A simple recursive implementation for// counting ways to reach a score using 1 and 2 with// consecutive 2 allowed function CountWays(n, flag){ // base cases if (n == 0) { return 1; } if (n == 1) { return 1; } if (n == 2) { return 1 + 1; } // For cases n > 2 return CountWays(n - 1) + CountWays(n - 3);} // Driver code let n = 5;document.write(CountWays(n, false)); </script>", "e": 29930, "s": 29491, "text": null }, { "code": null, "e": 29932, "s": 29930, "text": "6" }, { "code": null, "e": 30010, "s": 29934, "text": "We can store intermediate values and solve it in O(n) time and O(n) space. " }, { "code": null, "e": 30014, "s": 30010, "text": "C++" }, { "code": null, "e": 30019, "s": 30014, "text": "Java" }, { "code": null, "e": 30027, "s": 30019, "text": "Python3" }, { "code": null, "e": 30030, "s": 30027, "text": "C#" }, { "code": null, "e": 30041, "s": 30030, "text": "Javascript" }, { "code": "// Bottom up approach for// counting ways to reach a score using 1 and 2 with// consecutive 2 allowed#include <iostream>using namespace std; int CountWays(int n){ // noOfWays[i] will store count for value i. // 3 extra values are to take care of corner case n = 0 int noOfWays[n + 3]; noOfWays[0] = 1; noOfWays[1] = 1; noOfWays[2] = 1 + 1; // Loop till \"n+1\" to compute value for \"n\" for (int i=3; i<n+1; i++) { noOfWays[i] = // number of ways if first run is 1 noOfWays[i-1] // number of ways if first run is 2 // and second run is 1 + noOfWays[i-3]; } return noOfWays[n];} int main(){ int n = 0; cout << CountWays(n); return 0;}", "e": 30757, "s": 30041, "text": null }, { "code": "import java.util.Arrays; // Bottom up approach for// counting ways to reach a score using// 1 and 2 with consecutive 2 allowedclass GfG { static int CountWays(int n) { // noOfWays[i] will store count for value i. // 3 extra values are to take care of cornser case n // = 0 int noOfWays[] = new int[n + 3]; noOfWays[0] = 1; noOfWays[1] = 1; noOfWays[2] = 1 + 1; // Loop till \"n+1\" to compute value for \"n\" for (int i = 3; i < n + 1; i++) { noOfWays[i] = // number of ways if first run is 1 noOfWays[i - 1] // number of ways if first run is 2 // and second run is 1 + noOfWays[i - 3]; } return noOfWays[n]; } public static void main(String[] args) { int n = 5; System.out.println(CountWays(n)); }}", "e": 31651, "s": 30757, "text": null }, { "code": "# Bottom up approach for# counting ways to reach a score using# 1 and 2 with consecutive 2 allowed def CountWays(n): # noOfWays[i] will store count for value i. # 3 extra values are to take care of corner case n = 0 noOfWays = [0] * (n + 3) noOfWays[0] = 1 noOfWays[1] = 1 noOfWays[2] = 1 + 1 # Loop till \"n+1\" to compute value for \"n\" for i in range(3, n+1): # number of ways if first run is 1 # + # number of ways if first run is 2 # and second run is 1 noOfWays[i] = noOfWays[i-1] + noOfWays[i-3] return noOfWays[n] # Driver Codeif __name__ == '__main__': n = 5 print(CountWays(n))", "e": 32309, "s": 31651, "text": null }, { "code": "// Bottom up approach for// counting ways to reach a score using// 1 and 2 with consecutive 2 allowedusing System; class GfG{ static int CountWays(int n) { // if this state is already visited return // its value if (dp[n, flag] != -1) { return dp[n, flag]; } // base case if (n == 0) { return 1; } // 2 is not scored last time so we can // score either 2 or 1 int sum = 0; if (flag == 0 && n > 1) { sum = sum + CountWays(n - 1, 0) + CountWays(n - 2, 1); } // 2 is scored last time so we can only score 1 else { sum = sum + CountWays(n - 1, 0); } return dp[n,flag] = sum; } // Driver code public static void Main(String[] args) { int n = 5; for (int i = 0; i <dp.GetLength(0); i++) for (int j = 0; j < dp.GetLength(1); j++) dp[i,j]=-1; Console.WriteLine(CountWays(n, 0)); }} // This code has been contributed by 29AjayKumar", "e": 33413, "s": 32309, "text": null }, { "code": "<script> // Bottom up approach for// counting ways to reach a score using// 1 and 2 with consecutive 2 allowed function CountWays(n) { // noOfWays[i] will store count for value i. // 3 extra values are to take care of cornser case n // = 0 var noOfWays = Array(n + 3).fill(0); noOfWays[0] = 1; noOfWays[1] = 1; noOfWays[2] = 1 + 1; // Loop till \"n+1\" to compute value for \"n\" for (var i = 3; i < n + 1; i++) { // number of ways if first run is 1 // number of ways if first run is 2 // and second run is 1 noOfWays[i] = noOfWays[i - 1] + noOfWays[i - 3]; } return noOfWays[n]; } // Driver code var n = 5; document.write(CountWays(n)); // This code is contributed by gauravrajput1</script>", "e": 34253, "s": 33413, "text": null }, { "code": null, "e": 34255, "s": 34253, "text": "6" }, { "code": null, "e": 34349, "s": 34257, "text": "This can be further improved to O(n) time and constant space by storing only last 3 values." }, { "code": null, "e": 34353, "s": 34349, "text": "C++" }, { "code": null, "e": 34358, "s": 34353, "text": "Java" }, { "code": null, "e": 34366, "s": 34358, "text": "Python3" }, { "code": null, "e": 34369, "s": 34366, "text": "C#" }, { "code": null, "e": 34380, "s": 34369, "text": "Javascript" }, { "code": "// Bottom up approach for// counting ways to reach a score using 1 and 2 with// consecutive 2 allowed#include <iostream>using namespace std; int CountWays(int n){ // noOfWays[i] will store count // for last 3 values before i. int noOfWays[3]; noOfWays[0] = 1; noOfWays[1] = 1; noOfWays[2] = 1 + 1; // Loop till \"n+1\" to compute value for \"n\" for (int i=3; i<n+1; i++) { noOfWays[i] = // number of ways if first run is 1 noOfWays[3-1] // number of ways if first run is 2 // and second run is 1 + noOfWays[3-3]; // Remember last 3 values noOfWays[0] = noOfWays[1]; noOfWays[1] = noOfWays[2]; noOfWays[2] = noOfWays[i]; } return noOfWays[n];} int main(){ int n = 5; cout << CountWays(n); return 0;}", "e": 35188, "s": 34380, "text": null }, { "code": "// Bottom up approach for// counting ways to reach a score using 1 and 2 with// consecutive 2 allowedimport java.io.*;class GFG{ static int CountWays(int n){ // noOfWays[i] will store count // for last 3 values before i. int noOfWays[] = new int[n + 3]; noOfWays[0] = 1; noOfWays[1] = 1; noOfWays[2] = 1 + 1; // Loop till \"n+1\" to compute value for \"n\" for (int i=3; i<n+1; i++) { noOfWays[i] = // number of ways if first run is 1 noOfWays[3-1] // number of ways if first run is 2 // and second run is 1 + noOfWays[3-3]; // Remember last 3 values noOfWays[0] = noOfWays[1]; noOfWays[1] = noOfWays[2]; noOfWays[2] = noOfWays[i]; } return noOfWays[n];} // Driver codepublic static void main (String[] args) { int n = 5; System.out.println(CountWays(n));}} // This code is contributed by shivanisinghss2110", "e": 36106, "s": 35188, "text": null }, { "code": "# Bottom up approach for# counting ways to reach a score using 1 and 2 with# consecutive 2 alloweddef CountWays(n): # noOfWays[i] will store count # for last 3 values before i. noOfWays = [0] * (n+1) noOfWays[0] = 1 noOfWays[1] = 1 noOfWays[2] = 1 + 1 # Loop till \"n+1\" to compute value for \"n\" for i in range(3, n+1): # number of ways if first run is 1 # number of ways if first run is 2 # and second run is 1 noOfWays[i] = noOfWays[3-1] + noOfWays[3-3] # Remember last 3 values noOfWays[0] = noOfWays[1] noOfWays[1] = noOfWays[2] noOfWays[2] = noOfWays[i] return noOfWays[n] if __name__ == '__main__': n = 5 print(CountWays(n)) # this code is contributed by shivanisingh2110", "e": 36904, "s": 36106, "text": null }, { "code": "// Bottom up approach for// counting ways to reach a score using 1 and 2 with// consecutive 2 allowedusing System;using System.Collections.Generic;public class GFG { static int CountWays(int n) { // noOfWays[i] will store count // for last 3 values before i. int []noOfWays = new int[n + 3]; noOfWays[0] = 1; noOfWays[1] = 1; noOfWays[2] = 1 + 1; // Loop till \"n+1\" to compute value for \"n\" for (int i = 3; i < n + 1; i++) { noOfWays[i] = // number of ways if first run is 1 noOfWays[3 - 1] // number of ways if first run is 2 // and second run is 1 + noOfWays[3 - 3]; // Remember last 3 values noOfWays[0] = noOfWays[1]; noOfWays[1] = noOfWays[2]; noOfWays[2] = noOfWays[i]; } return noOfWays[n]; } // Driver code public static void Main(String[] args) { int n = 5; Console.WriteLine(CountWays(n)); }} // This code is contributed by umadevi9616", "e": 38029, "s": 36904, "text": null }, { "code": "<script>// Bottom up approach for// counting ways to reach a score using 1 and 2 with// consecutive 2 allowedfunction CountWays(n){ // noOfWays[i] will store count // for last 3 values before i. var noOfWays = Array(3).fill(0); noOfWays[0] = 1; noOfWays[1] = 1; noOfWays[2] = 1 + 1; // Loop till \"n+1\" to compute value for \"n\" for (var i = 3; i < n + 1; i++) { noOfWays[i] = // number of ways if first run is 1 noOfWays[3-1] // number of ways if first run is 2 // and second run is 1 + noOfWays[3-3]; // Remember last 3 values noOfWays[0] = noOfWays[1]; noOfWays[1] = noOfWays[2]; noOfWays[2] = noOfWays[i]; } return noOfWays[n];} var n = 5;document.write(CountWays(n)); // This code is contributed by shivanisinghss2110</script>", "e": 38863, "s": 38029, "text": null }, { "code": null, "e": 38865, "s": 38863, "text": "6" }, { "code": null, "e": 38877, "s": 38865, "text": "shrikanth13" }, { "code": null, "e": 38887, "s": 38877, "text": "Sach_Code" }, { "code": null, "e": 38904, "s": 38887, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 38918, "s": 38904, "text": "princiraj1992" }, { "code": null, "e": 38930, "s": 38918, "text": "29AjayKumar" }, { "code": null, "e": 38944, "s": 38930, "text": "surbhityagi15" }, { "code": null, "e": 38957, "s": 38944, "text": "SoumikMondal" }, { "code": null, "e": 38970, "s": 38957, "text": "puneetgarg80" }, { "code": null, "e": 38984, "s": 38970, "text": "GauravRajput1" }, { "code": null, "e": 39003, "s": 38984, "text": "shivanisinghss2110" }, { "code": null, "e": 39015, "s": 39003, "text": "umadevi9616" }, { "code": null, "e": 39022, "s": 39015, "text": "Oracle" }, { "code": null, "e": 39046, "s": 39022, "text": "Technical Scripter 2018" }, { "code": null, "e": 39066, "s": 39046, "text": "Dynamic Programming" }, { "code": null, "e": 39076, "s": 39066, "text": "Recursion" }, { "code": null, "e": 39083, "s": 39076, "text": "Oracle" }, { "code": null, "e": 39103, "s": 39083, "text": "Dynamic Programming" }, { "code": null, "e": 39113, "s": 39103, "text": "Recursion" }, { "code": null, "e": 39211, "s": 39113, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 39242, "s": 39211, "text": "Bellman–Ford Algorithm | DP-23" }, { "code": null, "e": 39275, "s": 39242, "text": "Floyd Warshall Algorithm | DP-16" }, { "code": null, "e": 39302, "s": 39275, "text": "Subset Sum Problem | DP-25" }, { "code": null, "e": 39337, "s": 39302, "text": "Matrix Chain Multiplication | DP-8" }, { "code": null, "e": 39375, "s": 39337, "text": "Longest Palindromic Substring | Set 1" }, { "code": null, "e": 39435, "s": 39375, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 39520, "s": 39435, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 39530, "s": 39520, "text": "Recursion" }, { "code": null, "e": 39557, "s": 39530, "text": "Program for Tower of Hanoi" } ]
Java.net.DatagramPacket class in Java - GeeksforGeeks
15 Dec, 2021 This class provides facility for connection less transfer of messages from one system to another. Each message is routed only on the basis of information contained within the packet and it may be possible for different packets to route differently. There is also no guarantee as to whether the message will be delivered or not, and they may also arrive out of order. This class provides mechanisms for creation of datagram packets for connectionless delivery using datagram socket class. Constructors : The constructors vary according to their use, i.e. for receiving or for sending the packet. The important parameters used in these constructors are- buf : This is the actual message that is to be delivered or received. Datagram packets receive or send data in stuffed in a byte array. If this is used in constructor for sending the message, than this represents the message to be delivered, when used for receiving purpose, it represents the buffer where the received message will be stored.offset : It represents the offset into the buffer array.length : It is the actual size of packet to receive. This must be less than or equal to the size of buffer array or else there will be overflow as received message wont fit into the array.InetAddress address : This is the destination to which the message is to be delivered.port : This is the port to which the message will be delivered.SocketAddress address : The information about the address and port can be represented with the help of socket address. Same function as the above two combined. buf : This is the actual message that is to be delivered or received. Datagram packets receive or send data in stuffed in a byte array. If this is used in constructor for sending the message, than this represents the message to be delivered, when used for receiving purpose, it represents the buffer where the received message will be stored. offset : It represents the offset into the buffer array. length : It is the actual size of packet to receive. This must be less than or equal to the size of buffer array or else there will be overflow as received message wont fit into the array. InetAddress address : This is the destination to which the message is to be delivered. port : This is the port to which the message will be delivered. SocketAddress address : The information about the address and port can be represented with the help of socket address. Same function as the above two combined. For sending purpose, following constructors are used : Syntax :public DatagramPacket(byte[] buf, int offset, int length, InetAddress address, int port) Parameters : buf : byte array offset : offset into the array length : length of message to deliver address : address of destination port : port number of destination Syntax :public DatagramPacket(byte[] buf, int offset, int length, SocketAddress address) Parameters : buf : byte array offset : offset into the array length : length of message to deliver address : socket address of destination Syntax :public DatagramPacket(byte[] buf, int length, InetAddress address, int port) Parameters : buf : byte array length : length of message to deliver address : address of destination port : port number of destination Syntax :public DatagramPacket(byte[] buf, int length, SocketAddress address) Parameters : buf : byte array length : length of message to deliver address : socket address of destination For receiving purpose, following constructors are used : Syntax :public DatagramPacket(byte[] buf, int offset, int length) Parameters : buf : byte array offset : offset into the array length : length of message to deliver Syntax :public DatagramPacket(byte[] buf, int length) Parameters : buf : byte array length : length of message to deliver Methods : getAddress() : Returns the IP address to which this packet is sent to or from which it was received. getAddress() : Returns the IP address to which this packet is sent to or from which it was received. Syntax :public InetAddress getAddress() getPort() : Returns the port to which this packet is sent to or from which it was received. This method is specifically used on the server from getting the port of the client who sent the request. getPort() : Returns the port to which this packet is sent to or from which it was received. This method is specifically used on the server from getting the port of the client who sent the request. Syntax : public int getPort() getData() : Returns the data contained in this packet as a byte array. The data starts from the offset specified and is of length specified. getData() : Returns the data contained in this packet as a byte array. The data starts from the offset specified and is of length specified. Syntax : public byte[] getData() getOffset() : Returns the offset specified. getOffset() : Returns the offset specified. Syntax : public int getOffset() getLength() : Returns the length of the data to send or receive getLength() : Returns the length of the data to send or receive Syntax : public int getLength() setData() : Used to set the data of this packet. setData() : Used to set the data of this packet. Syntax : public void setData(byte[] buf, int offset, int length) Parameters : buf : data buffer offset :offset into the data length : length of the data Syntax : public void setData(byte[] buf) Parameters : buf : data buffer setAddress() : Used to set the address to which this packet is sent. setAddress() : Used to set the address to which this packet is sent. Syntax : public void setAddress(InetAddress iaddr) Parameters : iaddr : InetAddress of the recipient setPort() : Set the port on which destination will receive this packet. setPort() : Set the port on which destination will receive this packet. Syntax :public void setPort(int iport) Parameters : iport : the port number setSocketAddress() : Used to set the socket address of the destination(IP address+ port number). setSocketAddress() : Used to set the socket address of the destination(IP address+ port number). Syntax : public void setSocketAddress(SocketAddress address) Parameters : address : socket address getSocketAddress() : Returns the socket address of this packet. In case it was received, return the socket address of the host machine. getSocketAddress() : Returns the socket address of this packet. In case it was received, return the socket address of the host machine. Syntax : public SocketAddress getSocketAddress() setLength() : Used to set the length for this packet. setLength() : Used to set the length for this packet. Syntax :public void setLength(int length) Parameters : length : length of the packet Java Implementation : Java //Java program to illustrate various//DatagramPacket class methodsimport java.io.IOException;import java.net.DatagramPacket;import java.net.InetAddress;import java.util.Arrays; public class datapacket{ public static void main(String[] args) throws IOException { byte ar[] = { 12, 13, 15, 16 }; byte buf[] = { 15, 16, 17, 18, 19 }; InetAddress ip = InetAddress.getByName("localhost"); // DatagramPacket for sending the data DatagramPacket dp1 = new DatagramPacket(ar, 4, ip, 1052); // setAddress() method // I have used same address as in initiation dp1.setAddress(ip); // getAddress() method System.out.println("Address : " + dp1.getAddress()); // setPort() method dp1.setPort(2525); // getPort() method System.out.println("Port : " + dp1.getPort()); // setLength() method dp1.setLength(4); // getLength() method System.out.println("Length : " + dp1.getLength()); // setData() method dp1.setData(buf); // getData() method System.out.println("Data : " + Arrays.toString(dp1.getData())); // setSocketAddress() method //dp1.setSocketAddress(address.getLocalSocketAddress()); // getSocketAddress() method System.out.println("Socket Address : " + dp1.getSocketAddress()); // getOffset() method System.out.println("Offset : " + dp1.getOffset()); }} Output : Address : localhost/127.0.0.1 Port : 2525 Length : 4 Data : [15, 16, 17, 18, 19] Socket Address : localhost/127.0.0.1:2525 Offset : 0 For a detailed implementation of a client-server program that uses datagram socket to send the actual packets over the network, please refer to – Working with UDP Datagram Sockets References : Official Java Documentation This article is contributed by Rishabh Mahrsee. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. ManasChhabra2 sumitgumber28 Java-Networking Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Interfaces in Java ArrayList in Java Initialize an ArrayList in Java Stack Class in Java Singleton Class in Java Multidimensional Arrays in Java Set in Java Multithreading in Java Collections in Java
[ { "code": null, "e": 25790, "s": 25762, "text": "\n15 Dec, 2021" }, { "code": null, "e": 26444, "s": 25790, "text": "This class provides facility for connection less transfer of messages from one system to another. Each message is routed only on the basis of information contained within the packet and it may be possible for different packets to route differently. There is also no guarantee as to whether the message will be delivered or not, and they may also arrive out of order. This class provides mechanisms for creation of datagram packets for connectionless delivery using datagram socket class. Constructors : The constructors vary according to their use, i.e. for receiving or for sending the packet. The important parameters used in these constructors are- " }, { "code": null, "e": 27339, "s": 26444, "text": "buf : This is the actual message that is to be delivered or received. Datagram packets receive or send data in stuffed in a byte array. If this is used in constructor for sending the message, than this represents the message to be delivered, when used for receiving purpose, it represents the buffer where the received message will be stored.offset : It represents the offset into the buffer array.length : It is the actual size of packet to receive. This must be less than or equal to the size of buffer array or else there will be overflow as received message wont fit into the array.InetAddress address : This is the destination to which the message is to be delivered.port : This is the port to which the message will be delivered.SocketAddress address : The information about the address and port can be represented with the help of socket address. Same function as the above two combined." }, { "code": null, "e": 27682, "s": 27339, "text": "buf : This is the actual message that is to be delivered or received. Datagram packets receive or send data in stuffed in a byte array. If this is used in constructor for sending the message, than this represents the message to be delivered, when used for receiving purpose, it represents the buffer where the received message will be stored." }, { "code": null, "e": 27739, "s": 27682, "text": "offset : It represents the offset into the buffer array." }, { "code": null, "e": 27928, "s": 27739, "text": "length : It is the actual size of packet to receive. This must be less than or equal to the size of buffer array or else there will be overflow as received message wont fit into the array." }, { "code": null, "e": 28015, "s": 27928, "text": "InetAddress address : This is the destination to which the message is to be delivered." }, { "code": null, "e": 28079, "s": 28015, "text": "port : This is the port to which the message will be delivered." }, { "code": null, "e": 28239, "s": 28079, "text": "SocketAddress address : The information about the address and port can be represented with the help of socket address. Same function as the above two combined." }, { "code": null, "e": 28296, "s": 28239, "text": "For sending purpose, following constructors are used : " }, { "code": null, "e": 28615, "s": 28296, "text": "Syntax :public DatagramPacket(byte[] buf,\n int offset,\n int length,\n InetAddress address,\n int port)\nParameters :\nbuf : byte array\noffset : offset into the array\nlength : length of message to deliver\naddress : address of destination\nport : port number of destination" }, { "code": null, "e": 28885, "s": 28615, "text": "Syntax :public DatagramPacket(byte[] buf,\n int offset,\n int length,\n SocketAddress address)\nParameters :\nbuf : byte array\noffset : offset into the array\nlength : length of message to deliver\naddress : socket address of destination" }, { "code": null, "e": 29147, "s": 28885, "text": "Syntax :public DatagramPacket(byte[] buf,\n int length,\n InetAddress address,\n int port)\nParameters :\nbuf : byte array\nlength : length of message to deliver\naddress : address of destination\nport : port number of destination" }, { "code": null, "e": 29360, "s": 29147, "text": "Syntax :public DatagramPacket(byte[] buf,\n int length,\n SocketAddress address)\nParameters :\nbuf : byte array\nlength : length of message to deliver\naddress : socket address of destination" }, { "code": null, "e": 29419, "s": 29360, "text": "For receiving purpose, following constructors are used : " }, { "code": null, "e": 29612, "s": 29419, "text": "Syntax :public DatagramPacket(byte[] buf,\n int offset,\n int length)\nParameters :\nbuf : byte array\noffset : offset into the array\nlength : length of message to deliver" }, { "code": null, "e": 29748, "s": 29612, "text": "Syntax :public DatagramPacket(byte[] buf,\n int length)\nParameters :\nbuf : byte array\nlength : length of message to deliver" }, { "code": null, "e": 29760, "s": 29748, "text": "Methods : " }, { "code": null, "e": 29863, "s": 29760, "text": "getAddress() : Returns the IP address to which this packet is sent to or from which it was received. " }, { "code": null, "e": 29966, "s": 29863, "text": "getAddress() : Returns the IP address to which this packet is sent to or from which it was received. " }, { "code": null, "e": 30006, "s": 29966, "text": "Syntax :public InetAddress getAddress()" }, { "code": null, "e": 30205, "s": 30006, "text": "getPort() : Returns the port to which this packet is sent to or from which it was received. This method is specifically used on the server from getting the port of the client who sent the request. " }, { "code": null, "e": 30404, "s": 30205, "text": "getPort() : Returns the port to which this packet is sent to or from which it was received. This method is specifically used on the server from getting the port of the client who sent the request. " }, { "code": null, "e": 30434, "s": 30404, "text": "Syntax : public int getPort()" }, { "code": null, "e": 30577, "s": 30434, "text": "getData() : Returns the data contained in this packet as a byte array. The data starts from the offset specified and is of length specified. " }, { "code": null, "e": 30720, "s": 30577, "text": "getData() : Returns the data contained in this packet as a byte array. The data starts from the offset specified and is of length specified. " }, { "code": null, "e": 30753, "s": 30720, "text": "Syntax : public byte[] getData()" }, { "code": null, "e": 30799, "s": 30753, "text": "getOffset() : Returns the offset specified. " }, { "code": null, "e": 30845, "s": 30799, "text": "getOffset() : Returns the offset specified. " }, { "code": null, "e": 30877, "s": 30845, "text": "Syntax : public int getOffset()" }, { "code": null, "e": 30943, "s": 30877, "text": "getLength() : Returns the length of the data to send or receive " }, { "code": null, "e": 31009, "s": 30943, "text": "getLength() : Returns the length of the data to send or receive " }, { "code": null, "e": 31041, "s": 31009, "text": "Syntax : public int getLength()" }, { "code": null, "e": 31092, "s": 31041, "text": "setData() : Used to set the data of this packet. " }, { "code": null, "e": 31143, "s": 31092, "text": "setData() : Used to set the data of this packet. " }, { "code": null, "e": 31318, "s": 31143, "text": "Syntax : public void setData(byte[] buf,\n int offset,\n int length)\nParameters :\nbuf : data buffer\noffset :offset into the data\nlength : length of the data" }, { "code": null, "e": 31390, "s": 31318, "text": "Syntax : public void setData(byte[] buf)\nParameters :\nbuf : data buffer" }, { "code": null, "e": 31461, "s": 31390, "text": "setAddress() : Used to set the address to which this packet is sent. " }, { "code": null, "e": 31532, "s": 31461, "text": "setAddress() : Used to set the address to which this packet is sent. " }, { "code": null, "e": 31634, "s": 31532, "text": "Syntax : public void setAddress(InetAddress iaddr)\nParameters : \niaddr : InetAddress of the recipient" }, { "code": null, "e": 31708, "s": 31634, "text": "setPort() : Set the port on which destination will receive this packet. " }, { "code": null, "e": 31782, "s": 31708, "text": "setPort() : Set the port on which destination will receive this packet. " }, { "code": null, "e": 31859, "s": 31782, "text": "Syntax :public void setPort(int iport)\nParameters : \niport : the port number" }, { "code": null, "e": 31958, "s": 31859, "text": "setSocketAddress() : Used to set the socket address of the destination(IP address+ port number). " }, { "code": null, "e": 32057, "s": 31958, "text": "setSocketAddress() : Used to set the socket address of the destination(IP address+ port number). " }, { "code": null, "e": 32156, "s": 32057, "text": "Syntax : public void setSocketAddress(SocketAddress address)\nParameters :\naddress : socket address" }, { "code": null, "e": 32294, "s": 32156, "text": "getSocketAddress() : Returns the socket address of this packet. In case it was received, return the socket address of the host machine. " }, { "code": null, "e": 32432, "s": 32294, "text": "getSocketAddress() : Returns the socket address of this packet. In case it was received, return the socket address of the host machine. " }, { "code": null, "e": 32481, "s": 32432, "text": "Syntax : public SocketAddress getSocketAddress()" }, { "code": null, "e": 32537, "s": 32481, "text": "setLength() : Used to set the length for this packet. " }, { "code": null, "e": 32593, "s": 32537, "text": "setLength() : Used to set the length for this packet. " }, { "code": null, "e": 32678, "s": 32593, "text": "Syntax :public void setLength(int length)\nParameters :\nlength : length of the packet" }, { "code": null, "e": 32702, "s": 32678, "text": "Java Implementation : " }, { "code": null, "e": 32707, "s": 32702, "text": "Java" }, { "code": "//Java program to illustrate various//DatagramPacket class methodsimport java.io.IOException;import java.net.DatagramPacket;import java.net.InetAddress;import java.util.Arrays; public class datapacket{ public static void main(String[] args) throws IOException { byte ar[] = { 12, 13, 15, 16 }; byte buf[] = { 15, 16, 17, 18, 19 }; InetAddress ip = InetAddress.getByName(\"localhost\"); // DatagramPacket for sending the data DatagramPacket dp1 = new DatagramPacket(ar, 4, ip, 1052); // setAddress() method // I have used same address as in initiation dp1.setAddress(ip); // getAddress() method System.out.println(\"Address : \" + dp1.getAddress()); // setPort() method dp1.setPort(2525); // getPort() method System.out.println(\"Port : \" + dp1.getPort()); // setLength() method dp1.setLength(4); // getLength() method System.out.println(\"Length : \" + dp1.getLength()); // setData() method dp1.setData(buf); // getData() method System.out.println(\"Data : \" + Arrays.toString(dp1.getData())); // setSocketAddress() method //dp1.setSocketAddress(address.getLocalSocketAddress()); // getSocketAddress() method System.out.println(\"Socket Address : \" + dp1.getSocketAddress()); // getOffset() method System.out.println(\"Offset : \" + dp1.getOffset()); }}", "e": 34241, "s": 32707, "text": null }, { "code": null, "e": 34252, "s": 34241, "text": "Output : " }, { "code": null, "e": 34386, "s": 34252, "text": "Address : localhost/127.0.0.1\nPort : 2525\nLength : 4\nData : [15, 16, 17, 18, 19]\nSocket Address : localhost/127.0.0.1:2525\nOffset : 0" }, { "code": null, "e": 35031, "s": 34386, "text": "For a detailed implementation of a client-server program that uses datagram socket to send the actual packets over the network, please refer to – Working with UDP Datagram Sockets References : Official Java Documentation This article is contributed by Rishabh Mahrsee. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 35045, "s": 35031, "text": "ManasChhabra2" }, { "code": null, "e": 35059, "s": 35045, "text": "sumitgumber28" }, { "code": null, "e": 35075, "s": 35059, "text": "Java-Networking" }, { "code": null, "e": 35080, "s": 35075, "text": "Java" }, { "code": null, "e": 35085, "s": 35080, "text": "Java" }, { "code": null, "e": 35183, "s": 35085, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35198, "s": 35183, "text": "Stream In Java" }, { "code": null, "e": 35217, "s": 35198, "text": "Interfaces in Java" }, { "code": null, "e": 35235, "s": 35217, "text": "ArrayList in Java" }, { "code": null, "e": 35267, "s": 35235, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 35287, "s": 35267, "text": "Stack Class in Java" }, { "code": null, "e": 35311, "s": 35287, "text": "Singleton Class in Java" }, { "code": null, "e": 35343, "s": 35311, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 35355, "s": 35343, "text": "Set in Java" }, { "code": null, "e": 35378, "s": 35355, "text": "Multithreading in Java" } ]
What is the difference between 'String' and 'string' in TypeScript ? - GeeksforGeeks
07 Sep, 2021 Unlike JavaScript, TypeScript uses static typing, i.e. it specifies what kind of data the variable will be able to hold. Since TypeScript is a superscript of JavaScript, it also holds a distinction between a string and String. The usage of a string object in JS (or TS for that matter) is very minimal. String objects have the feature of adding a property to an object. In general, the string(with a small ‘s’) denotes a primitive whereas String(with an uppercase ‘S’) denotes an object. JavaScript supports five types of primitives and string is one of them. You will get the idea of Variables and Datatypes in JavaScript from linked article. Primitive string: The string(with a small ‘s’) indicates a primitive, primitives are values that hold no properties. String literals and a few strings returned from a string function call can be classified as a primitive(string). A primitive string can be converted to an object by using a wrapper. Syntax: var test1 = "A TypeScript variable of type 'string'"; Object String: The object is an accumulation of different properties. An object can call numerous methods corresponding to it. Syntax: var test2 = new String('another test'); Example: Javascript <script>let a = new String("An object !");let b = "A literal ! haha";console.log(typeof(a));console.log(typeof(b));</script> Output: object string In the above code, we see the type of variable “a” is an object whereas “b” is a primitive (string). It shows that a string literal is primitive. The important thing to note here is that we are able to use a method for “b” even though it is not an object. This is because JavaScript changes a primitive to its object when a method is called through it. This happens for a very small amount of time just to execute the method and returns back to its primitive self. Then why question may arrive why we will need String object! Need of String Object: When we use the keyword new, TS creates a new object every time unlike when you use a primitive type, if you have the same value for the variables then they point to the same memory. Refer to the below example. Example 1: The below example will shows how a1 and b1 are shown to be equal since they are literals having the same value, whereas a2 and b2 are shown to be different because we used the keyword new which creates two different objects. Javascript <script>let a1 = "Hello World";let b1 = "Hello World";console.log(a1 != b1);let a2 = new String("Hello World");let b2 = new String("Hello World");console.log(a2 != b2);</script> Output: false true Example 2: The use of eval differs from primitive string to object. Refer to the following example. In this example, we will see how string and String differ when using eval() method. The string primitive is directly evaluated that is 25 * 25 gives you 525 as the output whereas the object will give the output as itself since eval() returns the argument unchanged if it is not a primitive string. We can also evaluate the object by changing it to a primitive string using toString() method. Javascript <script>var a3 = '21 * 25' ;console.log(eval(a3));var b3 = new String("1 + 1");console.log(eval(b3));console.log(eval(b3.toString()));</script> Output: 525 String { "1 + 1" } 2 As we have learned above the string object can hold properties. We can use String objects to hold an additional value in the properties. Even though this not commonly used, it is still a feature of JS. var primitive = 'hello'; var object = new String('HELLO'); primitive.prop = 'world';//Invalid object.prop = 'WORLD';//Valid Difference between string and String: chhabradhanvi JavaScript-Misc Picked TypeScript JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript How to Open URL in New Tab using JavaScript ? Node.js | fs.writeFileSync() Method Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript Top 10 Projects For Beginners To Practice HTML and CSS Skills What is REST API in Node.js ?
[ { "code": null, "e": 25727, "s": 25699, "text": "\n07 Sep, 2021" }, { "code": null, "e": 26098, "s": 25727, "text": "Unlike JavaScript, TypeScript uses static typing, i.e. it specifies what kind of data the variable will be able to hold. Since TypeScript is a superscript of JavaScript, it also holds a distinction between a string and String. The usage of a string object in JS (or TS for that matter) is very minimal. String objects have the feature of adding a property to an object. " }, { "code": null, "e": 26372, "s": 26098, "text": "In general, the string(with a small ‘s’) denotes a primitive whereas String(with an uppercase ‘S’) denotes an object. JavaScript supports five types of primitives and string is one of them. You will get the idea of Variables and Datatypes in JavaScript from linked article." }, { "code": null, "e": 26671, "s": 26372, "text": "Primitive string: The string(with a small ‘s’) indicates a primitive, primitives are values that hold no properties. String literals and a few strings returned from a string function call can be classified as a primitive(string). A primitive string can be converted to an object by using a wrapper." }, { "code": null, "e": 26680, "s": 26671, "text": "Syntax: " }, { "code": null, "e": 26734, "s": 26680, "text": "var test1 = \"A TypeScript variable of type 'string'\";" }, { "code": null, "e": 26861, "s": 26734, "text": "Object String: The object is an accumulation of different properties. An object can call numerous methods corresponding to it." }, { "code": null, "e": 26871, "s": 26861, "text": "Syntax: " }, { "code": null, "e": 26911, "s": 26871, "text": "var test2 = new String('another test');" }, { "code": null, "e": 26921, "s": 26911, "text": "Example: " }, { "code": null, "e": 26932, "s": 26921, "text": "Javascript" }, { "code": "<script>let a = new String(\"An object !\");let b = \"A literal ! haha\";console.log(typeof(a));console.log(typeof(b));</script>", "e": 27057, "s": 26932, "text": null }, { "code": null, "e": 27066, "s": 27057, "text": "Output: " }, { "code": null, "e": 27082, "s": 27066, "text": "object \nstring " }, { "code": null, "e": 27609, "s": 27082, "text": "In the above code, we see the type of variable “a” is an object whereas “b” is a primitive (string). It shows that a string literal is primitive. The important thing to note here is that we are able to use a method for “b” even though it is not an object. This is because JavaScript changes a primitive to its object when a method is called through it. This happens for a very small amount of time just to execute the method and returns back to its primitive self. Then why question may arrive why we will need String object! " }, { "code": null, "e": 27844, "s": 27609, "text": "Need of String Object: When we use the keyword new, TS creates a new object every time unlike when you use a primitive type, if you have the same value for the variables then they point to the same memory. Refer to the below example. " }, { "code": null, "e": 28081, "s": 27844, "text": "Example 1: The below example will shows how a1 and b1 are shown to be equal since they are literals having the same value, whereas a2 and b2 are shown to be different because we used the keyword new which creates two different objects. " }, { "code": null, "e": 28092, "s": 28081, "text": "Javascript" }, { "code": "<script>let a1 = \"Hello World\";let b1 = \"Hello World\";console.log(a1 != b1);let a2 = new String(\"Hello World\");let b2 = new String(\"Hello World\");console.log(a2 != b2);</script>", "e": 28270, "s": 28092, "text": null }, { "code": null, "e": 28279, "s": 28270, "text": "Output: " }, { "code": null, "e": 28290, "s": 28279, "text": "false\ntrue" }, { "code": null, "e": 28782, "s": 28290, "text": "Example 2: The use of eval differs from primitive string to object. Refer to the following example. In this example, we will see how string and String differ when using eval() method. The string primitive is directly evaluated that is 25 * 25 gives you 525 as the output whereas the object will give the output as itself since eval() returns the argument unchanged if it is not a primitive string. We can also evaluate the object by changing it to a primitive string using toString() method." }, { "code": null, "e": 28793, "s": 28782, "text": "Javascript" }, { "code": "<script>var a3 = '21 * 25' ;console.log(eval(a3));var b3 = new String(\"1 + 1\");console.log(eval(b3));console.log(eval(b3.toString()));</script>", "e": 28937, "s": 28793, "text": null }, { "code": null, "e": 28946, "s": 28937, "text": "Output: " }, { "code": null, "e": 28972, "s": 28946, "text": "525 \nString { \"1 + 1\" }\n2" }, { "code": null, "e": 29175, "s": 28972, "text": "As we have learned above the string object can hold properties. We can use String objects to hold an additional value in the properties. Even though this not commonly used, it is still a feature of JS. " }, { "code": null, "e": 29299, "s": 29175, "text": "var primitive = 'hello';\nvar object = new String('HELLO');\nprimitive.prop = 'world';//Invalid\nobject.prop = 'WORLD';//Valid" }, { "code": null, "e": 29337, "s": 29299, "text": "Difference between string and String:" }, { "code": null, "e": 29353, "s": 29339, "text": "chhabradhanvi" }, { "code": null, "e": 29369, "s": 29353, "text": "JavaScript-Misc" }, { "code": null, "e": 29376, "s": 29369, "text": "Picked" }, { "code": null, "e": 29387, "s": 29376, "text": "TypeScript" }, { "code": null, "e": 29398, "s": 29387, "text": "JavaScript" }, { "code": null, "e": 29415, "s": 29398, "text": "Web Technologies" }, { "code": null, "e": 29442, "s": 29415, "text": "Web technologies Questions" }, { "code": null, "e": 29540, "s": 29442, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29580, "s": 29540, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29625, "s": 29580, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 29686, "s": 29625, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 29732, "s": 29686, "text": "How to Open URL in New Tab using JavaScript ?" }, { "code": null, "e": 29768, "s": 29732, "text": "Node.js | fs.writeFileSync() Method" }, { "code": null, "e": 29808, "s": 29768, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29841, "s": 29808, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29886, "s": 29841, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 29948, "s": 29886, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
Java Program to Get Elements of a LinkedList - GeeksforGeeks
27 Nov, 2020 Linked List is a linear data structure, in which the elements are not stored at the contiguous memory locations. Here, the task is to get the elements of a LinkedList. 1. We can use get(int variable) method to access an element from a specific index of LinkedList: In the given example, we have used the get(i) method. Here, the method returns the element which is at the i th index. Syntax: LinkedList.get(int index) Parameters: The parameter index is of integer data type that specifies the position or index of the element to be fetched from the LinkedList. Return Value: The method returns the element present at the position specified by the parameter index. Java // Java program to get the elements of Linkedlist import java.io.*;import java.util.LinkedList;class GFG { public static void main(String[] args) { // Creating LinkedList LinkedList<String> gfg = new LinkedList<String>(); // Adding values gfg.add("GEEKS"); gfg.add("FOR"); gfg.add("GEEKS"); System.out.println("LinkedList Elements : "); for (int i = 0; i < gfg.size(); i++) { // get(i) returns element present at index i System.out.println("Element at index " + i + " is: " + gfg.get(i)); } }} LinkedList Elements : Element at index 0 is: GEEKS Element at index 1 is: FOR Element at index 2 is: GEEKS 2. We can use the iterator() method To use this method we have to import java.util.Iterator package. In this method, we can iterate over the LinkedList and then extract the element at the given index accordingly. Java // Java program to iterate over linkedlist// to extract elements of linkedlist import java.io.*;import java.util.LinkedList;import java.util.Iterator;class GFG { public static void main(String[] args) { LinkedList<String> gfg = new LinkedList<String>(); // Adding elements gfg.add("GEEKS"); gfg.add("FOR"); gfg.add("GEEKS"); // Create an object of Iterator Iterator<String> i = gfg.iterator(); System.out.print( "The elements of the input LinkedList: \n"); int j = 0; // has.next() returns true if there is a next // element while (i.hasNext()) { System.out.print("The element at the index " + j + " "); // next() returns the next element String str = i.next(); System.out.print(str); System.out.print(" \n"); ++j; } }} The elements of the input LinkedList: The element at the index 0 GEEKS The element at the index 1 FOR The element at the index 2 GEEKS 3. We can use ListIterator() method. ListIterator() is a subinterface of Iterator() method. It provides us with the function to access the elements of a list. It is bidirectional that means it allows us to iterate elements of a list in the both the direction. To use this method we have to import java.util.ListIterator. Java // Java program to iterate over the// linkedlist using listIterator() import java.io.*;import java.util.LinkedList;import java.util.ListIterator; class GFG { public static void main(String[] args) { LinkedList<String> gfg = new LinkedList<String>(); // Adding elements gfg.add("GEEKS"); gfg.add("FOR"); gfg.add("GEEKS"); // Create an object of ListIterator ListIterator<String> li = gfg.listIterator(); System.out.print( "The elements of the LinkedList: \n"); // hasNext() returns true if there is next element int j = 0; while (li.hasNext()) { // next() returns the next element System.out.print("The element at the index " + j + " "); System.out.print(li.next()); System.out.print("\n"); ++j; } --j; // Now to show that ListIterator() can traverse in // both the direction System.out.print( "\nThe elements of the LinkedList in Reverse order: \n"); // hasprevious() checks if there is a previous // element while (li.hasPrevious()) { System.out.print("The element at the index " + j + " "); // previous() returns the previous element System.out.print(li.previous()); System.out.print("\n"); --j; } }} The elements of the LinkedList: The element at the index 0 GEEKS The element at the index 1 FOR The element at the index 2 GEEKS The elements of the LinkedList in Reverse order: The element at the index 2 GEEKS The element at the index 1 FOR The element at the index 0 GEEKS java-LinkedList Technical Scripter 2020 Java Java Programs Technical Scripter Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Constructors in Java Exceptions in Java Functional Interfaces in Java Different ways of Reading a text file in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class How to Iterate HashMap in Java? Program to print ASCII Value of a character
[ { "code": null, "e": 25225, "s": 25197, "text": "\n27 Nov, 2020" }, { "code": null, "e": 25393, "s": 25225, "text": "Linked List is a linear data structure, in which the elements are not stored at the contiguous memory locations. Here, the task is to get the elements of a LinkedList." }, { "code": null, "e": 25490, "s": 25393, "text": "1. We can use get(int variable) method to access an element from a specific index of LinkedList:" }, { "code": null, "e": 25609, "s": 25490, "text": "In the given example, we have used the get(i) method. Here, the method returns the element which is at the i th index." }, { "code": null, "e": 25617, "s": 25609, "text": "Syntax:" }, { "code": null, "e": 25643, "s": 25617, "text": "LinkedList.get(int index)" }, { "code": null, "e": 25786, "s": 25643, "text": "Parameters: The parameter index is of integer data type that specifies the position or index of the element to be fetched from the LinkedList." }, { "code": null, "e": 25889, "s": 25786, "text": "Return Value: The method returns the element present at the position specified by the parameter index." }, { "code": null, "e": 25894, "s": 25889, "text": "Java" }, { "code": "// Java program to get the elements of Linkedlist import java.io.*;import java.util.LinkedList;class GFG { public static void main(String[] args) { // Creating LinkedList LinkedList<String> gfg = new LinkedList<String>(); // Adding values gfg.add(\"GEEKS\"); gfg.add(\"FOR\"); gfg.add(\"GEEKS\"); System.out.println(\"LinkedList Elements : \"); for (int i = 0; i < gfg.size(); i++) { // get(i) returns element present at index i System.out.println(\"Element at index \" + i + \" is: \" + gfg.get(i)); } }}", "e": 26523, "s": 25894, "text": null }, { "code": null, "e": 26631, "s": 26523, "text": "LinkedList Elements : \nElement at index 0 is: GEEKS\nElement at index 1 is: FOR\nElement at index 2 is: GEEKS" }, { "code": null, "e": 26667, "s": 26631, "text": "2. We can use the iterator() method" }, { "code": null, "e": 26732, "s": 26667, "text": "To use this method we have to import java.util.Iterator package." }, { "code": null, "e": 26844, "s": 26732, "text": "In this method, we can iterate over the LinkedList and then extract the element at the given index accordingly." }, { "code": null, "e": 26849, "s": 26844, "text": "Java" }, { "code": "// Java program to iterate over linkedlist// to extract elements of linkedlist import java.io.*;import java.util.LinkedList;import java.util.Iterator;class GFG { public static void main(String[] args) { LinkedList<String> gfg = new LinkedList<String>(); // Adding elements gfg.add(\"GEEKS\"); gfg.add(\"FOR\"); gfg.add(\"GEEKS\"); // Create an object of Iterator Iterator<String> i = gfg.iterator(); System.out.print( \"The elements of the input LinkedList: \\n\"); int j = 0; // has.next() returns true if there is a next // element while (i.hasNext()) { System.out.print(\"The element at the index \" + j + \" \"); // next() returns the next element String str = i.next(); System.out.print(str); System.out.print(\" \\n\"); ++j; } }}", "e": 27795, "s": 26849, "text": null }, { "code": null, "e": 27933, "s": 27795, "text": "The elements of the input LinkedList: \nThe element at the index 0 GEEKS \nThe element at the index 1 FOR \nThe element at the index 2 GEEKS" }, { "code": null, "e": 27970, "s": 27933, "text": "3. We can use ListIterator() method." }, { "code": null, "e": 28025, "s": 27970, "text": "ListIterator() is a subinterface of Iterator() method." }, { "code": null, "e": 28092, "s": 28025, "text": "It provides us with the function to access the elements of a list." }, { "code": null, "e": 28193, "s": 28092, "text": "It is bidirectional that means it allows us to iterate elements of a list in the both the direction." }, { "code": null, "e": 28254, "s": 28193, "text": "To use this method we have to import java.util.ListIterator." }, { "code": null, "e": 28259, "s": 28254, "text": "Java" }, { "code": "// Java program to iterate over the// linkedlist using listIterator() import java.io.*;import java.util.LinkedList;import java.util.ListIterator; class GFG { public static void main(String[] args) { LinkedList<String> gfg = new LinkedList<String>(); // Adding elements gfg.add(\"GEEKS\"); gfg.add(\"FOR\"); gfg.add(\"GEEKS\"); // Create an object of ListIterator ListIterator<String> li = gfg.listIterator(); System.out.print( \"The elements of the LinkedList: \\n\"); // hasNext() returns true if there is next element int j = 0; while (li.hasNext()) { // next() returns the next element System.out.print(\"The element at the index \" + j + \" \"); System.out.print(li.next()); System.out.print(\"\\n\"); ++j; } --j; // Now to show that ListIterator() can traverse in // both the direction System.out.print( \"\\nThe elements of the LinkedList in Reverse order: \\n\"); // hasprevious() checks if there is a previous // element while (li.hasPrevious()) { System.out.print(\"The element at the index \" + j + \" \"); // previous() returns the previous element System.out.print(li.previous()); System.out.print(\"\\n\"); --j; } }}", "e": 29731, "s": 28259, "text": null }, { "code": null, "e": 30010, "s": 29731, "text": "The elements of the LinkedList: \nThe element at the index 0 GEEKS\nThe element at the index 1 FOR\nThe element at the index 2 GEEKS\n\nThe elements of the LinkedList in Reverse order: \nThe element at the index 2 GEEKS\nThe element at the index 1 FOR\nThe element at the index 0 GEEKS\n" }, { "code": null, "e": 30026, "s": 30010, "text": "java-LinkedList" }, { "code": null, "e": 30050, "s": 30026, "text": "Technical Scripter 2020" }, { "code": null, "e": 30055, "s": 30050, "text": "Java" }, { "code": null, "e": 30069, "s": 30055, "text": "Java Programs" }, { "code": null, "e": 30088, "s": 30069, "text": "Technical Scripter" }, { "code": null, "e": 30093, "s": 30088, "text": "Java" }, { "code": null, "e": 30191, "s": 30093, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30206, "s": 30191, "text": "Stream In Java" }, { "code": null, "e": 30227, "s": 30206, "text": "Constructors in Java" }, { "code": null, "e": 30246, "s": 30227, "text": "Exceptions in Java" }, { "code": null, "e": 30276, "s": 30246, "text": "Functional Interfaces in Java" }, { "code": null, "e": 30322, "s": 30276, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 30348, "s": 30322, "text": "Java Programming Examples" }, { "code": null, "e": 30382, "s": 30348, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 30429, "s": 30382, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 30461, "s": 30429, "text": "How to Iterate HashMap in Java?" } ]
grep command in Unix/Linux - GeeksforGeeks
28 Apr, 2022 The grep filter searches a file for a particular pattern of characters, and displays all lines that contain that pattern. The pattern that is searched in the file is referred to as the regular expression (grep stands for global search for regular expression and print out). Syntax: grep [options] pattern [files] Options Description -c : This prints only a count of the lines that match a pattern -h : Display the matched lines, but do not display the filenames. -i : Ignores, case for matching -l : Displays list of a filenames only. -n : Display the matched lines and their line numbers. -v : This prints out all the lines that do not matches the pattern -e exp : Specifies expression with this option. Can use multiple times. -f file : Takes patterns from file, one per line. -E : Treats pattern as an extended regular expression (ERE) -w : Match whole word -o : Print only the matched parts of a matching line, with each such part on a separate output line. -A n : Prints searched line and nlines after the result. -B n : Prints searched line and n line before the result. -C n : Prints searched line and n lines after before the result. Sample Commands Consider the below file as an input. $cat > geekfile.txt unix is great os. unix is opensource. unix is free os. learn operating system. Unix linux which one you choose. uNix is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful. 1. Case insensitive search : The -i option enables to search for a string case insensitively in the given file. It matches the words like “UNIX”, “Unix”, “unix”. $grep -i "UNix" geekfile.txt Output: unix is great os. unix is opensource. unix is free os. Unix linux which one you choose. uNix is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful. 2. Displaying the count of number of matches : We can find the number of lines that matches the given string/pattern $grep -c "unix" geekfile.txt Output: 2 3. Display the file names that matches the pattern : We can just display the files that contains the given string/pattern. $grep -l "unix" * or $grep -l "unix" f1.txt f2.txt f3.xt f4.txt Output: geekfile.txt 4. Checking for the whole words in a file : By default, grep matches the given string/pattern even if it is found as a substring in a file. The -w option to grep makes it match only the whole words. $ grep -w "unix" geekfile.txt Output: unix is great os. unix is opensource. unix is free os. uNix is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful. 5. Displaying only the matched pattern : By default, grep displays the entire line which has the matched string. We can make the grep to display only the matched string by using the -o option. $ grep -o "unix" geekfile.txt Output: unix unix unix unix unix unix 6. Show line number while displaying the output using grep -n : To show the line number of file with the line matched. $ grep -n "unix" geekfile.txt Output: 1:unix is great os. unix is opensource. unix is free os. 4:uNix is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful. 7. Inverting the pattern match : You can display the lines that are not matched with the specified search string pattern using the -v option. $ grep -v "unix" geekfile.txt Output: learn operating system. Unix linux which one you choose. 8. Matching the lines that start with a string : The ^ regular expression pattern specifies the start of a line. This can be used in grep to match the lines which start with the given string or pattern. $ grep "^unix" geekfile.txt Output: unix is great os. unix is opensource. unix is free os. 9. Matching the lines that end with a string : The $ regular expression pattern specifies the end of a line. This can be used in grep to match the lines which end with the given string or pattern. $ grep "os$" geekfile.txt 10.Specifies expression with -e option. Can use multiple times : $grep –e "Agarwal" –e "Aggarwal" –e "Agrawal" geekfile.txt 11. -f file option Takes patterns from file, one per line. $cat pattern.txt Agarwal Aggarwal Agrawal $grep –f pattern.txt geekfile.txt 12. Print n specific lines from a file: -A prints the searched line and n lines after the result, -B prints the searched line and n lines before the result, and -C prints the searched line and n lines after and before the result. Syntax: $grep -A[NumberOfLines(n)] [search] [file] $grep -B[NumberOfLines(n)] [search] [file] $grep -C[NumberOfLines(n)] [search] [file] Example: $grep -A1 learn geekfile.txt Output: learn operating system. Unix linux which one you choose. -- uNix is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful. (Prints the searched line along with the next n lines (here n = 1 (A1).) (Will print each and every occurrence of the found line, separating each output by --) (Output pattern remains the same for -B and -C respectively) Unix linux which one you choose. -- uNix is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful. Unix linux which one you choose. -- uNix is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful. 13. Search recursively for a pattern in the directory: -R prints the searched pattern in the given directory recursively in all the files. Syntax $grep -R [Search] [directory] Example : $grep -iR geeks /home/geeks Output: ./geeks2.txt:Well Hello Geeks ./geeks1.txt:I am a big time geek ---------------------------------- -i to search for a string case insensitively -R to recursively check all the files in the directory. This article is contributed by Akshay Rajput. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks’ main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. yashbeersingh42 saurabh1990aror anikaseth98 meetgor avi122186 simmytarika5 linux-command Linux-misc-commands Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. tar command in Linux with examples Conditional Statements | Shell Script UDP Server-Client implementation in C Tail command in Linux with examples Cat command in Linux with examples touch command in Linux with Examples echo command in Linux with Examples Compiling with g++ scp command in Linux with Examples ps command in Linux with Examples
[ { "code": null, "e": 25201, "s": 25173, "text": "\n28 Apr, 2022" }, { "code": null, "e": 25485, "s": 25201, "text": "The grep filter searches a file for a particular pattern of characters, and displays all lines that contain that pattern. The pattern that is searched in the file is referred to as the regular expression (grep stands for global search for regular expression and print out). Syntax: " }, { "code": null, "e": 25516, "s": 25485, "text": "grep [options] pattern [files]" }, { "code": null, "e": 26349, "s": 25518, "text": "Options Description\n-c : This prints only a count of the lines that match a pattern\n-h : Display the matched lines, but do not display the filenames.\n-i : Ignores, case for matching\n-l : Displays list of a filenames only.\n-n : Display the matched lines and their line numbers.\n-v : This prints out all the lines that do not matches the pattern\n-e exp : Specifies expression with this option. Can use multiple times.\n-f file : Takes patterns from file, one per line.\n-E : Treats pattern as an extended regular expression (ERE)\n-w : Match whole word\n-o : Print only the matched parts of a matching line,\n with each such part on a separate output line.\n\n-A n : Prints searched line and nlines after the result.\n-B n : Prints searched line and n line before the result.\n-C n : Prints searched line and n lines after before the result." }, { "code": null, "e": 26367, "s": 26351, "text": "Sample Commands" }, { "code": null, "e": 26406, "s": 26367, "text": "Consider the below file as an input. " }, { "code": null, "e": 26426, "s": 26406, "text": "$cat > geekfile.txt" }, { "code": null, "e": 26617, "s": 26428, "text": "unix is great os. unix is opensource. unix is free os.\nlearn operating system.\nUnix linux which one you choose.\nuNix is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful." }, { "code": null, "e": 26781, "s": 26617, "text": "1. Case insensitive search : The -i option enables to search for a string case insensitively in the given file. It matches the words like “UNIX”, “Unix”, “unix”. " }, { "code": null, "e": 26810, "s": 26781, "text": "$grep -i \"UNix\" geekfile.txt" }, { "code": null, "e": 26820, "s": 26810, "text": "Output: " }, { "code": null, "e": 26985, "s": 26820, "text": "unix is great os. unix is opensource. unix is free os.\nUnix linux which one you choose.\nuNix is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful." }, { "code": null, "e": 27104, "s": 26985, "text": "2. Displaying the count of number of matches : We can find the number of lines that matches the given string/pattern " }, { "code": null, "e": 27133, "s": 27104, "text": "$grep -c \"unix\" geekfile.txt" }, { "code": null, "e": 27143, "s": 27133, "text": "Output: " }, { "code": null, "e": 27145, "s": 27143, "text": "2" }, { "code": null, "e": 27270, "s": 27145, "text": "3. Display the file names that matches the pattern : We can just display the files that contains the given string/pattern. " }, { "code": null, "e": 27337, "s": 27270, "text": "$grep -l \"unix\" *\n\nor\n \n$grep -l \"unix\" f1.txt f2.txt f3.xt f4.txt" }, { "code": null, "e": 27347, "s": 27337, "text": "Output: " }, { "code": null, "e": 27360, "s": 27347, "text": "geekfile.txt" }, { "code": null, "e": 27561, "s": 27360, "text": "4. Checking for the whole words in a file : By default, grep matches the given string/pattern even if it is found as a substring in a file. The -w option to grep makes it match only the whole words. " }, { "code": null, "e": 27591, "s": 27561, "text": "$ grep -w \"unix\" geekfile.txt" }, { "code": null, "e": 27601, "s": 27591, "text": "Output: " }, { "code": null, "e": 27733, "s": 27601, "text": "unix is great os. unix is opensource. unix is free os.\nuNix is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful." }, { "code": null, "e": 27928, "s": 27733, "text": "5. Displaying only the matched pattern : By default, grep displays the entire line which has the matched string. We can make the grep to display only the matched string by using the -o option. " }, { "code": null, "e": 27958, "s": 27928, "text": "$ grep -o \"unix\" geekfile.txt" }, { "code": null, "e": 27968, "s": 27958, "text": "Output: " }, { "code": null, "e": 27998, "s": 27968, "text": "unix\nunix\nunix\nunix\nunix\nunix" }, { "code": null, "e": 28119, "s": 27998, "text": "6. Show line number while displaying the output using grep -n : To show the line number of file with the line matched. " }, { "code": null, "e": 28149, "s": 28119, "text": "$ grep -n \"unix\" geekfile.txt" }, { "code": null, "e": 28159, "s": 28149, "text": "Output: " }, { "code": null, "e": 28295, "s": 28159, "text": "1:unix is great os. unix is opensource. unix is free os.\n4:uNix is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful." }, { "code": null, "e": 28439, "s": 28295, "text": "7. Inverting the pattern match : You can display the lines that are not matched with the specified search string pattern using the -v option. " }, { "code": null, "e": 28469, "s": 28439, "text": "$ grep -v \"unix\" geekfile.txt" }, { "code": null, "e": 28479, "s": 28469, "text": "Output: " }, { "code": null, "e": 28536, "s": 28479, "text": "learn operating system.\nUnix linux which one you choose." }, { "code": null, "e": 28741, "s": 28536, "text": "8. Matching the lines that start with a string : The ^ regular expression pattern specifies the start of a line. This can be used in grep to match the lines which start with the given string or pattern. " }, { "code": null, "e": 28769, "s": 28741, "text": "$ grep \"^unix\" geekfile.txt" }, { "code": null, "e": 28779, "s": 28769, "text": "Output: " }, { "code": null, "e": 28834, "s": 28779, "text": "unix is great os. unix is opensource. unix is free os." }, { "code": null, "e": 29033, "s": 28834, "text": "9. Matching the lines that end with a string : The $ regular expression pattern specifies the end of a line. This can be used in grep to match the lines which end with the given string or pattern. " }, { "code": null, "e": 29059, "s": 29033, "text": "$ grep \"os$\" geekfile.txt" }, { "code": null, "e": 29126, "s": 29059, "text": "10.Specifies expression with -e option. Can use multiple times : " }, { "code": null, "e": 29185, "s": 29126, "text": "$grep –e \"Agarwal\" –e \"Aggarwal\" –e \"Agrawal\" geekfile.txt" }, { "code": null, "e": 29246, "s": 29185, "text": "11. -f file option Takes patterns from file, one per line. " }, { "code": null, "e": 29289, "s": 29246, "text": "$cat pattern.txt\n\nAgarwal\nAggarwal\nAgrawal" }, { "code": null, "e": 29326, "s": 29291, "text": "$grep –f pattern.txt geekfile.txt" }, { "code": null, "e": 29558, "s": 29326, "text": "12. Print n specific lines from a file: -A prints the searched line and n lines after the result, -B prints the searched line and n lines before the result, and -C prints the searched line and n lines after and before the result. " }, { "code": null, "e": 29566, "s": 29558, "text": "Syntax:" }, { "code": null, "e": 29703, "s": 29566, "text": "$grep -A[NumberOfLines(n)] [search] [file] \n\n$grep -B[NumberOfLines(n)] [search] [file] \n\n$grep -C[NumberOfLines(n)] [search] [file] " }, { "code": null, "e": 29712, "s": 29703, "text": "Example:" }, { "code": null, "e": 29741, "s": 29712, "text": "$grep -A1 learn geekfile.txt" }, { "code": null, "e": 29751, "s": 29741, "text": "Output: " }, { "code": null, "e": 31245, "s": 29751, "text": "learn operating system. \nUnix linux which one you choose. \n--\nuNix is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful. \n\n(Prints the searched line along with the next n lines (here n = 1 (A1).)\n(Will print each and every occurrence of the found line, separating each output by --) \n(Output pattern remains the same for -B and -C respectively) Unix linux which one you choose. -- uNix is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful. Unix linux which one you choose. -- uNix is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful." }, { "code": null, "e": 31384, "s": 31245, "text": "13. Search recursively for a pattern in the directory: -R prints the searched pattern in the given directory recursively in all the files." }, { "code": null, "e": 31391, "s": 31384, "text": "Syntax" }, { "code": null, "e": 31421, "s": 31391, "text": "$grep -R [Search] [directory]" }, { "code": null, "e": 31432, "s": 31421, "text": " Example :" }, { "code": null, "e": 31460, "s": 31432, "text": "$grep -iR geeks /home/geeks" }, { "code": null, "e": 31468, "s": 31460, "text": "Output:" }, { "code": null, "e": 31668, "s": 31468, "text": "./geeks2.txt:Well Hello Geeks\n./geeks1.txt:I am a big time geek\n----------------------------------\n-i to search for a string case insensitively\n-R to recursively check all the files in the directory." }, { "code": null, "e": 31967, "s": 31668, "text": "This article is contributed by Akshay Rajput. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks’ main page and help other Geeks. " }, { "code": null, "e": 32093, "s": 31967, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 32109, "s": 32093, "text": "yashbeersingh42" }, { "code": null, "e": 32125, "s": 32109, "text": "saurabh1990aror" }, { "code": null, "e": 32137, "s": 32125, "text": "anikaseth98" }, { "code": null, "e": 32145, "s": 32137, "text": "meetgor" }, { "code": null, "e": 32155, "s": 32145, "text": "avi122186" }, { "code": null, "e": 32168, "s": 32155, "text": "simmytarika5" }, { "code": null, "e": 32182, "s": 32168, "text": "linux-command" }, { "code": null, "e": 32202, "s": 32182, "text": "Linux-misc-commands" }, { "code": null, "e": 32213, "s": 32202, "text": "Linux-Unix" }, { "code": null, "e": 32311, "s": 32213, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32346, "s": 32311, "text": "tar command in Linux with examples" }, { "code": null, "e": 32384, "s": 32346, "text": "Conditional Statements | Shell Script" }, { "code": null, "e": 32422, "s": 32384, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 32458, "s": 32422, "text": "Tail command in Linux with examples" }, { "code": null, "e": 32493, "s": 32458, "text": "Cat command in Linux with examples" }, { "code": null, "e": 32530, "s": 32493, "text": "touch command in Linux with Examples" }, { "code": null, "e": 32566, "s": 32530, "text": "echo command in Linux with Examples" }, { "code": null, "e": 32585, "s": 32566, "text": "Compiling with g++" }, { "code": null, "e": 32620, "s": 32585, "text": "scp command in Linux with Examples" } ]
C++ Program for GCD of more than two (or array) numbers - GeeksforGeeks
04 Dec, 2018 The GCD of three or more numbers equals the product of the prime factors common to all the numbers, but it can also be calculated by repeatedly taking the GCDs of pairs of numbers. gcd(a, b, c) = gcd(a, gcd(b, c)) = gcd(gcd(a, b), c) = gcd(gcd(a, c), b) // C++ program to find GCD of two or// more numbers#include <bits/stdc++.h>using namespace std; // Function to return gcd of a and bint gcd(int a, int b){ if (a == 0) return b; return gcd(b % a, a);} // Function to find gcd of array of// numbersint findGCD(int arr[], int n){ int result = arr[0]; for (int i = 1; i < n; i++) result = gcd(arr[i], result); return result;} // Driven codeint main(){ int arr[] = { 2, 4, 6, 8, 16 }; int n = sizeof(arr) / sizeof(arr[0]); cout << findGCD(arr, n) << endl; return 0;} 2 Please refer complete article on GCD of more than two (or array) numbers for more details! GCD-LCM C++ Programs Mathematical Mathematical 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 Write a program to print all permutations of a given string C++ Data Types Set in C++ Standard Template Library (STL) Coin Change | DP-7
[ { "code": null, "e": 25877, "s": 25849, "text": "\n04 Dec, 2018" }, { "code": null, "e": 26058, "s": 25877, "text": "The GCD of three or more numbers equals the product of the prime factors common to all the numbers, but it can also be calculated by repeatedly taking the GCDs of pairs of numbers." }, { "code": null, "e": 26160, "s": 26058, "text": "gcd(a, b, c) = gcd(a, gcd(b, c)) \n = gcd(gcd(a, b), c) \n = gcd(gcd(a, c), b)\n" }, { "code": "// C++ program to find GCD of two or// more numbers#include <bits/stdc++.h>using namespace std; // Function to return gcd of a and bint gcd(int a, int b){ if (a == 0) return b; return gcd(b % a, a);} // Function to find gcd of array of// numbersint findGCD(int arr[], int n){ int result = arr[0]; for (int i = 1; i < n; i++) result = gcd(arr[i], result); return result;} // Driven codeint main(){ int arr[] = { 2, 4, 6, 8, 16 }; int n = sizeof(arr) / sizeof(arr[0]); cout << findGCD(arr, n) << endl; return 0;}", "e": 26717, "s": 26160, "text": null }, { "code": null, "e": 26720, "s": 26717, "text": "2\n" }, { "code": null, "e": 26811, "s": 26720, "text": "Please refer complete article on GCD of more than two (or array) numbers for more details!" }, { "code": null, "e": 26819, "s": 26811, "text": "GCD-LCM" }, { "code": null, "e": 26832, "s": 26819, "text": "C++ Programs" }, { "code": null, "e": 26845, "s": 26832, "text": "Mathematical" }, { "code": null, "e": 26858, "s": 26845, "text": "Mathematical" }, { "code": null, "e": 26956, "s": 26858, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26997, "s": 26956, "text": "Passing a function as a parameter in C++" }, { "code": null, "e": 27056, "s": 26997, "text": "Program to implement Singly Linked List in C++ using class" }, { "code": null, "e": 27077, "s": 27056, "text": "Const keyword in C++" }, { "code": null, "e": 27089, "s": 27077, "text": "cout in C++" }, { "code": null, "e": 27110, "s": 27089, "text": "Dynamic _Cast in C++" }, { "code": null, "e": 27140, "s": 27110, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 27200, "s": 27140, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 27215, "s": 27200, "text": "C++ Data Types" }, { "code": null, "e": 27258, "s": 27215, "text": "Set in C++ Standard Template Library (STL)" } ]
HashSet spliterator() method in Java - GeeksforGeeks
10 Dec, 2018 The spliterator() method of HashSet returns a Spliterator with the same elements as HashSet. The returned Spliterator is late-binding and fail-fast Spliterator. A late-binding Spliterator binds to the source of elements means HashSet at the point of first traversal, first split, or first query for estimated size, rather than at the time the Spliterator is created. It can be used with Streams in Java 8. Also it can traverse elements individually and in bulk too. Spliterator is better way to traverse over element because it provides more control on elements. Syntax: public Spliterator<E> spliterator() Returns: This method returns a Spliterator over the elements in HashSet. Below programs illustrate spliterator() method of HashSet: Example 1: To demonstrate spliterator() method on HashSet which contains a set of Numbers. // Java Program Demonstrate spliterator()// method of HashSet import java.util.*;public class GFG { public static void main(String[] args) { // create an HashSet which going to // contains a list of Numbers HashSet<Integer> Numbers = new HashSet<Integer>(); // Add Number to list Numbers.add(23); Numbers.add(32); Numbers.add(45); Numbers.add(63); // using spliterator() method Spliterator<Integer> numbers = Numbers.spliterator(); // print result from Spliterator System.out.println("list of Numbers:"); // forEachRemaining method of Spliterator numbers.forEachRemaining((n) -> System.out.println(n)); }} list of Numbers: 32 23 45 63 Example 2: To demonstrate spliterator() method on HashSet which contains set of Students Names. // Java Program Demonstrate spliterator()// method of HashSet import java.util.*;public class GFG { public static void main(String[] args) { // create an HashSet which going to // contains a list of string values HashSet<String> students = new HashSet<String>(); // Add Strings to list students.add("Ram"); students.add("Mohan"); students.add("Sohan"); students.add("Rabi"); // using spliterator() method Spliterator<String> names = students.spliterator(); // print result from Spliterator System.out.println("list of Students:"); // forEachRemaining method of Spliterator names.forEachRemaining( (n) -> System.out.println("Student Name: " + n)); }} list of Students: Student Name: Rabi Student Name: Mohan Student Name: Sohan Student Name: Ram Reference: https://docs.oracle.com/javase/8/docs/api/java/util/HashSet.html#spliterator– Java - util package java-basics Java-Collections Java-Functions java-hashset Java Java Java-Collections 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": "\n10 Dec, 2018" }, { "code": null, "e": 25788, "s": 25225, "text": "The spliterator() method of HashSet returns a Spliterator with the same elements as HashSet. The returned Spliterator is late-binding and fail-fast Spliterator. A late-binding Spliterator binds to the source of elements means HashSet at the point of first traversal, first split, or first query for estimated size, rather than at the time the Spliterator is created. It can be used with Streams in Java 8. Also it can traverse elements individually and in bulk too. Spliterator is better way to traverse over element because it provides more control on elements." }, { "code": null, "e": 25796, "s": 25788, "text": "Syntax:" }, { "code": null, "e": 25832, "s": 25796, "text": "public Spliterator<E> spliterator()" }, { "code": null, "e": 25905, "s": 25832, "text": "Returns: This method returns a Spliterator over the elements in HashSet." }, { "code": null, "e": 25964, "s": 25905, "text": "Below programs illustrate spliterator() method of HashSet:" }, { "code": null, "e": 26055, "s": 25964, "text": "Example 1: To demonstrate spliterator() method on HashSet which contains a set of Numbers." }, { "code": "// Java Program Demonstrate spliterator()// method of HashSet import java.util.*;public class GFG { public static void main(String[] args) { // create an HashSet which going to // contains a list of Numbers HashSet<Integer> Numbers = new HashSet<Integer>(); // Add Number to list Numbers.add(23); Numbers.add(32); Numbers.add(45); Numbers.add(63); // using spliterator() method Spliterator<Integer> numbers = Numbers.spliterator(); // print result from Spliterator System.out.println(\"list of Numbers:\"); // forEachRemaining method of Spliterator numbers.forEachRemaining((n) -> System.out.println(n)); }}", "e": 26781, "s": 26055, "text": null }, { "code": null, "e": 26811, "s": 26781, "text": "list of Numbers:\n32\n23\n45\n63\n" }, { "code": null, "e": 26907, "s": 26811, "text": "Example 2: To demonstrate spliterator() method on HashSet which contains set of Students Names." }, { "code": "// Java Program Demonstrate spliterator()// method of HashSet import java.util.*;public class GFG { public static void main(String[] args) { // create an HashSet which going to // contains a list of string values HashSet<String> students = new HashSet<String>(); // Add Strings to list students.add(\"Ram\"); students.add(\"Mohan\"); students.add(\"Sohan\"); students.add(\"Rabi\"); // using spliterator() method Spliterator<String> names = students.spliterator(); // print result from Spliterator System.out.println(\"list of Students:\"); // forEachRemaining method of Spliterator names.forEachRemaining( (n) -> System.out.println(\"Student Name: \" + n)); }}", "e": 27688, "s": 26907, "text": null }, { "code": null, "e": 27784, "s": 27688, "text": "list of Students:\nStudent Name: Rabi\nStudent Name: Mohan\nStudent Name: Sohan\nStudent Name: Ram\n" }, { "code": null, "e": 27873, "s": 27784, "text": "Reference: https://docs.oracle.com/javase/8/docs/api/java/util/HashSet.html#spliterator–" }, { "code": null, "e": 27893, "s": 27873, "text": "Java - util package" }, { "code": null, "e": 27905, "s": 27893, "text": "java-basics" }, { "code": null, "e": 27922, "s": 27905, "text": "Java-Collections" }, { "code": null, "e": 27937, "s": 27922, "text": "Java-Functions" }, { "code": null, "e": 27950, "s": 27937, "text": "java-hashset" }, { "code": null, "e": 27955, "s": 27950, "text": "Java" }, { "code": null, "e": 27960, "s": 27955, "text": "Java" }, { "code": null, "e": 27977, "s": 27960, "text": "Java-Collections" }, { "code": null, "e": 28075, "s": 27977, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28090, "s": 28075, "text": "Stream In Java" }, { "code": null, "e": 28111, "s": 28090, "text": "Constructors in Java" }, { "code": null, "e": 28130, "s": 28111, "text": "Exceptions in Java" }, { "code": null, "e": 28160, "s": 28130, "text": "Functional Interfaces in Java" }, { "code": null, "e": 28206, "s": 28160, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 28223, "s": 28206, "text": "Generics in Java" }, { "code": null, "e": 28244, "s": 28223, "text": "Introduction to Java" }, { "code": null, "e": 28287, "s": 28244, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 28323, "s": 28287, "text": "Internal Working of HashMap in Java" } ]
Node.js MySQL LENGTH() Function - GeeksforGeeks
07 Oct, 2021 LENGTH() Function is a Builtin function in MySQL which is used to get length of given string in bytes. Syntax: LENGTH(input_string) Parameters: LENGTH() function accepts a single parameter as mentioned above and described below. input_string: We will get number of characters of this string Return Value: LENGTH() function returns length of given string in bytes. Modules: mysql: To handle MySQL Connection and Queries npm install mysql SQL publishers Table Preview: Example 1: Javascript const mysql = require("mysql"); let db_con = mysql.createConnection({ host: "localhost", user: "root", password: "", database: "gfg_db",}); db_con.connect((err) => { if (err) { console.log("Database Connection Failed !!!", err); return; } console.log("We are connected to gfg_db database"); // here is the query let query = `SELECT LENGTH('Geeks for Geeks') AS length_in_bytes`; db_con.query(query, (err, rows) => { if (err) throw err; console.log(rows); });}); Output: Example 2: Javascript const mysql = require("mysql"); let db_con = mysql.createConnection({ host: "localhost", user: "root", password: "", database: "gfg_db",}); db_con.connect((err) => { if (err) { console.log("Database Connection Failed !!!", err); return; } console.log("We are connected to gfg_db database"); // here is the query let query = `SELECT name, LENGTH(name) AS length_in_bytes FROM publishers`; db_con.query(query, (err, rows) => { if (err) throw err; console.log(rows); });}); Output: NodeJS-MySQL Technical Scripter 2020 Node.js Technical Scripter Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to connect Node.js with React.js ? Node.js Export Module Difference between dependencies, devDependencies and peerDependencies Mongoose Populate() Method Mongoose find() Function Remove elements from a JavaScript Array 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 Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26267, "s": 26239, "text": "\n07 Oct, 2021" }, { "code": null, "e": 26370, "s": 26267, "text": "LENGTH() Function is a Builtin function in MySQL which is used to get length of given string in bytes." }, { "code": null, "e": 26378, "s": 26370, "text": "Syntax:" }, { "code": null, "e": 26399, "s": 26378, "text": "LENGTH(input_string)" }, { "code": null, "e": 26496, "s": 26399, "text": "Parameters: LENGTH() function accepts a single parameter as mentioned above and described below." }, { "code": null, "e": 26558, "s": 26496, "text": "input_string: We will get number of characters of this string" }, { "code": null, "e": 26631, "s": 26558, "text": "Return Value: LENGTH() function returns length of given string in bytes." }, { "code": null, "e": 26640, "s": 26631, "text": "Modules:" }, { "code": null, "e": 26686, "s": 26640, "text": "mysql: To handle MySQL Connection and Queries" }, { "code": null, "e": 26704, "s": 26686, "text": "npm install mysql" }, { "code": null, "e": 26734, "s": 26704, "text": "SQL publishers Table Preview:" }, { "code": null, "e": 26745, "s": 26734, "text": "Example 1:" }, { "code": null, "e": 26756, "s": 26745, "text": "Javascript" }, { "code": "const mysql = require(\"mysql\"); let db_con = mysql.createConnection({ host: \"localhost\", user: \"root\", password: \"\", database: \"gfg_db\",}); db_con.connect((err) => { if (err) { console.log(\"Database Connection Failed !!!\", err); return; } console.log(\"We are connected to gfg_db database\"); // here is the query let query = `SELECT LENGTH('Geeks for Geeks') AS length_in_bytes`; db_con.query(query, (err, rows) => { if (err) throw err; console.log(rows); });});", "e": 27251, "s": 26756, "text": null }, { "code": null, "e": 27259, "s": 27251, "text": "Output:" }, { "code": null, "e": 27270, "s": 27259, "text": "Example 2:" }, { "code": null, "e": 27281, "s": 27270, "text": "Javascript" }, { "code": "const mysql = require(\"mysql\"); let db_con = mysql.createConnection({ host: \"localhost\", user: \"root\", password: \"\", database: \"gfg_db\",}); db_con.connect((err) => { if (err) { console.log(\"Database Connection Failed !!!\", err); return; } console.log(\"We are connected to gfg_db database\"); // here is the query let query = `SELECT name, LENGTH(name) AS length_in_bytes FROM publishers`; db_con.query(query, (err, rows) => { if (err) throw err; console.log(rows); });});", "e": 27785, "s": 27281, "text": null }, { "code": null, "e": 27793, "s": 27785, "text": "Output:" }, { "code": null, "e": 27806, "s": 27793, "text": "NodeJS-MySQL" }, { "code": null, "e": 27830, "s": 27806, "text": "Technical Scripter 2020" }, { "code": null, "e": 27838, "s": 27830, "text": "Node.js" }, { "code": null, "e": 27857, "s": 27838, "text": "Technical Scripter" }, { "code": null, "e": 27874, "s": 27857, "text": "Web Technologies" }, { "code": null, "e": 27972, "s": 27874, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28011, "s": 27972, "text": "How to connect Node.js with React.js ?" }, { "code": null, "e": 28033, "s": 28011, "text": "Node.js Export Module" }, { "code": null, "e": 28103, "s": 28033, "text": "Difference between dependencies, devDependencies and peerDependencies" }, { "code": null, "e": 28130, "s": 28103, "text": "Mongoose Populate() Method" }, { "code": null, "e": 28155, "s": 28130, "text": "Mongoose find() Function" }, { "code": null, "e": 28195, "s": 28155, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28240, "s": 28195, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28283, "s": 28240, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 28345, "s": 28283, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
numpy.intersect1d() function in Python - GeeksforGeeks
17 May, 2020 numpy.intersect1d() function find the intersection of two arrays and return the sorted, unique values that are in both of the input arrays. Syntax: numpy.intersect1d(arr1, arr2, assume_unique = False, return_indices = False) Parameters :arr1, arr2 : [array_like] Input arrays.assume_unique : [bool] If True, the input arrays are both assumed to be unique, which can speed up the calculation. Default is False.return_indices : [bool] If True, the indices which correspond to the intersection of the two arrays are returned. The first instance of a value is used if there are multiple. Default is False. Return : [ndarray] Sorted 1D array of common and unique elements. Code #1 : # Python program explaining# numpy.intersect1d() function # importing numpy as geek import numpy as geek arr1 = geek.array([1, 1, 2, 3, 4])arr2 = geek.array([2, 1, 4, 6]) gfg = geek.intersect1d(arr1, arr2) print (gfg) Output : [1 2 4] Code #2 : # Python program explaining# numpy.intersect1d() function # importing numpy as geek import numpy as geek arr1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]arr2 = [1, 3, 5, 7, 9] gfg = geek.intersect1d(arr1, arr2) print (gfg) Output : [1 3 5 7 9] Python numpy-arrayManipulation Python-numpy 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 ? Enumerate() in Python Different ways to create Pandas Dataframe Reading and Writing to text files in Python *args and **kwargs in Python Convert integer to string in Python Check if element exists in list in Python Create a Pandas DataFrame from Lists sum() function in Python
[ { "code": null, "e": 26119, "s": 26091, "text": "\n17 May, 2020" }, { "code": null, "e": 26259, "s": 26119, "text": "numpy.intersect1d() function find the intersection of two arrays and return the sorted, unique values that are in both of the input arrays." }, { "code": null, "e": 26344, "s": 26259, "text": "Syntax: numpy.intersect1d(arr1, arr2, assume_unique = False, return_indices = False)" }, { "code": null, "e": 26721, "s": 26344, "text": "Parameters :arr1, arr2 : [array_like] Input arrays.assume_unique : [bool] If True, the input arrays are both assumed to be unique, which can speed up the calculation. Default is False.return_indices : [bool] If True, the indices which correspond to the intersection of the two arrays are returned. The first instance of a value is used if there are multiple. Default is False." }, { "code": null, "e": 26787, "s": 26721, "text": "Return : [ndarray] Sorted 1D array of common and unique elements." }, { "code": null, "e": 26797, "s": 26787, "text": "Code #1 :" }, { "code": "# Python program explaining# numpy.intersect1d() function # importing numpy as geek import numpy as geek arr1 = geek.array([1, 1, 2, 3, 4])arr2 = geek.array([2, 1, 4, 6]) gfg = geek.intersect1d(arr1, arr2) print (gfg)", "e": 27029, "s": 26797, "text": null }, { "code": null, "e": 27038, "s": 27029, "text": "Output :" }, { "code": null, "e": 27047, "s": 27038, "text": "[1 2 4]\n" }, { "code": null, "e": 27058, "s": 27047, "text": " Code #2 :" }, { "code": "# Python program explaining# numpy.intersect1d() function # importing numpy as geek import numpy as geek arr1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]arr2 = [1, 3, 5, 7, 9] gfg = geek.intersect1d(arr1, arr2) print (gfg)", "e": 27281, "s": 27058, "text": null }, { "code": null, "e": 27290, "s": 27281, "text": "Output :" }, { "code": null, "e": 27303, "s": 27290, "text": "[1 3 5 7 9]\n" }, { "code": null, "e": 27334, "s": 27303, "text": "Python numpy-arrayManipulation" }, { "code": null, "e": 27347, "s": 27334, "text": "Python-numpy" }, { "code": null, "e": 27354, "s": 27347, "text": "Python" }, { "code": null, "e": 27452, "s": 27354, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27470, "s": 27452, "text": "Python Dictionary" }, { "code": null, "e": 27502, "s": 27470, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27524, "s": 27502, "text": "Enumerate() in Python" }, { "code": null, "e": 27566, "s": 27524, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27610, "s": 27566, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 27639, "s": 27610, "text": "*args and **kwargs in Python" }, { "code": null, "e": 27675, "s": 27639, "text": "Convert integer to string in Python" }, { "code": null, "e": 27717, "s": 27675, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27754, "s": 27717, "text": "Create a Pandas DataFrame from Lists" } ]
Filter multiple values on a string column in R using Dplyr - GeeksforGeeks
28 Jul, 2021 In this article we will learn how to filter multiple values on a string column in R programming language using dplyr package. filter() function is used to choose cases and filtering out the values based on the filtering conditions. Syntax: filter(df, condition) Parameters: df: Dataframe object condition: filtering based on this condition Example: R program to filter multiple values using filter() R library(dplyr) df <- data.frame(prep = c(11:15), str = c("Welcome", "to", "Geeks", "for", "Geeks"), date=c("Sunday","Monday", "Thursday", "January","December")) filter(df,date=='Sunday'| date=='Monday') Output: prep str date 1 11 Welcome Sunday 2 12 to Monday In this, first, pass your dataframe object to the filter function, then in the condition parameter write the column name in which you want to filter multiple values then put the %in% operator, and then pass a vector containing all the string values which you want in the result. This produces all the rows containing the string values in the specified column. Syntax: filter(df, date %in% c(“Thursday”, “January”, “Sunday”)) Parameters: df: dataframe object condition: column_name %in% vector string of values Example: R program to filter multiple values using %in% R library(dplyr) df <- data.frame(prep = c(11:15), str = c("Welcome", "to", "Geeks", "for", "Geeks"), date=c("Sunday","Monday", "Thursday", "January","December")) filter(df, date %in% c("Thursday", "January", "Sunday")) Output: prep str date 1 11 Welcome Sunday 2 13 Geeks Thursday 3 14 for January Example: Same as above but in this example, we perform the same operation, but on different columns with a different set of values. R library(dplyr) df <- data.frame(prep = c(11:15), str = c("Welcome", "to", "Geeks", "for", "Geeks"), date=c("Sunday","Monday", "Thursday", "January","December")) filter(df, str %in% c("Geeks", "to")) Output: prep str date 1 12 to Monday 2 13 Geeks Thursday 3 15 Geeks December For this functionality, select() function accepts 2 parameters, first is the filter function and the second is a vector of column names, Syntax: select(filter(df, condition, columns) Parameters: df: dataframe object condition: filtering condition columns: vector of column names which you want to print filter() works almost the same way as given above, the only difference being the vector of column names which we are passing in the second argument. This prints only the columns that were passed in the select function. In this way we can print selected columns only. Example: Printing selected rows R library(dplyr) df <- data.frame(prep = c(11:15), str = c("Welcome", "to", "Geeks", "for", "Geeks"), date=c("Sunday","Monday", "Thursday", "January","December")) select(filter(df, date %in% c("January", "Monday")), c(date,prep)) Output: date prep 1 Monday 12 2 January 14 Picked R Dplyr R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Replace specific values in column in R DataFrame ? Loops in R (for, while, repeat) How to change Row Names of DataFrame in R ? 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? R Programming Language - Introduction Creating a Data Frame from Vectors in R Programming K-Means Clustering in R Programming
[ { "code": null, "e": 26159, "s": 26131, "text": "\n28 Jul, 2021" }, { "code": null, "e": 26285, "s": 26159, "text": "In this article we will learn how to filter multiple values on a string column in R programming language using dplyr package." }, { "code": null, "e": 26391, "s": 26285, "text": "filter() function is used to choose cases and filtering out the values based on the filtering conditions." }, { "code": null, "e": 26421, "s": 26391, "text": "Syntax: filter(df, condition)" }, { "code": null, "e": 26433, "s": 26421, "text": "Parameters:" }, { "code": null, "e": 26454, "s": 26433, "text": "df: Dataframe object" }, { "code": null, "e": 26499, "s": 26454, "text": "condition: filtering based on this condition" }, { "code": null, "e": 26559, "s": 26499, "text": "Example: R program to filter multiple values using filter()" }, { "code": null, "e": 26561, "s": 26559, "text": "R" }, { "code": "library(dplyr) df <- data.frame(prep = c(11:15), str = c(\"Welcome\", \"to\", \"Geeks\", \"for\", \"Geeks\"), date=c(\"Sunday\",\"Monday\", \"Thursday\", \"January\",\"December\")) filter(df,date=='Sunday'| date=='Monday')", "e": 26847, "s": 26561, "text": null }, { "code": null, "e": 26855, "s": 26847, "text": "Output:" }, { "code": null, "e": 26921, "s": 26855, "text": " prep str date\n1 11 Welcome Sunday\n2 12 to Monday" }, { "code": null, "e": 27281, "s": 26921, "text": "In this, first, pass your dataframe object to the filter function, then in the condition parameter write the column name in which you want to filter multiple values then put the %in% operator, and then pass a vector containing all the string values which you want in the result. This produces all the rows containing the string values in the specified column." }, { "code": null, "e": 27347, "s": 27281, "text": "Syntax: filter(df, date %in% c(“Thursday”, “January”, “Sunday”))" }, { "code": null, "e": 27359, "s": 27347, "text": "Parameters:" }, { "code": null, "e": 27380, "s": 27359, "text": "df: dataframe object" }, { "code": null, "e": 27432, "s": 27380, "text": "condition: column_name %in% vector string of values" }, { "code": null, "e": 27488, "s": 27432, "text": "Example: R program to filter multiple values using %in%" }, { "code": null, "e": 27490, "s": 27488, "text": "R" }, { "code": "library(dplyr) df <- data.frame(prep = c(11:15), str = c(\"Welcome\", \"to\", \"Geeks\", \"for\", \"Geeks\"), date=c(\"Sunday\",\"Monday\", \"Thursday\", \"January\",\"December\")) filter(df, date %in% c(\"Thursday\", \"January\", \"Sunday\"))", "e": 27790, "s": 27490, "text": null }, { "code": null, "e": 27798, "s": 27790, "text": "Output:" }, { "code": null, "e": 27894, "s": 27798, "text": " prep str date\n1 11 Welcome Sunday\n2 13 Geeks Thursday\n3 14 for January" }, { "code": null, "e": 28027, "s": 27894, "text": "Example: Same as above but in this example, we perform the same operation, but on different columns with a different set of values. " }, { "code": null, "e": 28029, "s": 28027, "text": "R" }, { "code": "library(dplyr) df <- data.frame(prep = c(11:15), str = c(\"Welcome\", \"to\", \"Geeks\", \"for\", \"Geeks\"), date=c(\"Sunday\",\"Monday\", \"Thursday\", \"January\",\"December\")) filter(df, str %in% c(\"Geeks\", \"to\"))", "e": 28311, "s": 28029, "text": null }, { "code": null, "e": 28319, "s": 28311, "text": "Output:" }, { "code": null, "e": 28407, "s": 28319, "text": " prep str date\n1 12 to Monday\n2 13 Geeks Thursday\n3 15 Geeks December" }, { "code": null, "e": 28544, "s": 28407, "text": "For this functionality, select() function accepts 2 parameters, first is the filter function and the second is a vector of column names," }, { "code": null, "e": 28590, "s": 28544, "text": "Syntax: select(filter(df, condition, columns)" }, { "code": null, "e": 28602, "s": 28590, "text": "Parameters:" }, { "code": null, "e": 28623, "s": 28602, "text": "df: dataframe object" }, { "code": null, "e": 28654, "s": 28623, "text": "condition: filtering condition" }, { "code": null, "e": 28710, "s": 28654, "text": "columns: vector of column names which you want to print" }, { "code": null, "e": 28977, "s": 28710, "text": "filter() works almost the same way as given above, the only difference being the vector of column names which we are passing in the second argument. This prints only the columns that were passed in the select function. In this way we can print selected columns only." }, { "code": null, "e": 29009, "s": 28977, "text": "Example: Printing selected rows" }, { "code": null, "e": 29011, "s": 29009, "text": "R" }, { "code": "library(dplyr) df <- data.frame(prep = c(11:15), str = c(\"Welcome\", \"to\", \"Geeks\", \"for\", \"Geeks\"), date=c(\"Sunday\",\"Monday\", \"Thursday\", \"January\",\"December\")) select(filter(df, date %in% c(\"January\", \"Monday\")), c(date,prep))", "e": 29323, "s": 29011, "text": null }, { "code": null, "e": 29331, "s": 29323, "text": "Output:" }, { "code": null, "e": 29377, "s": 29331, "text": " date prep\n1 Monday 12\n2 January 14" }, { "code": null, "e": 29384, "s": 29377, "text": "Picked" }, { "code": null, "e": 29392, "s": 29384, "text": "R Dplyr" }, { "code": null, "e": 29403, "s": 29392, "text": "R Language" }, { "code": null, "e": 29501, "s": 29403, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29559, "s": 29501, "text": "How to Replace specific values in column in R DataFrame ?" }, { "code": null, "e": 29591, "s": 29559, "text": "Loops in R (for, while, repeat)" }, { "code": null, "e": 29635, "s": 29591, "text": "How to change Row Names of DataFrame in R ?" }, { "code": null, "e": 29687, "s": 29635, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 29722, "s": 29687, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 29760, "s": 29722, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 29818, "s": 29760, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 29856, "s": 29818, "text": "R Programming Language - Introduction" }, { "code": null, "e": 29908, "s": 29856, "text": "Creating a Data Frame from Vectors in R Programming" } ]
Printing Output on Screen in Julia - GeeksforGeeks
28 Jul, 2021 Julia provides many methods of printing output on the screen. The Julia program starts with an interactive REPL (Read/ Evaluate /Print / Loop) as default. R: Reads what was typed; E: Evaluates the typed expression; P: Prints the return value; L: Loops back and repeats it ; It helps in outputting the result of the expression on the screen immediately. Using REPL, Julia provides the facility to evaluate the expression at the time of reading it, and further print the output of the expression. Example: Julia # x is a string"hello" # x is a integer4 # adding two integer4 + 4 If you don’t want the output to be printed you can use a semicolon(;) at the end. Example: Julia # example of ; # addition of two int4 + 4 ; # concatenation of two strings"hello" * "world"; To recall the last expression that was typed on the console we use ans command. The ans stores the last expression that was typed in the console. Example: Julia # expression2 + 2 - 4 * 5 + 12; # recall last evaluated expressionans The most common function to print the output of the program in the console of Julia is print() and println(). To execute this command we just need to press Enter on the keyboard. The main difference is that the println() function adds a new line to the end of the output. Example: Julia # print functionx = "The quick brown fox jumps over the lazy dog";print(x) # println functionx = "The quick brown fox jumps over the lazy dog";println(x) The show(io:: IO, x) function is also used to print output on the screen where the first argument is a stream. The REPL returns the output of show() function as a string. Example: Julia # show functionshow("HELLO WORLD") printstyled() function helps in printing out message in different colors. Example: Julia # using printstyled # printing text in different colorsfor color in [:red, :cyan, :blue, :magenta] printstyled("Hello World $(color)\n"; color = color)end Julia also supports printf() function which is used in C language to print output on the console. Julia macro (which is used by prefacing it with the @ sign) provides the Printf package which needs to be imported in order to use. printf() is also used as a formatting tool. Here %f is used for conversion. Example: Julia # importing Printfusing Printf # using printf macro with @ sign@printf("pi = %0.20f", float(pi)) And we can use @sprintf() function in order to create another string Example: Julia # importing Printfusing Printf # using @macro with sprintf where output is a string@sprintf("pi = %0.20f", float(pi)) write() function is used to write the output to a file and it prints the no. of characters present in the string on the console. Example: Julia # write functionopen("geek.txt", "w") do io write(io, "The quick brown fox jumps over the lazy dog");end # the readline() function to show the output of the filereadline("geek.txt") anikaseth98 sagar0719kumar Picked Julia Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Decision Making in Julia (if, if-else, Nested-if, if-elseif-else ladder) Get array dimensions and size of a dimension in Julia - size() Method Exception handling in Julia Searching in Array for a given element in Julia Find maximum element along with its index in Julia - findmax() Method Get number of elements of array in Julia - length() Method Join an array of strings into a single string in Julia - join() Method Working with Excel Files in Julia Getting last element of an array in Julia - last() Method File Handling in Julia
[ { "code": null, "e": 25719, "s": 25691, "text": "\n28 Jul, 2021" }, { "code": null, "e": 25875, "s": 25719, "text": "Julia provides many methods of printing output on the screen. The Julia program starts with an interactive REPL (Read/ Evaluate /Print / Loop) as default. " }, { "code": null, "e": 25900, "s": 25875, "text": "R: Reads what was typed;" }, { "code": null, "e": 25935, "s": 25900, "text": "E: Evaluates the typed expression;" }, { "code": null, "e": 25963, "s": 25935, "text": "P: Prints the return value;" }, { "code": null, "e": 25994, "s": 25963, "text": "L: Loops back and repeats it ;" }, { "code": null, "e": 26074, "s": 25994, "text": "It helps in outputting the result of the expression on the screen immediately. " }, { "code": null, "e": 26217, "s": 26074, "text": "Using REPL, Julia provides the facility to evaluate the expression at the time of reading it, and further print the output of the expression. " }, { "code": null, "e": 26226, "s": 26217, "text": "Example:" }, { "code": null, "e": 26232, "s": 26226, "text": "Julia" }, { "code": "# x is a string\"hello\" # x is a integer4 # adding two integer4 + 4", "e": 26299, "s": 26232, "text": null }, { "code": null, "e": 26381, "s": 26299, "text": "If you don’t want the output to be printed you can use a semicolon(;) at the end." }, { "code": null, "e": 26391, "s": 26381, "text": "Example: " }, { "code": null, "e": 26397, "s": 26391, "text": "Julia" }, { "code": "# example of ; # addition of two int4 + 4 ; # concatenation of two strings\"hello\" * \"world\";", "e": 26490, "s": 26397, "text": null }, { "code": null, "e": 26636, "s": 26490, "text": "To recall the last expression that was typed on the console we use ans command. The ans stores the last expression that was typed in the console." }, { "code": null, "e": 26645, "s": 26636, "text": "Example:" }, { "code": null, "e": 26651, "s": 26645, "text": "Julia" }, { "code": "# expression2 + 2 - 4 * 5 + 12; # recall last evaluated expressionans", "e": 26721, "s": 26651, "text": null }, { "code": null, "e": 26993, "s": 26721, "text": "The most common function to print the output of the program in the console of Julia is print() and println(). To execute this command we just need to press Enter on the keyboard. The main difference is that the println() function adds a new line to the end of the output." }, { "code": null, "e": 27003, "s": 26993, "text": "Example: " }, { "code": null, "e": 27009, "s": 27003, "text": "Julia" }, { "code": "# print functionx = \"The quick brown fox jumps over the lazy dog\";print(x) # println functionx = \"The quick brown fox jumps over the lazy dog\";println(x)", "e": 27163, "s": 27009, "text": null }, { "code": null, "e": 27334, "s": 27163, "text": "The show(io:: IO, x) function is also used to print output on the screen where the first argument is a stream. The REPL returns the output of show() function as a string." }, { "code": null, "e": 27343, "s": 27334, "text": "Example:" }, { "code": null, "e": 27349, "s": 27343, "text": "Julia" }, { "code": "# show functionshow(\"HELLO WORLD\")", "e": 27384, "s": 27349, "text": null }, { "code": null, "e": 27458, "s": 27384, "text": "printstyled() function helps in printing out message in different colors." }, { "code": null, "e": 27468, "s": 27458, "text": "Example: " }, { "code": null, "e": 27474, "s": 27468, "text": "Julia" }, { "code": "# using printstyled # printing text in different colorsfor color in [:red, :cyan, :blue, :magenta] printstyled(\"Hello World $(color)\\n\"; color = color)end", "e": 27632, "s": 27474, "text": null }, { "code": null, "e": 27938, "s": 27632, "text": "Julia also supports printf() function which is used in C language to print output on the console. Julia macro (which is used by prefacing it with the @ sign) provides the Printf package which needs to be imported in order to use. printf() is also used as a formatting tool. Here %f is used for conversion." }, { "code": null, "e": 27948, "s": 27938, "text": "Example: " }, { "code": null, "e": 27954, "s": 27948, "text": "Julia" }, { "code": "# importing Printfusing Printf # using printf macro with @ sign@printf(\"pi = %0.20f\", float(pi))", "e": 28051, "s": 27954, "text": null }, { "code": null, "e": 28120, "s": 28051, "text": "And we can use @sprintf() function in order to create another string" }, { "code": null, "e": 28130, "s": 28120, "text": "Example: " }, { "code": null, "e": 28136, "s": 28130, "text": "Julia" }, { "code": "# importing Printfusing Printf # using @macro with sprintf where output is a string@sprintf(\"pi = %0.20f\", float(pi))", "e": 28254, "s": 28136, "text": null }, { "code": null, "e": 28383, "s": 28254, "text": "write() function is used to write the output to a file and it prints the no. of characters present in the string on the console." }, { "code": null, "e": 28393, "s": 28383, "text": "Example: " }, { "code": null, "e": 28399, "s": 28393, "text": "Julia" }, { "code": "# write functionopen(\"geek.txt\", \"w\") do io write(io, \"The quick brown fox jumps over the lazy dog\");end # the readline() function to show the output of the filereadline(\"geek.txt\")", "e": 28585, "s": 28399, "text": null }, { "code": null, "e": 28597, "s": 28585, "text": "anikaseth98" }, { "code": null, "e": 28612, "s": 28597, "text": "sagar0719kumar" }, { "code": null, "e": 28619, "s": 28612, "text": "Picked" }, { "code": null, "e": 28625, "s": 28619, "text": "Julia" }, { "code": null, "e": 28723, "s": 28625, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28796, "s": 28723, "text": "Decision Making in Julia (if, if-else, Nested-if, if-elseif-else ladder)" }, { "code": null, "e": 28866, "s": 28796, "text": "Get array dimensions and size of a dimension in Julia - size() Method" }, { "code": null, "e": 28894, "s": 28866, "text": "Exception handling in Julia" }, { "code": null, "e": 28942, "s": 28894, "text": "Searching in Array for a given element in Julia" }, { "code": null, "e": 29012, "s": 28942, "text": "Find maximum element along with its index in Julia - findmax() Method" }, { "code": null, "e": 29071, "s": 29012, "text": "Get number of elements of array in Julia - length() Method" }, { "code": null, "e": 29142, "s": 29071, "text": "Join an array of strings into a single string in Julia - join() Method" }, { "code": null, "e": 29176, "s": 29142, "text": "Working with Excel Files in Julia" }, { "code": null, "e": 29234, "s": 29176, "text": "Getting last element of an array in Julia - last() Method" } ]
Count Negative Numbers in a Column-Wise and Row-Wise Sorted Matrix - GeeksforGeeks
22 Jan, 2022 Find the number of negative numbers in a column-wise / row-wise sorted matrix M[][]. Suppose M has n rows and m columns.Example: Input: M = [-3, -2, -1, 1] [-2, 2, 3, 4] [4, 5, 7, 8] Output : 4 We have 4 negative numbers in this matrix We strongly recommend you to minimize your browser and try this yourself first.Naive Solution Here’s a naive, non-optimal solution.We start from the top left corner and count the number of negative numbers one by one, from left to right and top to bottom.With the given example: [-3, -2, -1, 1] [-2, 2, 3, 4] [4, 5, 7, 8] Evaluation process [?, ?, ?, 1] [?, 2, 3, 4] [4, 5, 7, 8] Below is the implementation of above idea: C++ Java Python3 C# PHP Javascript // CPP implementation of Naive method// to count of negative numbers in// M[n][m]#include <bits/stdc++.h>using namespace std; int countNegative(int M[][4], int n, int m){ int count = 0; // Follow the path shown using // arrows above for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (M[i][j] < 0) count += 1; // no more negative numbers // in this row else break; } } return count;} // Driver program to test above functionsint main(){ int M[3][4] = { { -3, -2, -1, 1 }, { -2, 2, 3, 4 }, { 4, 5, 7, 8 } }; cout << countNegative(M, 3, 4); return 0;}// This code is contributed by Niteesh Kumar // Java implementation of Naive method// to count of negative numbers in// M[n][m]import java.util.*;import java.lang.*;import java.io.*; class GFG { static int countNegative(int M[][], int n, int m) { int count = 0; // Follow the path shown using // arrows above for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (M[i][j] < 0) count += 1; // no more negative numbers // in this row else break; } } return count; } // Driver program to test above functions public static void main(String[] args) { int M[][] = { { -3, -2, -1, 1 }, { -2, 2, 3, 4 }, { 4, 5, 7, 8 } }; System.out.println(countNegative(M, 3, 4)); }}// This code is contributed by Chhavi # Python implementation of Naive method to count of# negative numbers in M[n][m] def countNegative(M, n, m): count = 0 # Follow the path shown using arrows above for i in range(n): for j in range(m): if M[i][j] < 0: count += 1 else: # no more negative numbers in this row break return count # Driver codeM = [ [-3, -2, -1, 1], [-2, 2, 3, 4], [ 4, 5, 7, 8] ]print(countNegative(M, 3, 4)) // C# implementation of Naive method// to count of negative numbers in// M[n][m]using System; class GFG { // Function to count // negative number static int countNegative(int[, ] M, int n, int m) { int count = 0; // Follow the path shown // using arrows above for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (M[i, j] < 0) count += 1; // no more negative numbers // in this row else break; } } return count; } // Driver Code public static void Main() { int[, ] M = { { -3, -2, -1, 1 }, { -2, 2, 3, 4 }, { 4, 5, 7, 8 } }; Console.WriteLine(countNegative(M, 3, 4)); }} // This code is contributed by Sam007 <?php// PHP implementation of Naive method// to count of negative numbers in// M[n][m] function countNegative($M, $n, $m){ $count = 0; // Follow the path shown using // arrows above for( $i = 0; $i < $n; $i++) { for( $j = 0; $j < $m; $j++) { if( $M[$i][$j] < 0 ) $count += 1; // no more negative numbers // in this row else break; } } return $count;} // Driver Code $M = array(array(-3, -2, -1, 1), array(-2, 2, 3, 4), array(4, 5, 7, 8)); echo countNegative($M, 3, 4); // This code is contributed by anuj_67.?> <script> // JavaScript implementation of Naive method// to count of negative numbers in// M[n][m]function countNegative(M,n,m) { let count = 0; // Follow the path shown using // arrows above for (let i = 0; i < n; i++) { for (let j = 0; j < m; j++) { if (M[i][j] < 0) count += 1; // no more negative numbers // in this row else break; } } return count; } // Driver program to test above functions let M = [[ -3, -2, -1, 1 ], [ -2, 2, 3, 4 ], [ 4, 5, 7, 8 ]]; document.write(countNegative(M, 3, 4)); // This code is contributed by sravan kumar </script> Output: 4 In this approach we are traversing through all the elements and therefore, in the worst case scenario (when all numbers are negative in the matrix), this takes O(n * m) time.Optimal SolutionHere’s a more efficient solution: We start from the top right corner and find the position of the last negative number in the first row.Using this information, we find the position of the last negative number in the second row.We keep repeating this process until we either run out of negative numbers or we get to the last row. We start from the top right corner and find the position of the last negative number in the first row. Using this information, we find the position of the last negative number in the second row. We keep repeating this process until we either run out of negative numbers or we get to the last row. With the given example: [-3, -2, -1, 1] [-2, 2, 3, 4] [4, 5, 7, 8] Here's the idea: [-3, -2, ?, ?] -> Found 3 negative numbers in this row [ ?, ?, ?, 4] -> Found 1 negative number in this row [ ?, 5, 7, 8] -> No negative numbers in this row C++ Java Python3 C# PHP Javascript // CPP implementation of Efficient// method to count of negative numbers// in M[n][m]#include <bits/stdc++.h>using namespace std; int countNegative(int M[][4], int n, int m){ // initialize result int count = 0; // Start with top right corner int i = 0; int j = m - 1; // Follow the path shown using // arrows above while (j >= 0 && i < n) { if (M[i][j] < 0) { // j is the index of the // last negative number // in this row. So there // must be ( j+1 ) count += j + 1; // negative numbers in // this row. i += 1; } // move to the left and see // if we can find a negative // number there else j -= 1; } return count;} // Driver program to test above functionsint main(){ int M[3][4] = { { -3, -2, -1, 1 }, { -2, 2, 3, 4 }, { 4, 5, 7, 8 } }; cout << countNegative(M, 3, 4); return 0;}// This code is contributed by Niteesh Kumar // Java implementation of Efficient// method to count of negative numbers// in M[n][m]import java.util.*;import java.lang.*;import java.io.*; class GFG { static int countNegative(int M[][], int n, int m) { // initialize result int count = 0; // Start with top right corner int i = 0; int j = m - 1; // Follow the path shown using // arrows above while (j >= 0 && i < n) { if (M[i][j] < 0) { // j is the index of the // last negative number // in this row. So there // must be ( j+1 ) count += j + 1; // negative numbers in // this row. i += 1; } // move to the left and see // if we can find a negative // number there else j -= 1; } return count; } // Driver program to test above functions public static void main(String[] args) { int M[][] = { { -3, -2, -1, 1 }, { -2, 2, 3, 4 }, { 4, 5, 7, 8 } }; System.out.println(countNegative(M, 3, 4)); }}// This code is contributed by Chhavi # Python implementation of Efficient method to count of# negative numbers in M[n][m] def countNegative(M, n, m): count = 0 # initialize result # Start with top right corner i = 0 j = m - 1 # Follow the path shown using arrows above while j >= 0 and i < n: if M[i][j] < 0: # j is the index of the last negative number # in this row. So there must be ( j + 1 ) count += (j + 1) # negative numbers in this row. i += 1 else: # move to the left and see if we can # find a negative number there j -= 1 return count # Driver codeM = [ [-3, -2, -1, 1], [-2, 2, 3, 4], [4, 5, 7, 8] ]print(countNegative(M, 3, 4)) // C# implementation of Efficient// method to count of negative// numbers in M[n][m]using System; class GFG { // Function to count // negative number static int countNegative(int[, ] M, int n, int m) { // initialize result int count = 0; // Start with top right corner int i = 0; int j = m - 1; // Follow the path shown // using arrows above while (j >= 0 && i < n) { if (M[i, j] < 0) { // j is the index of the // last negative number // in this row. So there // must be ( j + 1 ) count += j + 1; // negative numbers in // this row. i += 1; } // move to the left and see // if we can find a negative // number there else j -= 1; } return count; } // Driver Code public static void Main() { int[, ] M = { { -3, -2, -1, 1 }, { -2, 2, 3, 4 }, { 4, 5, 7, 8 } }; Console.WriteLine(countNegative(M, 3, 4)); }} // This code is contributed by Sam007 <?php// PHP implementation of Efficient// method to count of negative numbers// in M[n][m] function countNegative( $M, $n, $m){ // initialize result $count = 0; // Start with top right corner $i = 0; $j = $m - 1; // Follow the path shown using // arrows above while( $j >= 0 and $i < $n ) { if( $M[$i][$j] < 0 ) { // j is the index of the // last negative number // in this row. So there // must be ( j+1 ) $count += $j + 1; // negative numbers in // this row. $i += 1; } // move to the left and see // if we can find a negative // number there else $j -= 1; } return $count;} // Driver Code $M = array(array(-3, -2, -1, 1), array(-2, 2, 3, 4), array(4, 5, 7, 8)); echo countNegative($M, 3, 4); return 0; // This code is contributed by anuj_67.?> <script> // Javascript implementation of Efficient // method to count of negative numbers // in M[n][m]q function countNegative(M, n, m) { // initialize result let count = 0; // Start with top right corner let i = 0; let j = m - 1; // Follow the path shown using // arrows above while (j >= 0 && i < n) { if (M[i][j] < 0) { // j is the index of the // last negative number // in this row. So there // must be ( j+1 ) count += j + 1; // negative numbers in // this row. i += 1; } // move to the left and see // if we can find a negative // number there else j -= 1; } return count; } let M = [ [ -3, -2, -1, 1 ], [ -2, 2, 3, 4 ], [ 4, 5, 7, 8 ] ]; document.write(countNegative(M, 3, 4)); ` // This code is contributed by decode2207.</script> Output: 4 With this solution, we can now solve this problem in O(n + m) time.More Optimal SolutionHere’s a more efficient solution using binary search instead of linear search: We start from the first row and find the position of the last negative number in the first row using binary search.Using this information, we find the position of the last negative number in the second row by running binary search only until the position of the last negative number in the row above.We keep repeating this process until we either run out of negative numbers or we get to the last row. We start from the first row and find the position of the last negative number in the first row using binary search. Using this information, we find the position of the last negative number in the second row by running binary search only until the position of the last negative number in the row above. We keep repeating this process until we either run out of negative numbers or we get to the last row. With the given example: [-3, -2, -1, 1] [-2, 2, 3, 4] [4, 5, 7, 8] Here's the idea: 1. Count is initialized to 0 2. Binary search on full 1st row returns 2 as the index of last negative integer, and we increase count to 0+(2+1) = 3. 3. For 2nd row, we run binary search from index 0 to index 2 and it returns 0 as the index of last negative integer. We increase the count to 3+(0+1) = 4; 4. For 3rd row, first element is > 0, so we end the loop here. C++ Java Python3 C# Javascript // C++ implementation of More efficient// method to count number of negative numbers// in row-column sorted matrix M[n][m]#include<bits/stdc++.h>using namespace std; // Recursive binary search to get last negative// value in a row between a start and an endint getLastNegativeIndex(int array[], int start, int end,int n){ // Base case if (start == end) { return start; } // Get the mid for binary search int mid = start + (end - start) / 2; // If current element is negative if (array[mid] < 0) { // If it is the rightmost negative // element in the current row if (mid + 1 < n && array[mid + 1] >= 0) { return mid; } // Check in the right half of the array return getLastNegativeIndex(array, mid + 1, end, n); } else { // Check in the left half of the array return getLastNegativeIndex(array, start, mid - 1, n); }} // Function to return the count of// negative numbers in the given matrixint countNegative(int M[][4], int n, int m){ // Initialize result int count = 0; // To store the index of the rightmost negative // element in the row under consideration int nextEnd = m - 1; // Iterate over all rows of the matrix for (int i = 0; i < n; i++) { // If the first element of the current row // is positive then there will be no negatives // in the matrix below or after it if (M[i][0] >= 0) { break; } // Run binary search only until the index of last // negative Integer in the above row nextEnd = getLastNegativeIndex(M[i], 0, nextEnd, 4); count += nextEnd + 1; } return count;} // Driver codeint main(){ int M[][4] = { { -3, -2, -1, 1 }, { -2, 2, 3, 4 }, { 4, 5, 7, 8 } }; int r = 3; int c = 4; cout << (countNegative(M, r, c)); return 0;} // This code is contributed by Arnab Kundu // Java implementation of More efficient// method to count number of negative numbers// in row-column sorted matrix M[n][m]import java.util.*;import java.lang.*;import java.io.*; class GFG { // Recursive binary search to get last negative // value in a row between a start and an end static int getLastNegativeIndex(int array[], int start, int end) { // Base case if (start == end) { return start; } // Get the mid for binary search int mid = start + (end - start) / 2; // If current element is negative if (array[mid] < 0) { // If it is the rightmost negative // element in the current row if (mid + 1 < array.length && array[mid + 1] >= 0) { return mid; } // Check in the right half of the array return getLastNegativeIndex(array, mid + 1, end); } else { // Check in the left half of the array return getLastNegativeIndex(array, start, mid - 1); } } // Function to return the count of // negative numbers in the given matrix static int countNegative(int M[][], int n, int m) { // Initialize result int count = 0; // To store the index of the rightmost negative // element in the row under consideration int nextEnd = m - 1; // Iterate over all rows of the matrix for (int i = 0; i < n; i++) { // If the first element of the current row // is positive then there will be no negatives // in the matrix below or after it if (M[i][0] >= 0) { break; } // Run binary search only until the index of last // negative Integer in the above row nextEnd = getLastNegativeIndex(M[i], 0, nextEnd); count += nextEnd + 1; } return count; } // Driver code public static void main(String[] args) { int M[][] = { { -3, -2, -1, 1 }, { -2, 2, 3, 4 }, { 4, 5, 7, 8 } }; int r = M.length; int c = M[0].length; System.out.println(countNegative(M, r, c)); }}// This code is contributed by Rahul Jain # Python3 implementation of More efficient# method to count number of negative numbers# in row-column sorted matrix M[n][m] # Recursive binary search to get last negative# value in a row between a start and an enddef getLastNegativeIndex(array, start, end, n): # Base case if (start == end): return start # Get the mid for binary search mid = start + (end - start) // 2 # If current element is negative if (array[mid] < 0): # If it is the rightmost negative # element in the current row if (mid + 1 < n and array[mid + 1] >= 0): return mid # Check in the right half of the array return getLastNegativeIndex(array, mid + 1, end, n) else: # Check in the left half of the array return getLastNegativeIndex(array, start, mid - 1, n) # Function to return the count of# negative numbers in the given matrixdef countNegative(M, n, m): # Initialize result count = 0 # To store the index of the rightmost negative # element in the row under consideration nextEnd = m - 1 # Iterate over all rows of the matrix for i in range(n): # If the first element of the current row # is positive then there will be no negatives # in the matrix below or after it if (M[i][0] >= 0): break # Run binary search only until the index of last # negative Integer in the above row nextEnd = getLastNegativeIndex(M[i], 0, nextEnd, 4) count += nextEnd + 1 return count # Driver code M = [[-3, -2, -1, 1],[-2, 2, 3, 4],[ 4, 5, 7, 8]]r = 3c = 4print(countNegative(M, r, c)) # This code is contributed by shubhamsingh10 // C# implementation of More efficient// method to count number of negative numbers// in row-column sorted matrix M[n,m]using System;using System.Collections.Generic; class GFG{ // Recursive binary search to get last negative // value in a row between a start and an end static int getLastNegativeIndex(int []array, int start, int end) { // Base case if (start == end) { return start; } // Get the mid for binary search int mid = start + (end - start) / 2; // If current element is negative if (array[mid] < 0) { // If it is the rightmost negative // element in the current row if (mid + 1 < array.GetLength(0) && array[mid + 1] >= 0) { return mid; } // Check in the right half of the array return getLastNegativeIndex(array, mid + 1, end); } else { // Check in the left half of the array return getLastNegativeIndex(array, start, mid - 1); } } // Function to return the count of // negative numbers in the given matrix static int countNegative(int [,]M, int n, int m) { // Initialize result int count = 0; // To store the index of the rightmost negative // element in the row under consideration int nextEnd = m - 1; // Iterate over all rows of the matrix for (int i = 0; i < n; i++) { // If the first element of the current row // is positive then there will be no negatives // in the matrix below or after it if (M[i, 0] >= 0) { break; } // Run binary search only until the index of last // negative int in the above row nextEnd = getLastNegativeIndex(GetRow(M, i), 0, nextEnd); count += nextEnd + 1; } return count; } public static int[] GetRow(int[,] matrix, int row) { var rowLength = matrix.GetLength(1); var rowVector = new int[rowLength]; for (var i = 0; i < rowLength; i++) rowVector[i] = matrix[row, i]; return rowVector; } // Driver code public static void Main(String[] args) { int [,]M = { { -3, -2, -1, 1 }, { -2, 2, 3, 4 }, { 4, 5, 7, 8 } }; int r = M.GetLength(0); int c = M.GetLength(1); Console.WriteLine(countNegative(M, r, c)); }} // This code is contributed by PrinciRaj1992 <script> // JavaScript implementation of More efficient// method to count number of negative numbers// in row-column sorted matrix M[n,m]// Recursive binary search to get last negative// value in a row between a start and an endfunction getLastNegativeIndex(array, start, end){ // Base case if (start == end) { return start; } // Get the mid for binary search var mid = start + parseInt((end - start) / 2); // If current element is negative if (array[mid] < 0) { // If it is the rightmost negative // element in the current row if (mid + 1 < array.length && array[mid + 1] >= 0) { return mid; } // Check in the right half of the array return getLastNegativeIndex(array, mid + 1, end); } else { // Check in the left half of the array return getLastNegativeIndex(array, start, mid - 1); }}// Function to return the count of// negative numbers in the given matrixfunction countNegative(M, n, m){ // Initialize result var count = 0; // To store the index of the rightmost negative // element in the row under consideration var nextEnd = m - 1; // Iterate over all rows of the matrix for (var i = 0; i < n; i++) { // If the first element of the current row // is positive then there will be no negatives // in the matrix below or after it if (M[i][0] >= 0) { break; } // Run binary search only until the index of last // negative int in the above row nextEnd = getLastNegativeIndex(GetRow(M, i), 0, nextEnd); count += nextEnd + 1; } return count;} function GetRow(matrix, row){ var rowLength = matrix[0].length; var rowVector = Array(rowLength).fill(0); for (var i = 0; i < rowLength; i++) rowVector[i] = matrix[row][i]; return rowVector;} // Driver codevar M = [ [ -3, -2, -1, 1 ], [ -2, 2, 3, 4 ], [ 4, 5, 7, 8 ] ];var r = M.length;var c = M[0].length;document.write(countNegative(M, r, c)); </script> Output: 4 Here we have replaced the linear search for last negative number with a binary search. This should improve the worst case scenario keeping the Worst case to O(nlog(m)).This article is contributed by YK Sugishita and Rahul Jain. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Sam007 vt_m xRahul princiraj1992 andrew1234 SHUBHAMSINGH10 bicky jaiswal sravankumar8128 decode2207 rrrtnx amartyaniel20 Amazon Matrix Python Amazon Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Divide and Conquer | Set 5 (Strassen's Matrix Multiplication) Program to multiply two matrices Inplace rotate square matrix by 90 degrees | Set 1 Min Cost Path | DP-6 Rotate a matrix by 90 degree in clockwise direction without using any extra space Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe
[ { "code": null, "e": 25196, "s": 25168, "text": "\n22 Jan, 2022" }, { "code": null, "e": 25326, "s": 25196, "text": "Find the number of negative numbers in a column-wise / row-wise sorted matrix M[][]. Suppose M has n rows and m columns.Example: " }, { "code": null, "e": 25469, "s": 25326, "text": "Input: M = [-3, -2, -1, 1]\n [-2, 2, 3, 4]\n [4, 5, 7, 8]\nOutput : 4\nWe have 4 negative numbers in this matrix" }, { "code": null, "e": 25749, "s": 25469, "text": "We strongly recommend you to minimize your browser and try this yourself first.Naive Solution Here’s a naive, non-optimal solution.We start from the top left corner and count the number of negative numbers one by one, from left to right and top to bottom.With the given example: " }, { "code": null, "e": 25869, "s": 25749, "text": "[-3, -2, -1, 1]\n[-2, 2, 3, 4]\n[4, 5, 7, 8]\n\nEvaluation process\n\n[?, ?, ?, 1]\n[?, 2, 3, 4]\n[4, 5, 7, 8]" }, { "code": null, "e": 25912, "s": 25869, "text": "Below is the implementation of above idea:" }, { "code": null, "e": 25916, "s": 25912, "text": "C++" }, { "code": null, "e": 25921, "s": 25916, "text": "Java" }, { "code": null, "e": 25929, "s": 25921, "text": "Python3" }, { "code": null, "e": 25932, "s": 25929, "text": "C#" }, { "code": null, "e": 25936, "s": 25932, "text": "PHP" }, { "code": null, "e": 25947, "s": 25936, "text": "Javascript" }, { "code": "// CPP implementation of Naive method// to count of negative numbers in// M[n][m]#include <bits/stdc++.h>using namespace std; int countNegative(int M[][4], int n, int m){ int count = 0; // Follow the path shown using // arrows above for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (M[i][j] < 0) count += 1; // no more negative numbers // in this row else break; } } return count;} // Driver program to test above functionsint main(){ int M[3][4] = { { -3, -2, -1, 1 }, { -2, 2, 3, 4 }, { 4, 5, 7, 8 } }; cout << countNegative(M, 3, 4); return 0;}// This code is contributed by Niteesh Kumar", "e": 26709, "s": 25947, "text": null }, { "code": "// Java implementation of Naive method// to count of negative numbers in// M[n][m]import java.util.*;import java.lang.*;import java.io.*; class GFG { static int countNegative(int M[][], int n, int m) { int count = 0; // Follow the path shown using // arrows above for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (M[i][j] < 0) count += 1; // no more negative numbers // in this row else break; } } return count; } // Driver program to test above functions public static void main(String[] args) { int M[][] = { { -3, -2, -1, 1 }, { -2, 2, 3, 4 }, { 4, 5, 7, 8 } }; System.out.println(countNegative(M, 3, 4)); }}// This code is contributed by Chhavi", "e": 27643, "s": 26709, "text": null }, { "code": "# Python implementation of Naive method to count of# negative numbers in M[n][m] def countNegative(M, n, m): count = 0 # Follow the path shown using arrows above for i in range(n): for j in range(m): if M[i][j] < 0: count += 1 else: # no more negative numbers in this row break return count # Driver codeM = [ [-3, -2, -1, 1], [-2, 2, 3, 4], [ 4, 5, 7, 8] ]print(countNegative(M, 3, 4))", "e": 28145, "s": 27643, "text": null }, { "code": "// C# implementation of Naive method// to count of negative numbers in// M[n][m]using System; class GFG { // Function to count // negative number static int countNegative(int[, ] M, int n, int m) { int count = 0; // Follow the path shown // using arrows above for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (M[i, j] < 0) count += 1; // no more negative numbers // in this row else break; } } return count; } // Driver Code public static void Main() { int[, ] M = { { -3, -2, -1, 1 }, { -2, 2, 3, 4 }, { 4, 5, 7, 8 } }; Console.WriteLine(countNegative(M, 3, 4)); }} // This code is contributed by Sam007", "e": 29042, "s": 28145, "text": null }, { "code": "<?php// PHP implementation of Naive method// to count of negative numbers in// M[n][m] function countNegative($M, $n, $m){ $count = 0; // Follow the path shown using // arrows above for( $i = 0; $i < $n; $i++) { for( $j = 0; $j < $m; $j++) { if( $M[$i][$j] < 0 ) $count += 1; // no more negative numbers // in this row else break; } } return $count;} // Driver Code $M = array(array(-3, -2, -1, 1), array(-2, 2, 3, 4), array(4, 5, 7, 8)); echo countNegative($M, 3, 4); // This code is contributed by anuj_67.?>", "e": 29726, "s": 29042, "text": null }, { "code": "<script> // JavaScript implementation of Naive method// to count of negative numbers in// M[n][m]function countNegative(M,n,m) { let count = 0; // Follow the path shown using // arrows above for (let i = 0; i < n; i++) { for (let j = 0; j < m; j++) { if (M[i][j] < 0) count += 1; // no more negative numbers // in this row else break; } } return count; } // Driver program to test above functions let M = [[ -3, -2, -1, 1 ], [ -2, 2, 3, 4 ], [ 4, 5, 7, 8 ]]; document.write(countNegative(M, 3, 4)); // This code is contributed by sravan kumar </script>", "e": 30517, "s": 29726, "text": null }, { "code": null, "e": 30526, "s": 30517, "text": "Output: " }, { "code": null, "e": 30528, "s": 30526, "text": "4" }, { "code": null, "e": 30753, "s": 30528, "text": "In this approach we are traversing through all the elements and therefore, in the worst case scenario (when all numbers are negative in the matrix), this takes O(n * m) time.Optimal SolutionHere’s a more efficient solution: " }, { "code": null, "e": 31048, "s": 30753, "text": "We start from the top right corner and find the position of the last negative number in the first row.Using this information, we find the position of the last negative number in the second row.We keep repeating this process until we either run out of negative numbers or we get to the last row." }, { "code": null, "e": 31151, "s": 31048, "text": "We start from the top right corner and find the position of the last negative number in the first row." }, { "code": null, "e": 31243, "s": 31151, "text": "Using this information, we find the position of the last negative number in the second row." }, { "code": null, "e": 31345, "s": 31243, "text": "We keep repeating this process until we either run out of negative numbers or we get to the last row." }, { "code": null, "e": 31604, "s": 31345, "text": "With the given example:\n[-3, -2, -1, 1]\n[-2, 2, 3, 4]\n[4, 5, 7, 8]\n\nHere's the idea:\n[-3, -2, ?, ?] -> Found 3 negative numbers in this row\n[ ?, ?, ?, 4] -> Found 1 negative number in this row\n[ ?, 5, 7, 8] -> No negative numbers in this row " }, { "code": null, "e": 31608, "s": 31604, "text": "C++" }, { "code": null, "e": 31613, "s": 31608, "text": "Java" }, { "code": null, "e": 31621, "s": 31613, "text": "Python3" }, { "code": null, "e": 31624, "s": 31621, "text": "C#" }, { "code": null, "e": 31628, "s": 31624, "text": "PHP" }, { "code": null, "e": 31639, "s": 31628, "text": "Javascript" }, { "code": "// CPP implementation of Efficient// method to count of negative numbers// in M[n][m]#include <bits/stdc++.h>using namespace std; int countNegative(int M[][4], int n, int m){ // initialize result int count = 0; // Start with top right corner int i = 0; int j = m - 1; // Follow the path shown using // arrows above while (j >= 0 && i < n) { if (M[i][j] < 0) { // j is the index of the // last negative number // in this row. So there // must be ( j+1 ) count += j + 1; // negative numbers in // this row. i += 1; } // move to the left and see // if we can find a negative // number there else j -= 1; } return count;} // Driver program to test above functionsint main(){ int M[3][4] = { { -3, -2, -1, 1 }, { -2, 2, 3, 4 }, { 4, 5, 7, 8 } }; cout << countNegative(M, 3, 4); return 0;}// This code is contributed by Niteesh Kumar", "e": 32692, "s": 31639, "text": null }, { "code": "// Java implementation of Efficient// method to count of negative numbers// in M[n][m]import java.util.*;import java.lang.*;import java.io.*; class GFG { static int countNegative(int M[][], int n, int m) { // initialize result int count = 0; // Start with top right corner int i = 0; int j = m - 1; // Follow the path shown using // arrows above while (j >= 0 && i < n) { if (M[i][j] < 0) { // j is the index of the // last negative number // in this row. So there // must be ( j+1 ) count += j + 1; // negative numbers in // this row. i += 1; } // move to the left and see // if we can find a negative // number there else j -= 1; } return count; } // Driver program to test above functions public static void main(String[] args) { int M[][] = { { -3, -2, -1, 1 }, { -2, 2, 3, 4 }, { 4, 5, 7, 8 } }; System.out.println(countNegative(M, 3, 4)); }}// This code is contributed by Chhavi", "e": 33959, "s": 32692, "text": null }, { "code": "# Python implementation of Efficient method to count of# negative numbers in M[n][m] def countNegative(M, n, m): count = 0 # initialize result # Start with top right corner i = 0 j = m - 1 # Follow the path shown using arrows above while j >= 0 and i < n: if M[i][j] < 0: # j is the index of the last negative number # in this row. So there must be ( j + 1 ) count += (j + 1) # negative numbers in this row. i += 1 else: # move to the left and see if we can # find a negative number there j -= 1 return count # Driver codeM = [ [-3, -2, -1, 1], [-2, 2, 3, 4], [4, 5, 7, 8] ]print(countNegative(M, 3, 4))", "e": 34722, "s": 33959, "text": null }, { "code": "// C# implementation of Efficient// method to count of negative// numbers in M[n][m]using System; class GFG { // Function to count // negative number static int countNegative(int[, ] M, int n, int m) { // initialize result int count = 0; // Start with top right corner int i = 0; int j = m - 1; // Follow the path shown // using arrows above while (j >= 0 && i < n) { if (M[i, j] < 0) { // j is the index of the // last negative number // in this row. So there // must be ( j + 1 ) count += j + 1; // negative numbers in // this row. i += 1; } // move to the left and see // if we can find a negative // number there else j -= 1; } return count; } // Driver Code public static void Main() { int[, ] M = { { -3, -2, -1, 1 }, { -2, 2, 3, 4 }, { 4, 5, 7, 8 } }; Console.WriteLine(countNegative(M, 3, 4)); }} // This code is contributed by Sam007", "e": 35955, "s": 34722, "text": null }, { "code": "<?php// PHP implementation of Efficient// method to count of negative numbers// in M[n][m] function countNegative( $M, $n, $m){ // initialize result $count = 0; // Start with top right corner $i = 0; $j = $m - 1; // Follow the path shown using // arrows above while( $j >= 0 and $i < $n ) { if( $M[$i][$j] < 0 ) { // j is the index of the // last negative number // in this row. So there // must be ( j+1 ) $count += $j + 1; // negative numbers in // this row. $i += 1; } // move to the left and see // if we can find a negative // number there else $j -= 1; } return $count;} // Driver Code $M = array(array(-3, -2, -1, 1), array(-2, 2, 3, 4), array(4, 5, 7, 8)); echo countNegative($M, 3, 4); return 0; // This code is contributed by anuj_67.?>", "e": 36952, "s": 35955, "text": null }, { "code": "<script> // Javascript implementation of Efficient // method to count of negative numbers // in M[n][m]q function countNegative(M, n, m) { // initialize result let count = 0; // Start with top right corner let i = 0; let j = m - 1; // Follow the path shown using // arrows above while (j >= 0 && i < n) { if (M[i][j] < 0) { // j is the index of the // last negative number // in this row. So there // must be ( j+1 ) count += j + 1; // negative numbers in // this row. i += 1; } // move to the left and see // if we can find a negative // number there else j -= 1; } return count; } let M = [ [ -3, -2, -1, 1 ], [ -2, 2, 3, 4 ], [ 4, 5, 7, 8 ] ]; document.write(countNegative(M, 3, 4)); ` // This code is contributed by decode2207.</script>", "e": 38071, "s": 36952, "text": null }, { "code": null, "e": 38080, "s": 38071, "text": "Output: " }, { "code": null, "e": 38082, "s": 38080, "text": "4" }, { "code": null, "e": 38250, "s": 38082, "text": "With this solution, we can now solve this problem in O(n + m) time.More Optimal SolutionHere’s a more efficient solution using binary search instead of linear search: " }, { "code": null, "e": 38652, "s": 38250, "text": "We start from the first row and find the position of the last negative number in the first row using binary search.Using this information, we find the position of the last negative number in the second row by running binary search only until the position of the last negative number in the row above.We keep repeating this process until we either run out of negative numbers or we get to the last row." }, { "code": null, "e": 38768, "s": 38652, "text": "We start from the first row and find the position of the last negative number in the first row using binary search." }, { "code": null, "e": 38954, "s": 38768, "text": "Using this information, we find the position of the last negative number in the second row by running binary search only until the position of the last negative number in the row above." }, { "code": null, "e": 39056, "s": 38954, "text": "We keep repeating this process until we either run out of negative numbers or we get to the last row." }, { "code": null, "e": 39528, "s": 39056, "text": "With the given example:\n[-3, -2, -1, 1]\n[-2, 2, 3, 4]\n[4, 5, 7, 8]\n\nHere's the idea:\n1. Count is initialized to 0\n2. Binary search on full 1st row returns 2 as the index \n of last negative integer, and we increase count to 0+(2+1) = 3.\n3. For 2nd row, we run binary search from index 0 to index 2 \n and it returns 0 as the index of last negative integer. \n We increase the count to 3+(0+1) = 4;\n4. For 3rd row, first element is > 0, so we end the loop here." }, { "code": null, "e": 39532, "s": 39528, "text": "C++" }, { "code": null, "e": 39537, "s": 39532, "text": "Java" }, { "code": null, "e": 39545, "s": 39537, "text": "Python3" }, { "code": null, "e": 39548, "s": 39545, "text": "C#" }, { "code": null, "e": 39559, "s": 39548, "text": "Javascript" }, { "code": "// C++ implementation of More efficient// method to count number of negative numbers// in row-column sorted matrix M[n][m]#include<bits/stdc++.h>using namespace std; // Recursive binary search to get last negative// value in a row between a start and an endint getLastNegativeIndex(int array[], int start, int end,int n){ // Base case if (start == end) { return start; } // Get the mid for binary search int mid = start + (end - start) / 2; // If current element is negative if (array[mid] < 0) { // If it is the rightmost negative // element in the current row if (mid + 1 < n && array[mid + 1] >= 0) { return mid; } // Check in the right half of the array return getLastNegativeIndex(array, mid + 1, end, n); } else { // Check in the left half of the array return getLastNegativeIndex(array, start, mid - 1, n); }} // Function to return the count of// negative numbers in the given matrixint countNegative(int M[][4], int n, int m){ // Initialize result int count = 0; // To store the index of the rightmost negative // element in the row under consideration int nextEnd = m - 1; // Iterate over all rows of the matrix for (int i = 0; i < n; i++) { // If the first element of the current row // is positive then there will be no negatives // in the matrix below or after it if (M[i][0] >= 0) { break; } // Run binary search only until the index of last // negative Integer in the above row nextEnd = getLastNegativeIndex(M[i], 0, nextEnd, 4); count += nextEnd + 1; } return count;} // Driver codeint main(){ int M[][4] = { { -3, -2, -1, 1 }, { -2, 2, 3, 4 }, { 4, 5, 7, 8 } }; int r = 3; int c = 4; cout << (countNegative(M, r, c)); return 0;} // This code is contributed by Arnab Kundu", "e": 41626, "s": 39559, "text": null }, { "code": "// Java implementation of More efficient// method to count number of negative numbers// in row-column sorted matrix M[n][m]import java.util.*;import java.lang.*;import java.io.*; class GFG { // Recursive binary search to get last negative // value in a row between a start and an end static int getLastNegativeIndex(int array[], int start, int end) { // Base case if (start == end) { return start; } // Get the mid for binary search int mid = start + (end - start) / 2; // If current element is negative if (array[mid] < 0) { // If it is the rightmost negative // element in the current row if (mid + 1 < array.length && array[mid + 1] >= 0) { return mid; } // Check in the right half of the array return getLastNegativeIndex(array, mid + 1, end); } else { // Check in the left half of the array return getLastNegativeIndex(array, start, mid - 1); } } // Function to return the count of // negative numbers in the given matrix static int countNegative(int M[][], int n, int m) { // Initialize result int count = 0; // To store the index of the rightmost negative // element in the row under consideration int nextEnd = m - 1; // Iterate over all rows of the matrix for (int i = 0; i < n; i++) { // If the first element of the current row // is positive then there will be no negatives // in the matrix below or after it if (M[i][0] >= 0) { break; } // Run binary search only until the index of last // negative Integer in the above row nextEnd = getLastNegativeIndex(M[i], 0, nextEnd); count += nextEnd + 1; } return count; } // Driver code public static void main(String[] args) { int M[][] = { { -3, -2, -1, 1 }, { -2, 2, 3, 4 }, { 4, 5, 7, 8 } }; int r = M.length; int c = M[0].length; System.out.println(countNegative(M, r, c)); }}// This code is contributed by Rahul Jain", "e": 43889, "s": 41626, "text": null }, { "code": "# Python3 implementation of More efficient# method to count number of negative numbers# in row-column sorted matrix M[n][m] # Recursive binary search to get last negative# value in a row between a start and an enddef getLastNegativeIndex(array, start, end, n): # Base case if (start == end): return start # Get the mid for binary search mid = start + (end - start) // 2 # If current element is negative if (array[mid] < 0): # If it is the rightmost negative # element in the current row if (mid + 1 < n and array[mid + 1] >= 0): return mid # Check in the right half of the array return getLastNegativeIndex(array, mid + 1, end, n) else: # Check in the left half of the array return getLastNegativeIndex(array, start, mid - 1, n) # Function to return the count of# negative numbers in the given matrixdef countNegative(M, n, m): # Initialize result count = 0 # To store the index of the rightmost negative # element in the row under consideration nextEnd = m - 1 # Iterate over all rows of the matrix for i in range(n): # If the first element of the current row # is positive then there will be no negatives # in the matrix below or after it if (M[i][0] >= 0): break # Run binary search only until the index of last # negative Integer in the above row nextEnd = getLastNegativeIndex(M[i], 0, nextEnd, 4) count += nextEnd + 1 return count # Driver code M = [[-3, -2, -1, 1],[-2, 2, 3, 4],[ 4, 5, 7, 8]]r = 3c = 4print(countNegative(M, r, c)) # This code is contributed by shubhamsingh10", "e": 45650, "s": 43889, "text": null }, { "code": "// C# implementation of More efficient// method to count number of negative numbers// in row-column sorted matrix M[n,m]using System;using System.Collections.Generic; class GFG{ // Recursive binary search to get last negative // value in a row between a start and an end static int getLastNegativeIndex(int []array, int start, int end) { // Base case if (start == end) { return start; } // Get the mid for binary search int mid = start + (end - start) / 2; // If current element is negative if (array[mid] < 0) { // If it is the rightmost negative // element in the current row if (mid + 1 < array.GetLength(0) && array[mid + 1] >= 0) { return mid; } // Check in the right half of the array return getLastNegativeIndex(array, mid + 1, end); } else { // Check in the left half of the array return getLastNegativeIndex(array, start, mid - 1); } } // Function to return the count of // negative numbers in the given matrix static int countNegative(int [,]M, int n, int m) { // Initialize result int count = 0; // To store the index of the rightmost negative // element in the row under consideration int nextEnd = m - 1; // Iterate over all rows of the matrix for (int i = 0; i < n; i++) { // If the first element of the current row // is positive then there will be no negatives // in the matrix below or after it if (M[i, 0] >= 0) { break; } // Run binary search only until the index of last // negative int in the above row nextEnd = getLastNegativeIndex(GetRow(M, i), 0, nextEnd); count += nextEnd + 1; } return count; } public static int[] GetRow(int[,] matrix, int row) { var rowLength = matrix.GetLength(1); var rowVector = new int[rowLength]; for (var i = 0; i < rowLength; i++) rowVector[i] = matrix[row, i]; return rowVector; } // Driver code public static void Main(String[] args) { int [,]M = { { -3, -2, -1, 1 }, { -2, 2, 3, 4 }, { 4, 5, 7, 8 } }; int r = M.GetLength(0); int c = M.GetLength(1); Console.WriteLine(countNegative(M, r, c)); }} // This code is contributed by PrinciRaj1992", "e": 48233, "s": 45650, "text": null }, { "code": "<script> // JavaScript implementation of More efficient// method to count number of negative numbers// in row-column sorted matrix M[n,m]// Recursive binary search to get last negative// value in a row between a start and an endfunction getLastNegativeIndex(array, start, end){ // Base case if (start == end) { return start; } // Get the mid for binary search var mid = start + parseInt((end - start) / 2); // If current element is negative if (array[mid] < 0) { // If it is the rightmost negative // element in the current row if (mid + 1 < array.length && array[mid + 1] >= 0) { return mid; } // Check in the right half of the array return getLastNegativeIndex(array, mid + 1, end); } else { // Check in the left half of the array return getLastNegativeIndex(array, start, mid - 1); }}// Function to return the count of// negative numbers in the given matrixfunction countNegative(M, n, m){ // Initialize result var count = 0; // To store the index of the rightmost negative // element in the row under consideration var nextEnd = m - 1; // Iterate over all rows of the matrix for (var i = 0; i < n; i++) { // If the first element of the current row // is positive then there will be no negatives // in the matrix below or after it if (M[i][0] >= 0) { break; } // Run binary search only until the index of last // negative int in the above row nextEnd = getLastNegativeIndex(GetRow(M, i), 0, nextEnd); count += nextEnd + 1; } return count;} function GetRow(matrix, row){ var rowLength = matrix[0].length; var rowVector = Array(rowLength).fill(0); for (var i = 0; i < rowLength; i++) rowVector[i] = matrix[row][i]; return rowVector;} // Driver codevar M = [ [ -3, -2, -1, 1 ], [ -2, 2, 3, 4 ], [ 4, 5, 7, 8 ] ];var r = M.length;var c = M[0].length;document.write(countNegative(M, r, c)); </script>", "e": 50304, "s": 48233, "text": null }, { "code": null, "e": 50313, "s": 50304, "text": "Output: " }, { "code": null, "e": 50315, "s": 50313, "text": "4" }, { "code": null, "e": 50765, "s": 50315, "text": "Here we have replaced the linear search for last negative number with a binary search. This should improve the worst case scenario keeping the Worst case to O(nlog(m)).This article is contributed by YK Sugishita and Rahul Jain. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 50890, "s": 50765, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 50897, "s": 50890, "text": "Sam007" }, { "code": null, "e": 50902, "s": 50897, "text": "vt_m" }, { "code": null, "e": 50909, "s": 50902, "text": "xRahul" }, { "code": null, "e": 50923, "s": 50909, "text": "princiraj1992" }, { "code": null, "e": 50934, "s": 50923, "text": "andrew1234" }, { "code": null, "e": 50949, "s": 50934, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 50963, "s": 50949, "text": "bicky jaiswal" }, { "code": null, "e": 50979, "s": 50963, "text": "sravankumar8128" }, { "code": null, "e": 50990, "s": 50979, "text": "decode2207" }, { "code": null, "e": 50997, "s": 50990, "text": "rrrtnx" }, { "code": null, "e": 51011, "s": 50997, "text": "amartyaniel20" }, { "code": null, "e": 51018, "s": 51011, "text": "Amazon" }, { "code": null, "e": 51025, "s": 51018, "text": "Matrix" }, { "code": null, "e": 51032, "s": 51025, "text": "Python" }, { "code": null, "e": 51039, "s": 51032, "text": "Amazon" }, { "code": null, "e": 51046, "s": 51039, "text": "Matrix" }, { "code": null, "e": 51144, "s": 51046, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 51206, "s": 51144, "text": "Divide and Conquer | Set 5 (Strassen's Matrix Multiplication)" }, { "code": null, "e": 51239, "s": 51206, "text": "Program to multiply two matrices" }, { "code": null, "e": 51290, "s": 51239, "text": "Inplace rotate square matrix by 90 degrees | Set 1" }, { "code": null, "e": 51311, "s": 51290, "text": "Min Cost Path | DP-6" }, { "code": null, "e": 51393, "s": 51311, "text": "Rotate a matrix by 90 degree in clockwise direction without using any extra space" }, { "code": null, "e": 51421, "s": 51393, "text": "Read JSON file using Python" }, { "code": null, "e": 51471, "s": 51421, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 51493, "s": 51471, "text": "Python map() function" } ]
Managing Instance Attributes in Python | by Sadrach Pierre, Ph.D. | Towards Data Science
Often times in the implementation of a python class, it would be useful if we could easily add extra processing to getting and/or setting an instance attribute. For example, it would be useful to be able to perform type checking or some other form of validating during getting/setting instance attributes. In this post, we will discuss how to manage instance attributes in python. Let’s get started! Suppose we have a class called ‘Cars’ with an attribute called ‘car_brand’: class Car: def __init__(self, car_brand): self.car_brand = car_brand Let’s initialize a car class instance as a ‘Tesla’: car1 = Car('Tesla')print("Car brand:", car1.car_brand) While this works fine, if we initialize an instance with a bad input value for ‘car_brand’, there is no data validation or type checking. For example, if we initialize a car instance with a car brand value of the number 500: car2 = Car(500)print("Car brand:", car2.car_brand) we should have a way of validating the type of this instance attribute. We can customize access to attributes by defining the ‘car_brand’ attribute as a ‘property’: class Car: ... @property def car_brand(self): return self._car_brand Defining ‘car_brand’ as a ‘property’ allows us to attach setter and deleter functions to our ‘car_brand’ property. Let’s add a setter method to our ‘car_brand’ attribute that raises an error if the instance is initialized with a value that is not a string: class Car: ... #setter function @car_brand.setter def car_brand(self, value): if not isinstance(value, str): raise TypeError('Expected a string') self._car_brand = value Let’s define our instance again, with our integer input 500: car2 = Car(500)print("Car brand:", car2.car_brand) Another instance management operation to consider is the deletion of instance attributes. If we look at our initial instance: car1 = Car('Tesla')print("Car brand:", car1.car_brand) We can easily delete the attribute value: car1 = Car('Tesla')print("Car brand:", car1.car_brand)del car1.car_brandprint("Car brand:", car1.car_brand) We can add a deleter function that raises an error upon attempted deletion: class Car: ... #deleter function @car_brand.deleter def car_brand(self): raise AttributeError("Can't delete attribute") Let’s try to set and delete the attribute value once again: car1 = Car('Tesla')print("Car brand:", car1.car_brand)del car1.car_brand I’ll stop here but feel free to play around with the code yourself. To summarize, in this post we discussed how to manage instance attributes in python classes. We showed that by defining a class attribute as a ‘property’ we can attach setter and deleter functions that help us manage the access of attributes. I hope you found this post useful/interesting. The code from this post is available on GitHub. Thank you for reading!
[ { "code": null, "e": 553, "s": 172, "text": "Often times in the implementation of a python class, it would be useful if we could easily add extra processing to getting and/or setting an instance attribute. For example, it would be useful to be able to perform type checking or some other form of validating during getting/setting instance attributes. In this post, we will discuss how to manage instance attributes in python." }, { "code": null, "e": 572, "s": 553, "text": "Let’s get started!" }, { "code": null, "e": 648, "s": 572, "text": "Suppose we have a class called ‘Cars’ with an attribute called ‘car_brand’:" }, { "code": null, "e": 726, "s": 648, "text": "class Car: def __init__(self, car_brand): self.car_brand = car_brand" }, { "code": null, "e": 778, "s": 726, "text": "Let’s initialize a car class instance as a ‘Tesla’:" }, { "code": null, "e": 833, "s": 778, "text": "car1 = Car('Tesla')print(\"Car brand:\", car1.car_brand)" }, { "code": null, "e": 1058, "s": 833, "text": "While this works fine, if we initialize an instance with a bad input value for ‘car_brand’, there is no data validation or type checking. For example, if we initialize a car instance with a car brand value of the number 500:" }, { "code": null, "e": 1109, "s": 1058, "text": "car2 = Car(500)print(\"Car brand:\", car2.car_brand)" }, { "code": null, "e": 1274, "s": 1109, "text": "we should have a way of validating the type of this instance attribute. We can customize access to attributes by defining the ‘car_brand’ attribute as a ‘property’:" }, { "code": null, "e": 1359, "s": 1274, "text": "class Car: ... @property def car_brand(self): return self._car_brand" }, { "code": null, "e": 1616, "s": 1359, "text": "Defining ‘car_brand’ as a ‘property’ allows us to attach setter and deleter functions to our ‘car_brand’ property. Let’s add a setter method to our ‘car_brand’ attribute that raises an error if the instance is initialized with a value that is not a string:" }, { "code": null, "e": 1823, "s": 1616, "text": "class Car: ... #setter function @car_brand.setter def car_brand(self, value): if not isinstance(value, str): raise TypeError('Expected a string') self._car_brand = value" }, { "code": null, "e": 1884, "s": 1823, "text": "Let’s define our instance again, with our integer input 500:" }, { "code": null, "e": 1935, "s": 1884, "text": "car2 = Car(500)print(\"Car brand:\", car2.car_brand)" }, { "code": null, "e": 2061, "s": 1935, "text": "Another instance management operation to consider is the deletion of instance attributes. If we look at our initial instance:" }, { "code": null, "e": 2116, "s": 2061, "text": "car1 = Car('Tesla')print(\"Car brand:\", car1.car_brand)" }, { "code": null, "e": 2158, "s": 2116, "text": "We can easily delete the attribute value:" }, { "code": null, "e": 2266, "s": 2158, "text": "car1 = Car('Tesla')print(\"Car brand:\", car1.car_brand)del car1.car_brandprint(\"Car brand:\", car1.car_brand)" }, { "code": null, "e": 2342, "s": 2266, "text": "We can add a deleter function that raises an error upon attempted deletion:" }, { "code": null, "e": 2481, "s": 2342, "text": "class Car: ... #deleter function @car_brand.deleter def car_brand(self): raise AttributeError(\"Can't delete attribute\")" }, { "code": null, "e": 2541, "s": 2481, "text": "Let’s try to set and delete the attribute value once again:" }, { "code": null, "e": 2614, "s": 2541, "text": "car1 = Car('Tesla')print(\"Car brand:\", car1.car_brand)del car1.car_brand" }, { "code": null, "e": 2682, "s": 2614, "text": "I’ll stop here but feel free to play around with the code yourself." } ]
What is type conversion in java?
Java provides various datatypes to store various data values. It provides 7 primitive datatypes (stores single values) as listed below − boolean − Stores 1-bit value representing true or, false. byte − Stores twos compliment integer up to 8 bits. char − Stores a Unicode character value up to 16 bits. short − Stores an integer value upto 16 bits. int − Stores an integer value upto 32 bits. long − Stores an integer value upto 64 bits. float − Stores a floating point value upto 32bits. double − Stores a floating point value up to 64 bits. Converting one primitive datatype into another is known as type casting (type conversion) in Java. You can cast the primitive datatypes in two ways namely, Widening and, Narrowing. Widening − Converting a lower datatype to a higher datatype is known as widening. In this case the casting/conversion is done automatically therefore, it is known as implicit type casting. In this case both datatypes should be compatible with each other. public class WideningExample { public static void main(String args[]){ char ch = 'C'; int i = ch; System.out.println(i); } } Integer value of the given character: 67 Narrowing − Converting a higher datatype to a lower datatype is known as narrowing. In this case the casting/conversion is not done automatically, you need to convert explicitly using the cast operator “( )” explicitly. Therefore, it is known as explicit type casting. In this case both datatypes need not be compatible with each other. import java.util.Scanner; public class NarrowingExample { public static void main(String args[]){ Scanner sc = new Scanner(System.in); System.out.println("Enter an integer value: "); int i = sc.nextInt(); char ch = (char) i; System.out.println("Character value of the given integer: "+ch); } } Enter an integer value: 67 Character value of the given integer: C
[ { "code": null, "e": 1199, "s": 1062, "text": "Java provides various datatypes to store various data values. It provides 7 primitive datatypes (stores single values) as listed below −" }, { "code": null, "e": 1257, "s": 1199, "text": "boolean − Stores 1-bit value representing true or, false." }, { "code": null, "e": 1309, "s": 1257, "text": "byte − Stores twos compliment integer up to 8 bits." }, { "code": null, "e": 1364, "s": 1309, "text": "char − Stores a Unicode character value up to 16 bits." }, { "code": null, "e": 1410, "s": 1364, "text": "short − Stores an integer value upto 16 bits." }, { "code": null, "e": 1454, "s": 1410, "text": "int − Stores an integer value upto 32 bits." }, { "code": null, "e": 1499, "s": 1454, "text": "long − Stores an integer value upto 64 bits." }, { "code": null, "e": 1550, "s": 1499, "text": "float − Stores a floating point value upto 32bits." }, { "code": null, "e": 1604, "s": 1550, "text": "double − Stores a floating point value up to 64 bits." }, { "code": null, "e": 1785, "s": 1604, "text": "Converting one primitive datatype into another is known as type casting (type conversion) in Java. You can cast the primitive datatypes in two ways namely, Widening and, Narrowing." }, { "code": null, "e": 2040, "s": 1785, "text": "Widening − Converting a lower datatype to a higher datatype is known as widening. In this case the casting/conversion is done automatically therefore, it is known as implicit type casting. In this case both datatypes should be compatible with each other." }, { "code": null, "e": 2189, "s": 2040, "text": "public class WideningExample {\n public static void main(String args[]){\n char ch = 'C';\n int i = ch;\n System.out.println(i);\n }\n}" }, { "code": null, "e": 2230, "s": 2189, "text": "Integer value of the given character: 67" }, { "code": null, "e": 2567, "s": 2230, "text": "Narrowing − Converting a higher datatype to a lower datatype is known as narrowing. In this case the casting/conversion is not done automatically, you need to convert explicitly using the cast operator “( )” explicitly. Therefore, it is known as explicit type casting. In this case both datatypes need not be compatible with each other." }, { "code": null, "e": 2897, "s": 2567, "text": "import java.util.Scanner;\npublic class NarrowingExample {\n public static void main(String args[]){\n Scanner sc = new Scanner(System.in);\n System.out.println(\"Enter an integer value: \");\n int i = sc.nextInt();\n char ch = (char) i;\n System.out.println(\"Character value of the given integer: \"+ch);\n }\n}" }, { "code": null, "e": 2964, "s": 2897, "text": "Enter an integer value:\n67\nCharacter value of the given integer: C" } ]
Concatenate Vector of Character Strings in R - GeeksforGeeks
16 Jun, 2021 In this article, we will discuss how to concatenate the strings present in two or more vectors in R Programming Language. Discussed below are various methods of doing so. paste() function is used to combine strings present in vectors passed to it an argument. Syntax: paste(vector1,vector2,.,vector n,sep=”symbol”) Parameter: vectors are the input vectors to be concatenate sep is the separator symbol that separates the strings present in the vector. Example 1: R # create a vector with character# strings(names)a=c("manoj","sravan","harsha") # create a vector with character# strings (address)b=c("vijayawada","ponnur","hyd") # concatenate these two vectors# using paste functionprint(paste(a,b,sep="--")) Output: [1] “manoj–vijayawada” “sravan–ponnur” “harsha–hyd” Example 2: R # create a vector with character# strings(names)a=c("manoj","sravan","harsha") # create a vector with character# strings (address)b=c("vijayawada","ponnur","hyd") # create a vector with character# strings(subjects)d=c("java",".net","python") # create a vector with character# strings (college)e=c("iit","srm-ap","vignan") # create a vector with character# strings(department)f=c("cse","food tech","ece") # concatenate these five vectors# using paste functionprint(paste(a,b,d,e,f,sep="--")) Output: [1] "manoj--vijayawada--java--iit--cse" [2] "sravan--ponnur--.net--srm-ap--food tech" [3] "harsha--hyd--python--vignan--ece" Without a separator, the vectors will combine without any space or any symbol. Example 3: R # create a vector with character# strings(names)a=c("manoj","sravan","harsha") # create a vector with character# strings (address)b=c("vijayawada","ponnur","hyd") # create a vector with character# strings(subjects)d=c("java",".net","python") # create a vector with character# strings (college)e=c("iit","srm-ap","vignan") # create a vector with character# strings(department)f=c("cse","food tech","ece") # concatenate these five vectors# using paste functionprint(paste(a,b,d,e,f)) Output: [1] “manoj vijayawada java iit cse” “sravan ponnur .net srm-ap food tech” [3] “harsha hyd python vignan ece” cbind() function is used to combine the vectors column-wise i.e. it places the first vector in the first column and second vector in column 2 and so on. Syntax: cbind(x1, x2, ..., deparse.level = 1) Parameters:x1, x2: vector, matrix, data framesdeparse.level: This value determines how the column names generated. The default value of deparse.level is 1. Example: R # create a vector with character# strings(names)a=c("manoj","sravan","harsha") # create a vector with character# strings (address)b=c("vijayawada","ponnur","hyd") # create a vector with character# strings(subjects)d=c("java",".net","python") # create a vector with character# strings (college)e=c("iit","srm-ap","vignan") # create a vector with character# strings(department)f=c("cse","food tech","ece") # concatenate these five vectors# using cbind functionprint(cbind(a,b,d,e,f)) Output: a b d e f [1,] “manoj” “vijayawada” “java” “iit” “cse” [2,] “sravan” “ponnur” “.net” “srm-ap” “food tech” [3,] “harsha” “hyd” “python” “vignan” “ece” rbind() concatenates the strings of vectors row-wise i.e. row 1 is for vector 1, row2 is vector 2, and so on. Syntax: rbind(x1, x2, ..., deparse.level = 1) Parameters:x1, x2: vector, matrix, data framesdeparse.level: This value determines how the column names generated. The default value of deparse.level is 1. Example: R # create a vector with character# strings(names)a=c("manoj","sravan","harsha") # create a vector with character# strings (address)b=c("vijayawada","ponnur","hyd") # create a vector with character# strings(subjects)d=c("java",".net","python") # create a vector with character# strings (college)e=c("iit","srm-ap","vignan") # create a vector with character# strings(department)f=c("cse","food tech","ece") # concatenate these five vectors# using rbind functionprint(rbind(a,b,d,e,f)) Output: [,1] [,2] [,3] a "manoj" "sravan" "harsha" b "vijayawada" "ponnur" "hyd" d "java" ".net" "python" e "iit" "srm-ap" "vignan" f "cse" "food tech" "ece" cat() function is used to concatenate the given vectors. Syntax: cat(vector1,vector2,.,vector n) Where, the vector is the input vector It results in a one-dimensional vector with the last value as NULL Example 1: R # create a vector with character# strings(names)a=c("manoj","sravan","harsha") # create a vector with character# strings (address)b=c("vijayawada","ponnur","hyd") # concatenate these two vectors# using cat functionprint(cat(a,b)) Output: manoj sravan harsha vijayawada ponnur hydNULL Example 2: R # create a vector with character# strings(names)a=c("manoj","sravan","harsha") # create a vector with character# strings (address)b=c("vijayawada","ponnur","hyd") # create a vector with numeric datad=c(1,2,3,4,5) # create a vector with numeric datae=c(1.6,2.2,3.78,4.4456,5.4) # concatenate these four vectors using# cat functionprint(cat(a,b,d,e)) Output: manoj sravan harsha vijayawada ponnur hyd 1 2 3 4 5 1.6 2.2 3.78 4.4456 5.4NULL adnanirshad158 Picked R Vector-Programs R-Vectors R Language R Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Change Color of Bars in Barchart using ggplot2 in R How to Change Axis Scales in R Plots? Group by function in R using Dplyr How to Split Column Into Multiple Columns in R DataFrame? How to filter R DataFrame by values in a column? How to Split Column Into Multiple Columns in R DataFrame? How to filter R DataFrame by values in a column? Replace Specific Characters in String in R How to filter R dataframe by multiple conditions? Convert Matrix to Dataframe in R
[ { "code": null, "e": 24851, "s": 24823, "text": "\n16 Jun, 2021" }, { "code": null, "e": 24974, "s": 24851, "text": "In this article, we will discuss how to concatenate the strings present in two or more vectors in R Programming Language. " }, { "code": null, "e": 25023, "s": 24974, "text": "Discussed below are various methods of doing so." }, { "code": null, "e": 25113, "s": 25023, "text": "paste() function is used to combine strings present in vectors passed to it an argument." }, { "code": null, "e": 25168, "s": 25113, "text": "Syntax: paste(vector1,vector2,.,vector n,sep=”symbol”)" }, { "code": null, "e": 25179, "s": 25168, "text": "Parameter:" }, { "code": null, "e": 25227, "s": 25179, "text": "vectors are the input vectors to be concatenate" }, { "code": null, "e": 25305, "s": 25227, "text": "sep is the separator symbol that separates the strings present in the vector." }, { "code": null, "e": 25316, "s": 25305, "text": "Example 1:" }, { "code": null, "e": 25318, "s": 25316, "text": "R" }, { "code": "# create a vector with character# strings(names)a=c(\"manoj\",\"sravan\",\"harsha\") # create a vector with character# strings (address)b=c(\"vijayawada\",\"ponnur\",\"hyd\") # concatenate these two vectors# using paste functionprint(paste(a,b,sep=\"--\"))", "e": 25561, "s": 25318, "text": null }, { "code": null, "e": 25569, "s": 25561, "text": "Output:" }, { "code": null, "e": 25625, "s": 25569, "text": "[1] “manoj–vijayawada” “sravan–ponnur” “harsha–hyd” " }, { "code": null, "e": 25636, "s": 25625, "text": "Example 2:" }, { "code": null, "e": 25638, "s": 25636, "text": "R" }, { "code": "# create a vector with character# strings(names)a=c(\"manoj\",\"sravan\",\"harsha\") # create a vector with character# strings (address)b=c(\"vijayawada\",\"ponnur\",\"hyd\") # create a vector with character# strings(subjects)d=c(\"java\",\".net\",\"python\") # create a vector with character# strings (college)e=c(\"iit\",\"srm-ap\",\"vignan\") # create a vector with character# strings(department)f=c(\"cse\",\"food tech\",\"ece\") # concatenate these five vectors# using paste functionprint(paste(a,b,d,e,f,sep=\"--\"))", "e": 26129, "s": 25638, "text": null }, { "code": null, "e": 26137, "s": 26129, "text": "Output:" }, { "code": null, "e": 26275, "s": 26137, "text": "[1] \"manoj--vijayawada--java--iit--cse\" \n[2] \"sravan--ponnur--.net--srm-ap--food tech\"\n[3] \"harsha--hyd--python--vignan--ece\" " }, { "code": null, "e": 26354, "s": 26275, "text": "Without a separator, the vectors will combine without any space or any symbol." }, { "code": null, "e": 26365, "s": 26354, "text": "Example 3:" }, { "code": null, "e": 26367, "s": 26365, "text": "R" }, { "code": "# create a vector with character# strings(names)a=c(\"manoj\",\"sravan\",\"harsha\") # create a vector with character# strings (address)b=c(\"vijayawada\",\"ponnur\",\"hyd\") # create a vector with character# strings(subjects)d=c(\"java\",\".net\",\"python\") # create a vector with character# strings (college)e=c(\"iit\",\"srm-ap\",\"vignan\") # create a vector with character# strings(department)f=c(\"cse\",\"food tech\",\"ece\") # concatenate these five vectors# using paste functionprint(paste(a,b,d,e,f))", "e": 26849, "s": 26367, "text": null }, { "code": null, "e": 26857, "s": 26849, "text": "Output:" }, { "code": null, "e": 26937, "s": 26857, "text": "[1] “manoj vijayawada java iit cse” “sravan ponnur .net srm-ap food tech”" }, { "code": null, "e": 26976, "s": 26937, "text": "[3] “harsha hyd python vignan ece” " }, { "code": null, "e": 27129, "s": 26976, "text": "cbind() function is used to combine the vectors column-wise i.e. it places the first vector in the first column and second vector in column 2 and so on." }, { "code": null, "e": 27175, "s": 27129, "text": "Syntax: cbind(x1, x2, ..., deparse.level = 1)" }, { "code": null, "e": 27331, "s": 27175, "text": "Parameters:x1, x2: vector, matrix, data framesdeparse.level: This value determines how the column names generated. The default value of deparse.level is 1." }, { "code": null, "e": 27340, "s": 27331, "text": "Example:" }, { "code": null, "e": 27342, "s": 27340, "text": "R" }, { "code": "# create a vector with character# strings(names)a=c(\"manoj\",\"sravan\",\"harsha\") # create a vector with character# strings (address)b=c(\"vijayawada\",\"ponnur\",\"hyd\") # create a vector with character# strings(subjects)d=c(\"java\",\".net\",\"python\") # create a vector with character# strings (college)e=c(\"iit\",\"srm-ap\",\"vignan\") # create a vector with character# strings(department)f=c(\"cse\",\"food tech\",\"ece\") # concatenate these five vectors# using cbind functionprint(cbind(a,b,d,e,f))", "e": 27824, "s": 27342, "text": null }, { "code": null, "e": 27832, "s": 27824, "text": "Output:" }, { "code": null, "e": 27906, "s": 27832, "text": " a b d e f " }, { "code": null, "e": 27963, "s": 27906, "text": "[1,] “manoj” “vijayawada” “java” “iit” “cse” " }, { "code": null, "e": 28020, "s": 27963, "text": "[2,] “sravan” “ponnur” “.net” “srm-ap” “food tech”" }, { "code": null, "e": 28077, "s": 28020, "text": "[3,] “harsha” “hyd” “python” “vignan” “ece” " }, { "code": null, "e": 28187, "s": 28077, "text": "rbind() concatenates the strings of vectors row-wise i.e. row 1 is for vector 1, row2 is vector 2, and so on." }, { "code": null, "e": 28233, "s": 28187, "text": "Syntax: rbind(x1, x2, ..., deparse.level = 1)" }, { "code": null, "e": 28389, "s": 28233, "text": "Parameters:x1, x2: vector, matrix, data framesdeparse.level: This value determines how the column names generated. The default value of deparse.level is 1." }, { "code": null, "e": 28398, "s": 28389, "text": "Example:" }, { "code": null, "e": 28400, "s": 28398, "text": "R" }, { "code": "# create a vector with character# strings(names)a=c(\"manoj\",\"sravan\",\"harsha\") # create a vector with character# strings (address)b=c(\"vijayawada\",\"ponnur\",\"hyd\") # create a vector with character# strings(subjects)d=c(\"java\",\".net\",\"python\") # create a vector with character# strings (college)e=c(\"iit\",\"srm-ap\",\"vignan\") # create a vector with character# strings(department)f=c(\"cse\",\"food tech\",\"ece\") # concatenate these five vectors# using rbind functionprint(rbind(a,b,d,e,f))", "e": 28882, "s": 28400, "text": null }, { "code": null, "e": 28890, "s": 28882, "text": "Output:" }, { "code": null, "e": 29106, "s": 28890, "text": " [,1] [,2] [,3] \na \"manoj\" \"sravan\" \"harsha\"\nb \"vijayawada\" \"ponnur\" \"hyd\" \nd \"java\" \".net\" \"python\"\ne \"iit\" \"srm-ap\" \"vignan\"\nf \"cse\" \"food tech\" \"ece\" " }, { "code": null, "e": 29163, "s": 29106, "text": "cat() function is used to concatenate the given vectors." }, { "code": null, "e": 29171, "s": 29163, "text": "Syntax:" }, { "code": null, "e": 29203, "s": 29171, "text": "cat(vector1,vector2,.,vector n)" }, { "code": null, "e": 29241, "s": 29203, "text": "Where, the vector is the input vector" }, { "code": null, "e": 29308, "s": 29241, "text": "It results in a one-dimensional vector with the last value as NULL" }, { "code": null, "e": 29319, "s": 29308, "text": "Example 1:" }, { "code": null, "e": 29321, "s": 29319, "text": "R" }, { "code": "# create a vector with character# strings(names)a=c(\"manoj\",\"sravan\",\"harsha\") # create a vector with character# strings (address)b=c(\"vijayawada\",\"ponnur\",\"hyd\") # concatenate these two vectors# using cat functionprint(cat(a,b))", "e": 29551, "s": 29321, "text": null }, { "code": null, "e": 29559, "s": 29551, "text": "Output:" }, { "code": null, "e": 29605, "s": 29559, "text": "manoj sravan harsha vijayawada ponnur hydNULL" }, { "code": null, "e": 29616, "s": 29605, "text": "Example 2:" }, { "code": null, "e": 29618, "s": 29616, "text": "R" }, { "code": "# create a vector with character# strings(names)a=c(\"manoj\",\"sravan\",\"harsha\") # create a vector with character# strings (address)b=c(\"vijayawada\",\"ponnur\",\"hyd\") # create a vector with numeric datad=c(1,2,3,4,5) # create a vector with numeric datae=c(1.6,2.2,3.78,4.4456,5.4) # concatenate these four vectors using# cat functionprint(cat(a,b,d,e))", "e": 29967, "s": 29618, "text": null }, { "code": null, "e": 29975, "s": 29967, "text": "Output:" }, { "code": null, "e": 30055, "s": 29975, "text": "manoj sravan harsha vijayawada ponnur hyd 1 2 3 4 5 1.6 2.2 3.78 4.4456 5.4NULL" }, { "code": null, "e": 30070, "s": 30055, "text": "adnanirshad158" }, { "code": null, "e": 30077, "s": 30070, "text": "Picked" }, { "code": null, "e": 30095, "s": 30077, "text": "R Vector-Programs" }, { "code": null, "e": 30105, "s": 30095, "text": "R-Vectors" }, { "code": null, "e": 30116, "s": 30105, "text": "R Language" }, { "code": null, "e": 30127, "s": 30116, "text": "R Programs" }, { "code": null, "e": 30225, "s": 30127, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30234, "s": 30225, "text": "Comments" }, { "code": null, "e": 30247, "s": 30234, "text": "Old Comments" }, { "code": null, "e": 30299, "s": 30247, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 30337, "s": 30299, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 30372, "s": 30337, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 30430, "s": 30372, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 30479, "s": 30430, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 30537, "s": 30479, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 30586, "s": 30537, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 30629, "s": 30586, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 30679, "s": 30629, "text": "How to filter R dataframe by multiple conditions?" } ]
Top-level script environment in Python (__main__)
A module object is characterized by various attributes. Attribute names are prefixed and post-fixed by double underscore __. The most important attribute of module is __name__. When Python is running as a top level executable code, i.e. when read from standard input, a script, or from an interactive prompt the __name__ attribute is set to '__main__'. >>> __name__ '__main__' From within a script also, we find a value of __name__ attribute is set to '__main__'. Execute the following script. 'module docstring' print ('name of module:',__name__) Output name of module: __main__ However, for an imported module this attribute is set to name of the Python script. For hello.py module >>> import hello >>> hello.__name__ hello As seen earlier, the value of __name__ is set to __main__ for top-level module. However, for the imported module it is set to name of a file. Run following script (moduletest.py) import hello print ('name of top level module:', __name__) print ('name of imported module:', hello.__name__) Output name of top level module: __main__ name of imported module: hello A Python script containing function may also have a certain executable code. Hence if we import it its code will be run automatically. We have this script messages.py with two functions. In executable part user input is provided as an argument to thanks() function. def welcome(name): print ("Hi {}. Welcome to TutorialsPoint".format(name)) return def thanks(name): print ("Thank you {}. See you again".format(name)) name = input('enter name:') thanks(name) Obviously when we run messages.py output shows a thanks message as below. enter name:Ajit Thank you Ajit. See you again We have a moduletest.py script as below. import messages print ('name of top level module:', __name__) print ('name of imported module:', messages.__name__) Now we if we run the moduletest.py script, We'll find that the input statement and call to welcome() will be executed. c:\python37>python moduletest.py Output enter name:Kishan Thank you Kishan. See you again enter name:milind Hi milind. Welcome to TutorialsPoint This is an output of both the scripts. But want to import function from messages module but not the executable code in it. This is where the fact that value of __name__attribute of top-level script is __main__ is useful. Change messages.py script such that it executes input and function call statement only if __name__ is equal to __main__. "docstring of messages module" def welcome(name): print ("Hi {}. Welcome to TutorialsPoint".format(name)) return def thanks(name): print ("Thank you {}. See you again".format(name)) if __name__=='__main__': name = input('enter name') thanks(name) Use above technique whenever you want a module that can be executed as well as imported. The moduletest.py doesn't require any changes. An executable part in messages module won't run now. enter name: milind Hi milind. Welcome to TutorialsPoint Note that this doesn't prevent you from running messages.py script independently.
[ { "code": null, "e": 1415, "s": 1062, "text": "A module object is characterized by various attributes. Attribute names are prefixed and post-fixed by double underscore __. The most important attribute of module is __name__. When Python is running as a top level executable code, i.e. when read from standard input, a script, or from an interactive prompt the __name__ attribute is set to '__main__'." }, { "code": null, "e": 1439, "s": 1415, "text": ">>> __name__\n'__main__'" }, { "code": null, "e": 1556, "s": 1439, "text": "From within a script also, we find a value of __name__ attribute is set to '__main__'. Execute the following script." }, { "code": null, "e": 1610, "s": 1556, "text": "'module docstring'\nprint ('name of module:',__name__)" }, { "code": null, "e": 1617, "s": 1610, "text": "Output" }, { "code": null, "e": 1642, "s": 1617, "text": "name of module: __main__" }, { "code": null, "e": 1746, "s": 1642, "text": "However, for an imported module this attribute is set to name of the Python script. For hello.py module" }, { "code": null, "e": 1788, "s": 1746, "text": ">>> import hello\n>>> hello.__name__\nhello" }, { "code": null, "e": 1967, "s": 1788, "text": "As seen earlier, the value of __name__ is set to __main__ for top-level module. However, for the imported module it is set to name of a file. Run following script (moduletest.py)" }, { "code": null, "e": 2077, "s": 1967, "text": "import hello\nprint ('name of top level module:', __name__)\nprint ('name of imported module:', hello.__name__)" }, { "code": null, "e": 2084, "s": 2077, "text": "Output" }, { "code": null, "e": 2150, "s": 2084, "text": "name of top level module: __main__\nname of imported module: hello" }, { "code": null, "e": 2416, "s": 2150, "text": "A Python script containing function may also have a certain executable code. Hence if we import it its code will be run automatically. We have this script messages.py with two functions. In executable part user input is provided as an argument to thanks() function." }, { "code": null, "e": 2608, "s": 2416, "text": "def welcome(name):\nprint (\"Hi {}. Welcome to TutorialsPoint\".format(name))\nreturn\ndef thanks(name):\nprint (\"Thank you {}. See you again\".format(name))\nname = input('enter name:')\nthanks(name)" }, { "code": null, "e": 2682, "s": 2608, "text": "Obviously when we run messages.py output shows a thanks message as below." }, { "code": null, "e": 2728, "s": 2682, "text": "enter name:Ajit\nThank you Ajit. See you again" }, { "code": null, "e": 2769, "s": 2728, "text": "We have a moduletest.py script as below." }, { "code": null, "e": 2885, "s": 2769, "text": "import messages\nprint ('name of top level module:', __name__)\nprint ('name of imported module:', messages.__name__)" }, { "code": null, "e": 3004, "s": 2885, "text": "Now we if we run the moduletest.py script, We'll find that the input statement and call to welcome() will be executed." }, { "code": null, "e": 3037, "s": 3004, "text": "c:\\python37>python moduletest.py" }, { "code": null, "e": 3044, "s": 3037, "text": "Output" }, { "code": null, "e": 3149, "s": 3044, "text": "enter name:Kishan\nThank you Kishan. See you again\nenter name:milind\nHi milind. Welcome to TutorialsPoint" }, { "code": null, "e": 3272, "s": 3149, "text": "This is an output of both the scripts. But want to import function from messages module but not the executable code in it." }, { "code": null, "e": 3491, "s": 3272, "text": "This is where the fact that value of __name__attribute of top-level script is __main__ is useful. Change messages.py script such that it executes input and function call statement only if __name__ is equal to __main__." }, { "code": null, "e": 3738, "s": 3491, "text": "\"docstring of messages module\"\ndef welcome(name):\nprint (\"Hi {}. Welcome to TutorialsPoint\".format(name))\nreturn\ndef thanks(name):\nprint (\"Thank you {}. See you again\".format(name))\nif __name__=='__main__':\nname = input('enter name')\nthanks(name)" }, { "code": null, "e": 3927, "s": 3738, "text": "Use above technique whenever you want a module that can be executed as well as imported. The moduletest.py doesn't require any changes. An executable part in messages module won't run now." }, { "code": null, "e": 3983, "s": 3927, "text": "enter name: milind\nHi milind. Welcome to TutorialsPoint" }, { "code": null, "e": 4065, "s": 3983, "text": "Note that this doesn't prevent you from running messages.py script independently." } ]
Beautiful Soup - Searching the tree
There are many Beautifulsoup methods, which allows us to search a parse tree. The two most common and used methods are find() and find_all(). Before talking about find() and find_all(), let us see some examples of different filters you can pass into these methods. We have different filters which we can pass into these methods and understanding of these filters is crucial as these filters used again and again, throughout the search API. We can use these filters based on tag’s name, on its attributes, on the text of a string, or mixed of these. One of the simplest types of filter is a string. Passing a string to the search method and Beautifulsoup will perform a match against that exact string. Below code will find all the <p> tags in the document − >>> markup = BeautifulSoup('<p>Top Three</p><p><pre>Programming Languages are:</pre></p><p><b>Java, Python, Cplusplus</b></p>') >>> markup.find_all('p') [<p>Top Three</p>, <p></p>, <p><b>Java, Python, Cplusplus</b></p>] You can find all tags starting with a given string/tag. Before that we need to import the re module to use regular expression. >>> import re >>> markup = BeautifulSoup('<p>Top Three</p><p><pre>Programming Languages are:</pre></p><p><b>Java, Python, Cplusplus</b></p>') >>> >>> markup.find_all(re.compile('^p')) [<p>Top Three</p>, <p></p>, <pre>Programming Languages are:</pre>, <p><b>Java, Python, Cplusplus</b></p>] You can pass multiple tags to find by providing a list. Below code finds all the <b> and <pre> tags − >>> markup.find_all(['pre', 'b']) [<pre>Programming Languages are:</pre>, <b>Java, Python, Cplusplus</b>] True will return all tags that it can find, but no strings on their own − >>> markup.find_all(True) [<html><body><p>Top Three</p><p></p><pre>Programming Languages are:</pre> <p><b>Java, Python, Cplusplus</b> </p> </body></html>, <body><p>Top Three</p><p></p><pre> Programming Languages are:</pre><p><b>Java, Python, Cplusplus</b></p> </body>, <p>Top Three</p>, <p></p>, <pre>Programming Languages are:</pre>, <p><b>Java, Python, Cplusplus</b></p>, <b>Java, Python, Cplusplus</b>] To return only the tags from the above soup − >>> for tag in markup.find_all(True): (tag.name) 'html' 'body' 'p' 'p' 'pre' 'p' 'b' You can use find_all to extract all the occurrences of a particular tag from the page response as − find_all(name, attrs, recursive, string, limit, **kwargs) Let us extract some interesting data from IMDB-“Top rated movies” of all time. >>> url="https://www.imdb.com/chart/top/?ref_=nv_mv_250" >>> content = requests.get(url) >>> soup = BeautifulSoup(content.text, 'html.parser') #Extract title Page >>> print(soup.find('title')) <title>IMDb Top 250 - IMDb</title> #Extracting main heading >>> for heading in soup.find_all('h1'): print(heading.text) Top Rated Movies #Extracting sub-heading >>> for heading in soup.find_all('h3'): print(heading.text) IMDb Charts You Have Seen IMDb Charts Top India Charts Top Rated Movies by Genre Recently Viewed From above, we can see find_all will give us all the items matching the search criteria we define. All the filters we can use with find_all() can be used with find() and other searching methods too like find_parents() or find_siblings(). We have seen above, find_all() is used to scan the entire document to find all the contents but something, the requirement is to find only one result. If you know that the document contains only one <body> tag, it is waste of time to search the entire document. One way is to call find_all() with limit=1 every time or else we can use find() method to do the same − find(name, attrs, recursive, string, **kwargs) So below two different methods gives the same output − >>> soup.find_all('title',limit=1) [<title>IMDb Top 250 - IMDb</title>] >>> >>> soup.find('title') <title>IMDb Top 250 - IMDb</title> In the above outputs, we can see the find_all() method returns a list containing single item whereas find() method returns single result. Another difference between find() and find_all() method is − >>> soup.find_all('h2') [] >>> >>> soup.find('h2') If soup.find_all() method can’t find anything, it returns empty list whereas find() returns None. Unlike the find_all() and find() methods which traverse the tree, looking at tag’s descendents, find_parents() and find_parents methods() do the opposite, they traverse the tree upwards and look at a tag’s (or a string’s) parents. find_parents(name, attrs, string, limit, **kwargs) find_parent(name, attrs, string, **kwargs) >>> a_string = soup.find(string="The Godfather") >>> a_string 'The Godfather' >>> a_string.find_parents('a') [<a href="/title/tt0068646/" title="Francis Ford Coppola (dir.), Marlon Brando, Al Pacino">The Godfather</a>] >>> a_string.find_parent('a') <a href="/title/tt0068646/" title="Francis Ford Coppola (dir.), Marlon Brando, Al Pacino">The Godfather</a> >>> a_string.find_parent('tr') <tr> <td class="posterColumn"> <span data-value="2" name="rk"></span> <span data-value="9.149038526210072" name="ir"></span> <span data-value="6.93792E10" name="us"></span> <span data-value="1485540" name="nv"></span> <span data-value="-1.850961473789928" name="ur"></span> <a href="/title/tt0068646/"> <img alt="The Godfather" height="67" src="https://m.media-amazon.com/images/M/MV5BM2MyNjYxNmUtYTAwNi00MTYxLWJmNWYtYzZlODY3ZTk3OTFlXkEyXkFqcGdeQXVyNzkwMjQ5NzM@._V1_UY67_CR1,0,45,67_AL_.jpg" width="45"/> </a> </td> <td class="titleColumn"> 2. <a href="/title/tt0068646/" title="Francis Ford Coppola (dir.), Marlon Brando, Al Pacino">The Godfather</a> <span class="secondaryInfo">(1972)</span> </td> <td class="ratingColumn imdbRating"> <strong title="9.1 based on 1,485,540 user ratings">9.1</strong> </td> <td class="ratingColumn"> <div class="seen-widget seen-widget-tt0068646 pending" data-titleid="tt0068646"> <div class="boundary"> <div class="popover"> <span class="delete"> </span><ol><li>1<li>2<li>3<li>4<li>5<li>6<li>7<li>8<li>9<li>10</li>0</li></li></li></li&td;</li></li></li></li></li></ol> </div> </div> <div class="inline"> <div class="pending"></div> <div class="unseeable">NOT YET RELEASED</div> <div class="unseen"> </div> <div class="rating"></div> <div class="seen">Seen</div> </div> </div> </td> <td class="watchlistColumn"> <div class="wlb_ribbon" data-recordmetrics="true" data-tconst="tt0068646"></div> </td> </tr> >>> >>> a_string.find_parents('td') [<td class="titleColumn"> 2. <a href="/title/tt0068646/" title="Francis Ford Coppola (dir.), Marlon Brando, Al Pacino">The Godfather</a> <span class="secondaryInfo">(1972)</span> </td>] There are eight other similar methods − find_next_siblings(name, attrs, string, limit, **kwargs) find_next_sibling(name, attrs, string, **kwargs) find_previous_siblings(name, attrs, string, limit, **kwargs) find_previous_sibling(name, attrs, string, **kwargs) find_all_next(name, attrs, string, limit, **kwargs) find_next(name, attrs, string, **kwargs) find_all_previous(name, attrs, string, limit, **kwargs) find_previous(name, attrs, string, **kwargs) Where, find_next_siblings() and find_next_sibling() methods will iterate over all the siblings of the element that come after the current one. find_previous_siblings() and find_previous_sibling() methods will iterate over all the siblings that come before the current element. find_all_next() and find_next() methods will iterate over all the tags and strings that come after the current element. find_all_previous and find_previous() methods will iterate over all the tags and strings that come before the current element. The BeautifulSoup library to support the most commonly-used CSS selectors. You can search for elements using CSS selectors with the help of the select() method. Here are some examples − >>> soup.select('title') [<title>IMDb Top 250 - IMDb</title>, <title>IMDb Top Rated Movies</title>] >>> >>> soup.select("p:nth-of-type(1)") [<p>The Top Rated Movie list only includes theatrical features.</p>, <p> class="imdb-footer__copyright _2-iNNCFskmr4l2OFN2DRsf">© 1990-2019 by IMDb.com, Inc.</p>] >>> len(soup.select("p:nth-of-type(1)")) 2 >>> len(soup.select("a")) 609 >>> len(soup.select("p")) 2 >>> soup.select("html head title") [<title>IMDb Top 250 - IMDb</title>, <title>IMDb Top Rated Movies</title>] >>> soup.select("head > title") [<title>IMDb Top 250 - IMDb</title>] #print HTML code of the tenth li elemnet >>> soup.select("li:nth-of-type(10)") [<li class="subnav_item_main"> <a href="/search/title?genres=film_noir&sort=user_rating,desc&title_type=feature&num_votes=25000,">Film-Noir </a> </li>] 38 Lectures 3.5 hours Chandramouli Jayendran 22 Lectures 1 hours TELCOMA Global 6 Lectures 1 hours AlexanderSchlee 6 Lectures 1 hours AlexanderSchlee 6 Lectures 1 hours AlexanderSchlee 22 Lectures 4 hours AlexanderSchlee Print Add Notes Bookmark this page
[ { "code": null, "e": 2127, "s": 1985, "text": "There are many Beautifulsoup methods, which allows us to search a parse tree. The two most common and used methods are find() and find_all()." }, { "code": null, "e": 2250, "s": 2127, "text": "Before talking about find() and find_all(), let us see some examples of different filters you can pass into these methods." }, { "code": null, "e": 2534, "s": 2250, "text": "We have different filters which we can pass into these methods and understanding of these filters is crucial as these filters used again and again, throughout the search API. We can use these filters based on tag’s name, on its attributes, on the text of a string, or mixed of these." }, { "code": null, "e": 2687, "s": 2534, "text": "One of the simplest types of filter is a string. Passing a string to the search method and Beautifulsoup will perform a match against that exact string." }, { "code": null, "e": 2743, "s": 2687, "text": "Below code will find all the <p> tags in the document −" }, { "code": null, "e": 2963, "s": 2743, "text": ">>> markup = BeautifulSoup('<p>Top Three</p><p><pre>Programming Languages are:</pre></p><p><b>Java, Python, Cplusplus</b></p>')\n>>> markup.find_all('p')\n[<p>Top Three</p>, <p></p>, <p><b>Java, Python, Cplusplus</b></p>]" }, { "code": null, "e": 3090, "s": 2963, "text": "You can find all tags starting with a given string/tag. Before that we need to import the re module to use regular expression." }, { "code": null, "e": 3380, "s": 3090, "text": ">>> import re\n>>> markup = BeautifulSoup('<p>Top Three</p><p><pre>Programming Languages are:</pre></p><p><b>Java, Python, Cplusplus</b></p>')\n>>>\n>>> markup.find_all(re.compile('^p'))\n[<p>Top Three</p>, <p></p>, <pre>Programming Languages are:</pre>, <p><b>Java, Python, Cplusplus</b></p>]" }, { "code": null, "e": 3482, "s": 3380, "text": "You can pass multiple tags to find by providing a list. Below code finds all the <b> and <pre> tags −" }, { "code": null, "e": 3589, "s": 3482, "text": ">>> markup.find_all(['pre', 'b'])\n[<pre>Programming Languages are:</pre>, <b>Java, Python, Cplusplus</b>]\n" }, { "code": null, "e": 3663, "s": 3589, "text": "True will return all tags that it can find, but no strings on their own −" }, { "code": null, "e": 4071, "s": 3663, "text": ">>> markup.find_all(True)\n[<html><body><p>Top Three</p><p></p><pre>Programming Languages are:</pre>\n<p><b>Java, Python, Cplusplus</b> </p> </body></html>, \n<body><p>Top Three</p><p></p><pre> Programming Languages are:</pre><p><b>Java, Python, Cplusplus</b></p>\n</body>, \n<p>Top Three</p>, <p></p>, <pre>Programming Languages are:</pre>, <p><b>Java, Python, Cplusplus</b></p>, <b>Java, Python, Cplusplus</b>]" }, { "code": null, "e": 4117, "s": 4071, "text": "To return only the tags from the above soup −" }, { "code": null, "e": 4203, "s": 4117, "text": ">>> for tag in markup.find_all(True):\n(tag.name)\n'html'\n'body'\n'p'\n'p'\n'pre'\n'p'\n'b'\n" }, { "code": null, "e": 4303, "s": 4203, "text": "You can use find_all to extract all the occurrences of a particular tag from the page response as −" }, { "code": null, "e": 4362, "s": 4303, "text": "find_all(name, attrs, recursive, string, limit, **kwargs)\n" }, { "code": null, "e": 4441, "s": 4362, "text": "Let us extract some interesting data from IMDB-“Top rated movies” of all time." }, { "code": null, "e": 4970, "s": 4441, "text": ">>> url=\"https://www.imdb.com/chart/top/?ref_=nv_mv_250\"\n>>> content = requests.get(url)\n>>> soup = BeautifulSoup(content.text, 'html.parser')\n#Extract title Page\n>>> print(soup.find('title'))\n<title>IMDb Top 250 - IMDb</title>\n\n#Extracting main heading\n>>> for heading in soup.find_all('h1'):\n print(heading.text)\nTop Rated Movies\n\n#Extracting sub-heading\n>>> for heading in soup.find_all('h3'):\n print(heading.text)\n \nIMDb Charts\nYou Have Seen\n IMDb Charts\n Top India Charts\nTop Rated Movies by Genre\nRecently Viewed" }, { "code": null, "e": 5208, "s": 4970, "text": "From above, we can see find_all will give us all the items matching the search criteria we define. All the filters we can use with find_all() can be used with find() and other searching methods too like find_parents() or find_siblings()." }, { "code": null, "e": 5574, "s": 5208, "text": "We have seen above, find_all() is used to scan the entire document to find all the contents but something, the requirement is to find only one result. If you know that the document contains only one <body> tag, it is waste of time to search the entire document. One way is to call find_all() with limit=1 every time or else we can use find() method to do the same −" }, { "code": null, "e": 5622, "s": 5574, "text": "find(name, attrs, recursive, string, **kwargs)\n" }, { "code": null, "e": 5677, "s": 5622, "text": "So below two different methods gives the same output −" }, { "code": null, "e": 5811, "s": 5677, "text": ">>> soup.find_all('title',limit=1)\n[<title>IMDb Top 250 - IMDb</title>]\n>>>\n>>> soup.find('title')\n<title>IMDb Top 250 - IMDb</title>" }, { "code": null, "e": 5949, "s": 5811, "text": "In the above outputs, we can see the find_all() method returns a list containing single item whereas find() method returns single result." }, { "code": null, "e": 6010, "s": 5949, "text": "Another difference between find() and find_all() method is −" }, { "code": null, "e": 6062, "s": 6010, "text": ">>> soup.find_all('h2')\n[]\n>>>\n>>> soup.find('h2')\n" }, { "code": null, "e": 6160, "s": 6062, "text": "If soup.find_all() method can’t find anything, it returns empty list whereas find() returns None." }, { "code": null, "e": 6391, "s": 6160, "text": "Unlike the find_all() and find() methods which traverse the tree, looking at tag’s descendents, find_parents() and find_parents methods() do the opposite, they traverse the tree upwards and look at a tag’s (or a string’s) parents." }, { "code": null, "e": 8537, "s": 6391, "text": "find_parents(name, attrs, string, limit, **kwargs)\nfind_parent(name, attrs, string, **kwargs)\n\n>>> a_string = soup.find(string=\"The Godfather\")\n>>> a_string\n'The Godfather'\n>>> a_string.find_parents('a')\n[<a href=\"/title/tt0068646/\" title=\"Francis Ford Coppola (dir.), Marlon Brando, Al Pacino\">The Godfather</a>]\n>>> a_string.find_parent('a')\n<a href=\"/title/tt0068646/\" title=\"Francis Ford Coppola (dir.), Marlon Brando, Al Pacino\">The Godfather</a>\n>>> a_string.find_parent('tr')\n<tr>\n\n<td class=\"posterColumn\">\n<span data-value=\"2\" name=\"rk\"></span>\n<span data-value=\"9.149038526210072\" name=\"ir\"></span>\n<span data-value=\"6.93792E10\" name=\"us\"></span>\n<span data-value=\"1485540\" name=\"nv\"></span>\n<span data-value=\"-1.850961473789928\" name=\"ur\"></span>\n<a href=\"/title/tt0068646/\"> <img alt=\"The Godfather\" height=\"67\" src=\"https://m.media-amazon.com/images/M/MV5BM2MyNjYxNmUtYTAwNi00MTYxLWJmNWYtYzZlODY3ZTk3OTFlXkEyXkFqcGdeQXVyNzkwMjQ5NzM@._V1_UY67_CR1,0,45,67_AL_.jpg\" width=\"45\"/>\n</a> </td>\n<td class=\"titleColumn\">\n2.\n<a href=\"/title/tt0068646/\" title=\"Francis Ford Coppola (dir.), Marlon Brando, Al Pacino\">The Godfather</a>\n<span class=\"secondaryInfo\">(1972)</span>\n</td>\n<td class=\"ratingColumn imdbRating\">\n<strong title=\"9.1 based on 1,485,540 user ratings\">9.1</strong>\n</td>\n<td class=\"ratingColumn\">\n<div class=\"seen-widget seen-widget-tt0068646 pending\" data-titleid=\"tt0068646\">\n<div class=\"boundary\">\n<div class=\"popover\">\n<span class=\"delete\"> </span><ol><li>1<li>2<li>3<li>4<li>5<li>6<li>7<li>8<li>9<li>10</li>0</li></li></li></li&td;</li></li></li></li></li></ol> </div>\n</div>\n<div class=\"inline\">\n<div class=\"pending\"></div>\n<div class=\"unseeable\">NOT YET RELEASED</div>\n<div class=\"unseen\"> </div>\n<div class=\"rating\"></div>\n<div class=\"seen\">Seen</div>\n</div>\n</div>\n</td>\n<td class=\"watchlistColumn\">\n\n<div class=\"wlb_ribbon\" data-recordmetrics=\"true\" data-tconst=\"tt0068646\"></div>\n</td>\n</tr>\n>>>\n>>> a_string.find_parents('td')\n[<td class=\"titleColumn\">\n2.\n<a href=\"/title/tt0068646/\" title=\"Francis Ford Coppola (dir.), Marlon Brando, Al Pacino\">The Godfather</a>\n<span class=\"secondaryInfo\">(1972)</span>\n</td>]" }, { "code": null, "e": 8577, "s": 8537, "text": "There are eight other similar methods −" }, { "code": null, "e": 8994, "s": 8577, "text": "find_next_siblings(name, attrs, string, limit, **kwargs)\nfind_next_sibling(name, attrs, string, **kwargs)\n\nfind_previous_siblings(name, attrs, string, limit, **kwargs)\nfind_previous_sibling(name, attrs, string, **kwargs)\n\nfind_all_next(name, attrs, string, limit, **kwargs)\nfind_next(name, attrs, string, **kwargs)\n\nfind_all_previous(name, attrs, string, limit, **kwargs)\nfind_previous(name, attrs, string, **kwargs)" }, { "code": null, "e": 9001, "s": 8994, "text": "Where," }, { "code": null, "e": 9137, "s": 9001, "text": "find_next_siblings() and find_next_sibling() methods will iterate over all the siblings of the element that come after the current one." }, { "code": null, "e": 9271, "s": 9137, "text": "find_previous_siblings() and find_previous_sibling() methods will iterate over all the siblings that come before the current element." }, { "code": null, "e": 9391, "s": 9271, "text": "find_all_next() and find_next() methods will iterate over all the tags and strings that come after the current element." }, { "code": null, "e": 9518, "s": 9391, "text": "find_all_previous and find_previous() methods will iterate over all the tags and strings that come before the current element." }, { "code": null, "e": 9679, "s": 9518, "text": "The BeautifulSoup library to support the most commonly-used CSS selectors. You can search for elements using CSS selectors with the help of the select() method." }, { "code": null, "e": 9704, "s": 9679, "text": "Here are some examples −" }, { "code": null, "e": 10520, "s": 9704, "text": ">>> soup.select('title')\n[<title>IMDb Top 250 - IMDb</title>, <title>IMDb Top Rated Movies</title>]\n>>>\n>>> soup.select(\"p:nth-of-type(1)\")\n[<p>The Top Rated Movie list only includes theatrical features.</p>, <p> class=\"imdb-footer__copyright _2-iNNCFskmr4l2OFN2DRsf\">© 1990-2019 by IMDb.com, Inc.</p>]\n>>> len(soup.select(\"p:nth-of-type(1)\"))\n2\n>>> len(soup.select(\"a\"))\n609\n>>> len(soup.select(\"p\"))\n2\n\n>>> soup.select(\"html head title\")\n[<title>IMDb Top 250 - IMDb</title>, <title>IMDb Top Rated Movies</title>]\n>>> soup.select(\"head > title\")\n[<title>IMDb Top 250 - IMDb</title>]\n\n#print HTML code of the tenth li elemnet\n>>> soup.select(\"li:nth-of-type(10)\")\n[<li class=\"subnav_item_main\">\n<a href=\"/search/title?genres=film_noir&sort=user_rating,desc&title_type=feature&num_votes=25000,\">Film-Noir\n</a> </li>]" }, { "code": null, "e": 10555, "s": 10520, "text": "\n 38 Lectures \n 3.5 hours \n" }, { "code": null, "e": 10579, "s": 10555, "text": " Chandramouli Jayendran" }, { "code": null, "e": 10612, "s": 10579, "text": "\n 22 Lectures \n 1 hours \n" }, { "code": null, "e": 10628, "s": 10612, "text": " TELCOMA Global" }, { "code": null, "e": 10660, "s": 10628, "text": "\n 6 Lectures \n 1 hours \n" }, { "code": null, "e": 10677, "s": 10660, "text": " AlexanderSchlee" }, { "code": null, "e": 10709, "s": 10677, "text": "\n 6 Lectures \n 1 hours \n" }, { "code": null, "e": 10726, "s": 10709, "text": " AlexanderSchlee" }, { "code": null, "e": 10758, "s": 10726, "text": "\n 6 Lectures \n 1 hours \n" }, { "code": null, "e": 10775, "s": 10758, "text": " AlexanderSchlee" }, { "code": null, "e": 10808, "s": 10775, "text": "\n 22 Lectures \n 4 hours \n" }, { "code": null, "e": 10825, "s": 10808, "text": " AlexanderSchlee" }, { "code": null, "e": 10832, "s": 10825, "text": " Print" }, { "code": null, "e": 10843, "s": 10832, "text": " Add Notes" } ]
Java Regex - PatternSyntaxException Class
The java.util.regex.PatternSyntaxException class represents a unchecked exception thrown to indicate a syntax error in a regular-expression pattern. Following is the declaration for java.util.regex.PatternSyntaxException class − public class PatternSyntaxException extends IllegalArgumentException Constructs a new instance of this class. Retrieves the description of the error. Retrieves the error index. Returns a multi-line string containing the description of the syntax error and its index, the erroneous regular-expression pattern, and a visual indication of the error index within the pattern. Retrieves the erroneous regular-expression pattern. This class inherits methods from the following classes − Java.lang.Throwable Java.lang.Object The following example shows the usage of java.util.regex.Pattern.PatternSyntaxException class methods. package com.tutorialspoint; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; public class PatternSyntaxExceptionDemo { private static String REGEX = "["; private static String INPUT = "The dog says meow " + "All dogs say meow."; private static String REPLACE = "cat"; public static void main(String[] args) { try{ Pattern pattern = Pattern.compile(REGEX); // get a matcher object Matcher matcher = pattern.matcher(INPUT); INPUT = matcher.replaceAll(REPLACE); } catch(PatternSyntaxException e){ System.out.println("PatternSyntaxException: "); System.out.println("Description: "+ e.getDescription()); System.out.println("Index: "+ e.getIndex()); System.out.println("Message: "+ e.getMessage()); System.out.println("Pattern: "+ e.getPattern()); } } } Let us compile and run the above program, this will produce the following result − PatternSyntaxException: Description: Unclosed character class Index: 0 Message: Unclosed character class near index 0 [ ^ Pattern: [ Print Add Notes Bookmark this page
[ { "code": null, "e": 2273, "s": 2124, "text": "The java.util.regex.PatternSyntaxException class represents a unchecked exception thrown to indicate a syntax error in a regular-expression pattern." }, { "code": null, "e": 2353, "s": 2273, "text": "Following is the declaration for java.util.regex.PatternSyntaxException class −" }, { "code": null, "e": 2426, "s": 2353, "text": "public class PatternSyntaxException\n extends IllegalArgumentException\n" }, { "code": null, "e": 2467, "s": 2426, "text": "Constructs a new instance of this class." }, { "code": null, "e": 2507, "s": 2467, "text": "Retrieves the description of the error." }, { "code": null, "e": 2534, "s": 2507, "text": "Retrieves the error index." }, { "code": null, "e": 2729, "s": 2534, "text": "Returns a multi-line string containing the description of the syntax error and its index, the erroneous regular-expression pattern, and a visual indication of the error index within the pattern." }, { "code": null, "e": 2781, "s": 2729, "text": "Retrieves the erroneous regular-expression pattern." }, { "code": null, "e": 2838, "s": 2781, "text": "This class inherits methods from the following classes −" }, { "code": null, "e": 2858, "s": 2838, "text": "Java.lang.Throwable" }, { "code": null, "e": 2875, "s": 2858, "text": "Java.lang.Object" }, { "code": null, "e": 2978, "s": 2875, "text": "The following example shows the usage of java.util.regex.Pattern.PatternSyntaxException class methods." }, { "code": null, "e": 3916, "s": 2978, "text": "package com.tutorialspoint;\n\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\nimport java.util.regex.PatternSyntaxException;\n\npublic class PatternSyntaxExceptionDemo {\n private static String REGEX = \"[\";\n private static String INPUT = \"The dog says meow \" + \"All dogs say meow.\";\n private static String REPLACE = \"cat\";\n\n public static void main(String[] args) {\n try{\n Pattern pattern = Pattern.compile(REGEX);\n \n // get a matcher object\n Matcher matcher = pattern.matcher(INPUT); \n INPUT = matcher.replaceAll(REPLACE);\n } catch(PatternSyntaxException e){\n System.out.println(\"PatternSyntaxException: \");\n System.out.println(\"Description: \"+ e.getDescription());\n System.out.println(\"Index: \"+ e.getIndex());\n System.out.println(\"Message: \"+ e.getMessage());\n System.out.println(\"Pattern: \"+ e.getPattern());\n }\n }\n}" }, { "code": null, "e": 3999, "s": 3916, "text": "Let us compile and run the above program, this will produce the following result −" }, { "code": null, "e": 4134, "s": 3999, "text": "PatternSyntaxException: \nDescription: Unclosed character class\nIndex: 0\nMessage: Unclosed character class near index 0\n[\n^\nPattern: [\n" }, { "code": null, "e": 4141, "s": 4134, "text": " Print" }, { "code": null, "e": 4152, "s": 4141, "text": " Add Notes" } ]
C++ Program to Check Whether a character is Vowel or Consonant
Vowels are the alphabets a, e, i, o, u. All the rest of the alphabets are known as consonants. The program to check if a character is a vowel or consonant is as follows − Live Demo #include <iostream> using namespace std; int main() { char c = 'a'; if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' ) cout <<c<< " is a Vowel" << endl; else cout <<c<< " is a Consonant" << endl; return 0; } a is a Vowel In the above program, an if statement is used to find if the character is a, e, i, o or u. If it is any of these, it is a vowel. Otherwise, it is a consonant. This is shown in the below code snippet. if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' ) cout <<c<< " is a Vowel" << endl; else cout <<c<< " is a Consonant" << endl; The above program checks only for lower case characters. So, a program that checks for upper case as well as lower case characters is as follows − Live Demo #include <iostream> using namespace std; int main() { char c = 'B'; if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' || c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U') cout <<c<< " is a Vowel" << endl; else cout <<c<< " is a Consonant" << endl; return 0; } B is a Consonant In the above program, an if statement is used to find if the character is a, e, i, o or u (both in upper case as well as lower case).. If it is any of these, it is a vowel. Otherwise, it is a consonant. if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' || c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U') cout <<c<< " is a Vowel" << endl; else cout <<c<< " is a Consonant" << endl;
[ { "code": null, "e": 1157, "s": 1062, "text": "Vowels are the alphabets a, e, i, o, u. All the rest of the alphabets are known as consonants." }, { "code": null, "e": 1233, "s": 1157, "text": "The program to check if a character is a vowel or consonant is as follows −" }, { "code": null, "e": 1244, "s": 1233, "text": " Live Demo" }, { "code": null, "e": 1482, "s": 1244, "text": "#include <iostream>\nusing namespace std;\nint main() {\n char c = 'a';\n if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' )\n cout <<c<< \" is a Vowel\" << endl;\n else\n cout <<c<< \" is a Consonant\" << endl;\n return 0;\n}" }, { "code": null, "e": 1495, "s": 1482, "text": "a is a Vowel" }, { "code": null, "e": 1654, "s": 1495, "text": "In the above program, an if statement is used to find if the character is a, e, i, o or u. If it is any of these, it is a vowel. Otherwise, it is a consonant." }, { "code": null, "e": 1695, "s": 1654, "text": "This is shown in the below code snippet." }, { "code": null, "e": 1835, "s": 1695, "text": "if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' )\ncout <<c<< \" is a Vowel\" << endl;\nelse\ncout <<c<< \" is a Consonant\" << endl;" }, { "code": null, "e": 1982, "s": 1835, "text": "The above program checks only for lower case characters. So, a program that checks for upper case as well as lower case characters is as follows −" }, { "code": null, "e": 1993, "s": 1982, "text": " Live Demo" }, { "code": null, "e": 2296, "s": 1993, "text": "#include <iostream>\nusing namespace std;\nint main() {\n char c = 'B';\n if (c == 'a' || c == 'e' || c == 'i' ||\n c == 'o' || c == 'u' || c == 'A' ||\n c == 'E' || c == 'I' || c == 'O' || c == 'U')\n cout <<c<< \" is a Vowel\" << endl;\n else\n cout <<c<< \" is a Consonant\" << endl;\n return 0;\n}" }, { "code": null, "e": 2313, "s": 2296, "text": "B is a Consonant" }, { "code": null, "e": 2516, "s": 2313, "text": "In the above program, an if statement is used to find if the character is a, e, i, o or u (both in upper case as well as lower case).. If it is any of these, it is a vowel. Otherwise, it is a consonant." }, { "code": null, "e": 2715, "s": 2516, "text": "if (c == 'a' || c == 'e' || c == 'i' ||\nc == 'o' || c == 'u' || c == 'A' ||\nc == 'E' || c == 'I' || c == 'O' || c == 'U')\ncout <<c<< \" is a Vowel\" << endl;\nelse\ncout <<c<< \" is a Consonant\" << endl;" } ]
An easy introduction to 3D plotting with Matplotlib | by George Seif | Towards Data Science
Want to be inspired? Come join my Super Quotes newsletter. 😎 Every Data Scientist should know how to create effective data visualisations. Without visualisation, you’ll be stuck trying to crunch numbers and imagine thousands of data points in your head! Beyond that, it’s also a crucial tool for communicating effectively with non-technical business stake holders who’ll more easily understand your results with a picture rather than just words. Most of the data visualisation tutorials out there show the same basic things: scatter plots, line plots, box plots, bar charts, and heat maps. These are all fantastic for gaining quick, high-level insight into a dataset. But what if we took things a step further. A 2D plot can only show the relationships between a single pair of axes x-y; a 3D plot on the other hand allows us to explore relationships of 3 pairs of axes: x-y, x-z, and y-z. In this article, I’ll give you an easy introduction into the world of 3D data visualisation using Matplotlib. At the end of it all, you’ll be able to add 3D plotting to your Data Science tool kit! Just before we jump in, check out the AI Smart Newsletter to read the latest and greatest on AI, Machine Learning, and Data Science! 3D plotting in Matplotlib starts by enabling the utility toolkit. We can enable this toolkit by importing the mplot3d library, which comes with your standard Matplotlib installation via pip. Just be sure that your Matplotlib version is over 1.0. Once this sub-module is imported, 3D plots can be created by passing the keyword projection="3d" to any of the regular axes creation functions in Matplotlib: from mpl_toolkits import mplot3dimport numpy as npimport matplotlib.pyplot as pltfig = plt.figure()ax = plt.axes(projection="3d")plt.show() Now that our axes are created we can start plotting in 3D. The 3D plotting functions are quite intuitive: instead of just scatter we call scatter3D , and instead of passing only x and y data, we pass over x, y, and z. All of the other function settings such as colour and line type remain the same as with the 2D plotting functions. Here’s an example of plotting a 3D line and 3D points. fig = plt.figure()ax = plt.axes(projection="3d")z_line = np.linspace(0, 15, 1000)x_line = np.cos(z_line)y_line = np.sin(z_line)ax.plot3D(x_line, y_line, z_line, 'gray')z_points = 15 * np.random.random(100)x_points = np.cos(z_points) + 0.1 * np.random.randn(100)y_points = np.sin(z_points) + 0.1 * np.random.randn(100)ax.scatter3D(x_points, y_points, z_points, c=z_points, cmap='hsv');plt.show() Here’s the most awesome part about plotting in 3D: interactivity. The interactivity of plots becomes extremely useful for exploring your visualised data once you’ve plotted in 3D. Check out some of the different views I created by doing a simple click-and-drag of the plot! Surface plots can be great for visualising the relationships among 3 variables across the entire 3D landscape. They give a full structure and view as to how the value of each variable changes across the axes of the 2 others. Constructing a surface plot in Matplotlib is a 3-step process. (1) First we need to generate the actual points that will make up the surface plot. Now, generating all the points of the 3D surface is impossible since there are an infinite number of them! So instead, we’ll generate just enough to be able to estimate the surface and then extrapolate the rest of the points. We’ll define the x and y points and then compute the z points using a function. fig = plt.figure()ax = plt.axes(projection="3d")def z_function(x, y): return np.sin(np.sqrt(x ** 2 + y ** 2))x = np.linspace(-6, 6, 30)y = np.linspace(-6, 6, 30)X, Y = np.meshgrid(x, y)Z = z_function(X, Y) (2) The second step is to plot a wire-frame — this is our estimate of the surface. fig = plt.figure()ax = plt.axes(projection="3d")ax.plot_wireframe(X, Y, Z, color='green')ax.set_xlabel('x')ax.set_ylabel('y')ax.set_zlabel('z')plt.show() (3) Finally, we’ll project our surface onto our wire-frame estimate and extrapolate all of the points. ax = plt.axes(projection='3d')ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap='winter', edgecolor='none')ax.set_title('surface'); Beauty! There’s our colourful 3D surface! Bar plots are used quite frequently in data visualisation projects since they’re able to convey information, usually some type of comparison, in a simple and intuitive way. The beauty of 3D bar plots is that they maintain the simplicity of 2D bar plots while extending their capacity to represent comparative information. Each bar in a bar plot always needs 2 things: a position and a size. With 3D bar plots, we’re going to supply that information for all three variables x, y, z. We’ll select the z axis to encode the height of each bar; therefore, each bar will start at z = 0 and have a size that is proportional to the value we are trying to visualise. The x and y positions will represent the coordinates of the bar across the 2D plane of z = 0. We’ll set the x and y size of each bar to a value of 1 so that all the bars have the same shape. Check out the code and 3D plots below for an example! fig = plt.figure()ax = plt.axes(projection="3d")num_bars = 15x_pos = random.sample(xrange(20), num_bars)y_pos = random.sample(xrange(20), num_bars)z_pos = [0] * num_barsx_size = np.ones(num_bars)y_size = np.ones(num_bars)z_size = random.sample(xrange(20), num_bars)ax.bar3d(x_pos, y_pos, z_pos, x_size, y_size, z_size, color='aqua')plt.show()
[ { "code": null, "e": 232, "s": 171, "text": "Want to be inspired? Come join my Super Quotes newsletter. 😎" }, { "code": null, "e": 425, "s": 232, "text": "Every Data Scientist should know how to create effective data visualisations. Without visualisation, you’ll be stuck trying to crunch numbers and imagine thousands of data points in your head!" }, { "code": null, "e": 617, "s": 425, "text": "Beyond that, it’s also a crucial tool for communicating effectively with non-technical business stake holders who’ll more easily understand your results with a picture rather than just words." }, { "code": null, "e": 839, "s": 617, "text": "Most of the data visualisation tutorials out there show the same basic things: scatter plots, line plots, box plots, bar charts, and heat maps. These are all fantastic for gaining quick, high-level insight into a dataset." }, { "code": null, "e": 1061, "s": 839, "text": "But what if we took things a step further. A 2D plot can only show the relationships between a single pair of axes x-y; a 3D plot on the other hand allows us to explore relationships of 3 pairs of axes: x-y, x-z, and y-z." }, { "code": null, "e": 1258, "s": 1061, "text": "In this article, I’ll give you an easy introduction into the world of 3D data visualisation using Matplotlib. At the end of it all, you’ll be able to add 3D plotting to your Data Science tool kit!" }, { "code": null, "e": 1391, "s": 1258, "text": "Just before we jump in, check out the AI Smart Newsletter to read the latest and greatest on AI, Machine Learning, and Data Science!" }, { "code": null, "e": 1637, "s": 1391, "text": "3D plotting in Matplotlib starts by enabling the utility toolkit. We can enable this toolkit by importing the mplot3d library, which comes with your standard Matplotlib installation via pip. Just be sure that your Matplotlib version is over 1.0." }, { "code": null, "e": 1795, "s": 1637, "text": "Once this sub-module is imported, 3D plots can be created by passing the keyword projection=\"3d\" to any of the regular axes creation functions in Matplotlib:" }, { "code": null, "e": 1935, "s": 1795, "text": "from mpl_toolkits import mplot3dimport numpy as npimport matplotlib.pyplot as pltfig = plt.figure()ax = plt.axes(projection=\"3d\")plt.show()" }, { "code": null, "e": 2268, "s": 1935, "text": "Now that our axes are created we can start plotting in 3D. The 3D plotting functions are quite intuitive: instead of just scatter we call scatter3D , and instead of passing only x and y data, we pass over x, y, and z. All of the other function settings such as colour and line type remain the same as with the 2D plotting functions." }, { "code": null, "e": 2323, "s": 2268, "text": "Here’s an example of plotting a 3D line and 3D points." }, { "code": null, "e": 2718, "s": 2323, "text": "fig = plt.figure()ax = plt.axes(projection=\"3d\")z_line = np.linspace(0, 15, 1000)x_line = np.cos(z_line)y_line = np.sin(z_line)ax.plot3D(x_line, y_line, z_line, 'gray')z_points = 15 * np.random.random(100)x_points = np.cos(z_points) + 0.1 * np.random.randn(100)y_points = np.sin(z_points) + 0.1 * np.random.randn(100)ax.scatter3D(x_points, y_points, z_points, c=z_points, cmap='hsv');plt.show()" }, { "code": null, "e": 2992, "s": 2718, "text": "Here’s the most awesome part about plotting in 3D: interactivity. The interactivity of plots becomes extremely useful for exploring your visualised data once you’ve plotted in 3D. Check out some of the different views I created by doing a simple click-and-drag of the plot!" }, { "code": null, "e": 3217, "s": 2992, "text": "Surface plots can be great for visualising the relationships among 3 variables across the entire 3D landscape. They give a full structure and view as to how the value of each variable changes across the axes of the 2 others." }, { "code": null, "e": 3280, "s": 3217, "text": "Constructing a surface plot in Matplotlib is a 3-step process." }, { "code": null, "e": 3670, "s": 3280, "text": "(1) First we need to generate the actual points that will make up the surface plot. Now, generating all the points of the 3D surface is impossible since there are an infinite number of them! So instead, we’ll generate just enough to be able to estimate the surface and then extrapolate the rest of the points. We’ll define the x and y points and then compute the z points using a function." }, { "code": null, "e": 3879, "s": 3670, "text": "fig = plt.figure()ax = plt.axes(projection=\"3d\")def z_function(x, y): return np.sin(np.sqrt(x ** 2 + y ** 2))x = np.linspace(-6, 6, 30)y = np.linspace(-6, 6, 30)X, Y = np.meshgrid(x, y)Z = z_function(X, Y)" }, { "code": null, "e": 3962, "s": 3879, "text": "(2) The second step is to plot a wire-frame — this is our estimate of the surface." }, { "code": null, "e": 4116, "s": 3962, "text": "fig = plt.figure()ax = plt.axes(projection=\"3d\")ax.plot_wireframe(X, Y, Z, color='green')ax.set_xlabel('x')ax.set_ylabel('y')ax.set_zlabel('z')plt.show()" }, { "code": null, "e": 4219, "s": 4116, "text": "(3) Finally, we’ll project our surface onto our wire-frame estimate and extrapolate all of the points." }, { "code": null, "e": 4368, "s": 4219, "text": "ax = plt.axes(projection='3d')ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap='winter', edgecolor='none')ax.set_title('surface');" }, { "code": null, "e": 4410, "s": 4368, "text": "Beauty! There’s our colourful 3D surface!" }, { "code": null, "e": 4732, "s": 4410, "text": "Bar plots are used quite frequently in data visualisation projects since they’re able to convey information, usually some type of comparison, in a simple and intuitive way. The beauty of 3D bar plots is that they maintain the simplicity of 2D bar plots while extending their capacity to represent comparative information." }, { "code": null, "e": 4892, "s": 4732, "text": "Each bar in a bar plot always needs 2 things: a position and a size. With 3D bar plots, we’re going to supply that information for all three variables x, y, z." }, { "code": null, "e": 5259, "s": 4892, "text": "We’ll select the z axis to encode the height of each bar; therefore, each bar will start at z = 0 and have a size that is proportional to the value we are trying to visualise. The x and y positions will represent the coordinates of the bar across the 2D plane of z = 0. We’ll set the x and y size of each bar to a value of 1 so that all the bars have the same shape." }, { "code": null, "e": 5313, "s": 5259, "text": "Check out the code and 3D plots below for an example!" } ]
How to capture a image from webcam in Python? - GeeksforGeeks
21 Dec, 2021 In this article, we will discuss how to capture an image from the webcam using Python. We will use OpenCV and PyGame libraries. Both libraries include various methods and functions to capture an image and video also. By using, these vast libraries we need to write only 4 to 5 lines of code to capture an image. OpenCV library is compatible with the Linux and windows both operating system. Users need to install the OpenCV library on their local computer using the below command before they go ahead. Install command - pip install opencv-python 1. Import OpenCV library 2. Initialize the camera using the VideoCapture() method. Syntax: Python3 cam = VideoCapture(0) 3. Read input using the camera using the cam.read() method. Syntax: Python3 result, image = cam.read() 4. If input image detected without any error, show output Syntax: If result: # show the image imshow("GeeksForGeeks", image) # save the image imwrite("GeeksForGeeks.png", image) else: Move to this part is input image has some error Python3 # program to capture single image from webcam in python # importing OpenCV libraryfrom cv2 import * # initialize the camera# If you have multiple camera connected with # current device, assign a value in cam_port # variable according to thatcam_port = 0cam = VideoCapture(cam_port) # reading the input using the cameraresult, image = cam.read() # If image will detected without any error, # show resultif result: # showing result, it take frame name and image # output imshow("GeeksForGeeks", image) # saving image in local storage imwrite("GeeksForGeeks.png", image) # If keyboard interrupt occurs, destroy image # window waitKey(0) destroyWindow("GeeksForGeeks") # If captured image is corrupted, moving to else partelse: print("No image detected. Please! try again") Output: PyGame.camera() camera initializer supports only Linux operating system and Currently, It is not compatible with Windows. To install PyGame in Linux, Enter the below command on the Linux terminal. 1. Import pygame.camera module 2. Initialize the camera using the camera.init() method. Python3 pygame.camera.init() 3. Detect all available cameras using the list_cameras() method. Python3 camlist = pygame.camera.list_cameras() 4. check if the camera is detected or not Syntax: if camlist: # Initialize and start camera cam = pygame.camera.Camera(camlist[0], (640, 480)) cam.start() # capturing the single image image = cam.get_image() # saving the image pygame.image.save(image, "filename.jpg") else: if camera is not detected the moving to this part Python3 # Python program to capture a single image# using pygame library # importing the pygame libraryimport pygameimport pygame.camera # initializing the camerapygame.camera.init() # make the list of all available camerascamlist = pygame.camera.list_cameras() # if camera is detected or notif camlist: # initializing the cam variable with default camera cam = pygame.camera.Camera(camlist[0], (640, 480)) # opening the camera cam.start() # capturing the single image image = cam.get_image() # saving the image pygame.image.save(image, "filename.jpg") # if camera is not detected the moving to else partelse: print("No camera on current device") Output: rajeev0719singh adnanirshad158 Python-OpenCV Python-PyGame Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python | Get unique values from a list Python | os.path.join() method Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n21 Dec, 2021" }, { "code": null, "e": 25624, "s": 25537, "text": "In this article, we will discuss how to capture an image from the webcam using Python." }, { "code": null, "e": 25849, "s": 25624, "text": "We will use OpenCV and PyGame libraries. Both libraries include various methods and functions to capture an image and video also. By using, these vast libraries we need to write only 4 to 5 lines of code to capture an image." }, { "code": null, "e": 26039, "s": 25849, "text": "OpenCV library is compatible with the Linux and windows both operating system. Users need to install the OpenCV library on their local computer using the below command before they go ahead." }, { "code": null, "e": 26083, "s": 26039, "text": "Install command - pip install opencv-python" }, { "code": null, "e": 26108, "s": 26083, "text": "1. Import OpenCV library" }, { "code": null, "e": 26166, "s": 26108, "text": "2. Initialize the camera using the VideoCapture() method." }, { "code": null, "e": 26174, "s": 26166, "text": "Syntax:" }, { "code": null, "e": 26182, "s": 26174, "text": "Python3" }, { "code": "cam = VideoCapture(0)", "e": 26204, "s": 26182, "text": null }, { "code": null, "e": 26264, "s": 26204, "text": "3. Read input using the camera using the cam.read() method." }, { "code": null, "e": 26272, "s": 26264, "text": "Syntax:" }, { "code": null, "e": 26280, "s": 26272, "text": "Python3" }, { "code": "result, image = cam.read()", "e": 26307, "s": 26280, "text": null }, { "code": null, "e": 26365, "s": 26307, "text": "4. If input image detected without any error, show output" }, { "code": null, "e": 26373, "s": 26365, "text": "Syntax:" }, { "code": null, "e": 26571, "s": 26373, "text": "If result:\n \n # show the image\n imshow(\"GeeksForGeeks\", image)\n \n # save the image\n imwrite(\"GeeksForGeeks.png\", image)\n\nelse:\n Move to this part is input image has some error\n" }, { "code": null, "e": 26579, "s": 26571, "text": "Python3" }, { "code": "# program to capture single image from webcam in python # importing OpenCV libraryfrom cv2 import * # initialize the camera# If you have multiple camera connected with # current device, assign a value in cam_port # variable according to thatcam_port = 0cam = VideoCapture(cam_port) # reading the input using the cameraresult, image = cam.read() # If image will detected without any error, # show resultif result: # showing result, it take frame name and image # output imshow(\"GeeksForGeeks\", image) # saving image in local storage imwrite(\"GeeksForGeeks.png\", image) # If keyboard interrupt occurs, destroy image # window waitKey(0) destroyWindow(\"GeeksForGeeks\") # If captured image is corrupted, moving to else partelse: print(\"No image detected. Please! try again\")", "e": 27392, "s": 26579, "text": null }, { "code": null, "e": 27400, "s": 27392, "text": "Output:" }, { "code": null, "e": 27597, "s": 27400, "text": "PyGame.camera() camera initializer supports only Linux operating system and Currently, It is not compatible with Windows. To install PyGame in Linux, Enter the below command on the Linux terminal." }, { "code": null, "e": 27628, "s": 27597, "text": "1. Import pygame.camera module" }, { "code": null, "e": 27685, "s": 27628, "text": "2. Initialize the camera using the camera.init() method." }, { "code": null, "e": 27693, "s": 27685, "text": "Python3" }, { "code": "pygame.camera.init()", "e": 27714, "s": 27693, "text": null }, { "code": null, "e": 27779, "s": 27714, "text": "3. Detect all available cameras using the list_cameras() method." }, { "code": null, "e": 27787, "s": 27779, "text": "Python3" }, { "code": "camlist = pygame.camera.list_cameras()", "e": 27826, "s": 27787, "text": null }, { "code": null, "e": 27868, "s": 27826, "text": "4. check if the camera is detected or not" }, { "code": null, "e": 27876, "s": 27868, "text": "Syntax:" }, { "code": null, "e": 28204, "s": 27876, "text": "if camlist:\n \n # Initialize and start camera \n cam = pygame.camera.Camera(camlist[0], (640, 480))\n cam.start()\n \n # capturing the single image\n image = cam.get_image()\n \n # saving the image\n pygame.image.save(image, \"filename.jpg\")\n \nelse:\n if camera is not detected the moving to this part" }, { "code": null, "e": 28212, "s": 28204, "text": "Python3" }, { "code": "# Python program to capture a single image# using pygame library # importing the pygame libraryimport pygameimport pygame.camera # initializing the camerapygame.camera.init() # make the list of all available camerascamlist = pygame.camera.list_cameras() # if camera is detected or notif camlist: # initializing the cam variable with default camera cam = pygame.camera.Camera(camlist[0], (640, 480)) # opening the camera cam.start() # capturing the single image image = cam.get_image() # saving the image pygame.image.save(image, \"filename.jpg\") # if camera is not detected the moving to else partelse: print(\"No camera on current device\")", "e": 28892, "s": 28212, "text": null }, { "code": null, "e": 28900, "s": 28892, "text": "Output:" }, { "code": null, "e": 28916, "s": 28900, "text": "rajeev0719singh" }, { "code": null, "e": 28931, "s": 28916, "text": "adnanirshad158" }, { "code": null, "e": 28945, "s": 28931, "text": "Python-OpenCV" }, { "code": null, "e": 28959, "s": 28945, "text": "Python-PyGame" }, { "code": null, "e": 28966, "s": 28959, "text": "Python" }, { "code": null, "e": 29064, "s": 28966, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29096, "s": 29064, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29138, "s": 29096, "text": "Check if element exists in list in Python" }, { "code": null, "e": 29180, "s": 29138, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 29207, "s": 29180, "text": "Python Classes and Objects" }, { "code": null, "e": 29263, "s": 29207, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 29285, "s": 29263, "text": "Defaultdict in Python" }, { "code": null, "e": 29324, "s": 29285, "text": "Python | Get unique values from a list" }, { "code": null, "e": 29355, "s": 29324, "text": "Python | os.path.join() method" }, { "code": null, "e": 29384, "s": 29355, "text": "Create a directory in Python" } ]
Array Multiplier in Digital Logic - GeeksforGeeks
30 Dec, 2019 An array multiplier is a digital combinational circuit used for multiplying two binary numbers by employing an array of full adders and half adders. This array is used for the nearly simultaneous addition of the various product terms involved. To form the various product terms, an array of AND gates is used before the Adder array. Checking the bits of the multiplier one at a time and forming partial products is a sequential operation that requires a sequence of add and shift micro-operations. The multiplication of two binary numbers can be done with one micro-operation by means of a combinational circuit that forms the product bits all at once. This is a fast way of multiplying two numbers since all it takes is the time for the signals to propagate through the gates that form the multiplication array. However, an array multiplier requires a large number of gates, and for this reason it was not economical until the development of integrated circuits. For implementation of array multiplier with a combinational circuit, consider the multiplication of two 2-bit numbers as shown in figure. The multiplicand bits are b1 and b0, the multiplier bits are a1 and a0, and the product is c3c2c1c0 Assuming A = a1a0 and B= b1b0, the various bits of the final product term P can be written as:-1. P(0)= a0b02. P(1)=a1b0 + b1a03. P(2) = a1b1 + c1 where c1 is the carry generated during the addition for the P(1) term.4. P(3) = c2 where c2 is the carry generated during the addition for the P(2) term. For the above multiplication, an array of four AND gates is required to form the various product terms like a0b0 etc. and then an adder array is required to calculate the sums involving the various product terms and carry combinations mentioned in the above equations in order to get the final Product bits. The first partial product is formed by multiplying a0 by b1, b0. The multiplication of two bits such as a0 and b0 produces a 1 if both bits are 1; otherwise, it produces 0. This is identical to an AND operation and can be implemented with an AND gate.The first partial product is formed by means of two AND gates.The second partial product is formed by multiplying a1 by b1b0 and is shifted one position to the left.The above two partial products are added with two half-adder(HA) circuits. Usually there are more bits in the partial products and it will be necessary to use full-adders to produce the sum.Note that the least significant bit of the product does not have to go through an adder since it is formed by the output of the first AND gate. The first partial product is formed by multiplying a0 by b1, b0. The multiplication of two bits such as a0 and b0 produces a 1 if both bits are 1; otherwise, it produces 0. This is identical to an AND operation and can be implemented with an AND gate. The first partial product is formed by means of two AND gates. The second partial product is formed by multiplying a1 by b1b0 and is shifted one position to the left. The above two partial products are added with two half-adder(HA) circuits. Usually there are more bits in the partial products and it will be necessary to use full-adders to produce the sum. Note that the least significant bit of the product does not have to go through an adder since it is formed by the output of the first AND gate. A combinational circuit binary multiplier with more bits can be constructed in similar fashion. A bit of the multiplier is ANDed with each bit of the multiplicand in as many levels as there are bits in the multiplier. The binary output in each level of AND gates is added in parallel with the partial product of the previous level to form a new partial product. The last level produces the product. For j multiplier bits and k multiplicand we need j*k AND gates and (j-1) k-bit adders to produce a product of j+k bits. Computer Organization & Architecture Digital Electronics & Logic Design GATE CS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Direct Access Media (DMA) Controller in Computer Architecture Computer Organization and Architecture | Pipelining | Set 2 (Dependencies and Data Hazard) Architecture of 8085 microprocessor Pin diagram of 8086 microprocessor I2C Communication Protocol Full Adder in Digital Logic Introduction of K-Map (Karnaugh Map) Full Subtractor in Digital Logic Shift Registers in Digital Logic 4-bit binary Adder-Subtractor
[ { "code": null, "e": 26049, "s": 26021, "text": "\n30 Dec, 2019" }, { "code": null, "e": 26382, "s": 26049, "text": "An array multiplier is a digital combinational circuit used for multiplying two binary numbers by employing an array of full adders and half adders. This array is used for the nearly simultaneous addition of the various product terms involved. To form the various product terms, an array of AND gates is used before the Adder array." }, { "code": null, "e": 27013, "s": 26382, "text": "Checking the bits of the multiplier one at a time and forming partial products is a sequential operation that requires a sequence of add and shift micro-operations. The multiplication of two binary numbers can be done with one micro-operation by means of a combinational circuit that forms the product bits all at once. This is a fast way of multiplying two numbers since all it takes is the time for the signals to propagate through the gates that form the multiplication array. However, an array multiplier requires a large number of gates, and for this reason it was not economical until the development of integrated circuits." }, { "code": null, "e": 27242, "s": 27013, "text": "For implementation of array multiplier with a combinational circuit, consider the multiplication of two 2-bit numbers as shown in figure. The multiplicand bits are b1 and b0, the multiplier bits are a1 and a0, and the product is" }, { "code": null, "e": 27251, "s": 27242, "text": "c3c2c1c0" }, { "code": null, "e": 27552, "s": 27251, "text": "Assuming A = a1a0 and B= b1b0, the various bits of the final product term P can be written as:-1. P(0)= a0b02. P(1)=a1b0 + b1a03. P(2) = a1b1 + c1 where c1 is the carry generated during the addition for the P(1) term.4. P(3) = c2 where c2 is the carry generated during the addition for the P(2) term." }, { "code": null, "e": 27860, "s": 27552, "text": "For the above multiplication, an array of four AND gates is required to form the various product terms like a0b0 etc. and then an adder array is required to calculate the sums involving the various product terms and carry combinations mentioned in the above equations in order to get the final Product bits." }, { "code": null, "e": 28610, "s": 27860, "text": "The first partial product is formed by multiplying a0 by b1, b0. The multiplication of two bits such as a0 and b0 produces a 1 if both bits are 1; otherwise, it produces 0. This is identical to an AND operation and can be implemented with an AND gate.The first partial product is formed by means of two AND gates.The second partial product is formed by multiplying a1 by b1b0 and is shifted one position to the left.The above two partial products are added with two half-adder(HA) circuits. Usually there are more bits in the partial products and it will be necessary to use full-adders to produce the sum.Note that the least significant bit of the product does not have to go through an adder since it is formed by the output of the first AND gate." }, { "code": null, "e": 28862, "s": 28610, "text": "The first partial product is formed by multiplying a0 by b1, b0. The multiplication of two bits such as a0 and b0 produces a 1 if both bits are 1; otherwise, it produces 0. This is identical to an AND operation and can be implemented with an AND gate." }, { "code": null, "e": 28925, "s": 28862, "text": "The first partial product is formed by means of two AND gates." }, { "code": null, "e": 29029, "s": 28925, "text": "The second partial product is formed by multiplying a1 by b1b0 and is shifted one position to the left." }, { "code": null, "e": 29220, "s": 29029, "text": "The above two partial products are added with two half-adder(HA) circuits. Usually there are more bits in the partial products and it will be necessary to use full-adders to produce the sum." }, { "code": null, "e": 29364, "s": 29220, "text": "Note that the least significant bit of the product does not have to go through an adder since it is formed by the output of the first AND gate." }, { "code": null, "e": 29883, "s": 29364, "text": "A combinational circuit binary multiplier with more bits can be constructed in similar fashion. A bit of the multiplier is ANDed with each bit of the multiplicand in as many levels as there are bits in the multiplier. The binary output in each level of AND gates is added in parallel with the partial product of the previous level to form a new partial product. The last level produces the product. For j multiplier bits and k multiplicand we need j*k AND gates and (j-1) k-bit adders to produce a product of j+k bits." }, { "code": null, "e": 29920, "s": 29883, "text": "Computer Organization & Architecture" }, { "code": null, "e": 29955, "s": 29920, "text": "Digital Electronics & Logic Design" }, { "code": null, "e": 29963, "s": 29955, "text": "GATE CS" }, { "code": null, "e": 30061, "s": 29963, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30123, "s": 30061, "text": "Direct Access Media (DMA) Controller in Computer Architecture" }, { "code": null, "e": 30214, "s": 30123, "text": "Computer Organization and Architecture | Pipelining | Set 2 (Dependencies and Data Hazard)" }, { "code": null, "e": 30250, "s": 30214, "text": "Architecture of 8085 microprocessor" }, { "code": null, "e": 30285, "s": 30250, "text": "Pin diagram of 8086 microprocessor" }, { "code": null, "e": 30312, "s": 30285, "text": "I2C Communication Protocol" }, { "code": null, "e": 30340, "s": 30312, "text": "Full Adder in Digital Logic" }, { "code": null, "e": 30377, "s": 30340, "text": "Introduction of K-Map (Karnaugh Map)" }, { "code": null, "e": 30410, "s": 30377, "text": "Full Subtractor in Digital Logic" }, { "code": null, "e": 30443, "s": 30410, "text": "Shift Registers in Digital Logic" } ]
Recursion in Python - GeeksforGeeks
28 Jul, 2020 The term Recursion can be defined as the process of defining something in terms of itself. In simple words, it is a process in which a function calls itself directly or indirectly. Advantages of using recursion A complicated function can be split down into smaller sub-problems utilizing recursion. Sequence creation is simpler through recursion than utilizing any nested iteration. Recursive functions render the code look simple and effective. Disadvantages of using recursion A lot of memory and time is taken through recursive calls which makes it expensive for use. Recursive functions are challenging to debug. The reasoning behind recursion can sometimes be tough to think through. Syntax: def func(): <-- | | (recursive call) | func() ---- Example 1:A Fibonacci sequence is the integer sequence of 0, 1, 1, 2, 3, 5, 8.... # Program to print the fibonacci series upto n_terms # Recursive functiondef recursive_fibonacci(n): if n <= 1: return n else: return(recursive_fibonacci(n-1) + recursive_fibonacci(n-2)) n_terms = 10 # check if the number of terms is validif n_terms <= 0: print("Invalid input ! Please input a positive value")else: print("Fibonacci series:") for i in range(n_terms): print(recursive_fibonacci(i)) Output: Fibonacci series: 0 1 1 2 3 5 8 13 21 34 Example 2:The factorial of 6 is denoted as 6! = 1*2*3*4*5*6 = 720. # Program to print factorial of a number # recursively. # Recursive functiondef recursive_factorial(n): if n == 1: return n else: return n * recursive_factorial(n-1) # user inputnum = 6 # check if the input is valid or notif num < 0: print("Invalid input ! Please enter a positive number.") elif num == 0: print("Factorial of number 0 is 1") else: print("Factorial of number", num, "=", recursive_factorial(num)) Output: Factorial of number 6 = 720 A unique type of recursion where the last procedure of a function is a recursive call. The recursion may be automated away by performing the request in the current stack frame and returning the output instead of generating a new stack frame. The tail-recursion may be optimized by the compiler which makes it better than non-tail recursive functions. Is it possible to optimize a program by making use of a tail-recursive function instead of non-tail recursive function?Considering the function given below in order to calculate the factorial of n, we can observe that the function looks like a tail-recursive at first but it is a non-tail-recursive function. If we observe closely, we can see that the value returned by Recur_facto(n-1) is used in Recur_facto(n), so the call to Recur_facto(n-1) is not the last thing done by Recur_facto(n). # Program to calculate factorial of a number# using a Non-Tail-Recursive function. # non-tail recursive functiondef Recur_facto(n): if (n == 0): return 1 return n * Recur_facto(n-1) # print the resultprint(Recur_facto(6)) Output: 720 We can write the given function Recur_facto as a tail-recursive function. The idea is to use one more argument and in the second argument, we accommodate the value of the factorial. When n reaches 0, return the final value of the factorial of the desired number. # Program to calculate factorial of a number# using a Tail-Recursive function. # A tail recursive function def Recur_facto(n, a = 1): if (n == 0): return a return Recur_facto(n - 1, n * a) # print the resultprint(Recur_facto(6)) Output: 720 python-basics tail-recursion 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": 26048, "s": 26020, "text": "\n28 Jul, 2020" }, { "code": null, "e": 26229, "s": 26048, "text": "The term Recursion can be defined as the process of defining something in terms of itself. In simple words, it is a process in which a function calls itself directly or indirectly." }, { "code": null, "e": 26259, "s": 26229, "text": "Advantages of using recursion" }, { "code": null, "e": 26347, "s": 26259, "text": "A complicated function can be split down into smaller sub-problems utilizing recursion." }, { "code": null, "e": 26431, "s": 26347, "text": "Sequence creation is simpler through recursion than utilizing any nested iteration." }, { "code": null, "e": 26494, "s": 26431, "text": "Recursive functions render the code look simple and effective." }, { "code": null, "e": 26527, "s": 26494, "text": "Disadvantages of using recursion" }, { "code": null, "e": 26619, "s": 26527, "text": "A lot of memory and time is taken through recursive calls which makes it expensive for use." }, { "code": null, "e": 26665, "s": 26619, "text": "Recursive functions are challenging to debug." }, { "code": null, "e": 26737, "s": 26665, "text": "The reasoning behind recursion can sometimes be tough to think through." }, { "code": null, "e": 26745, "s": 26737, "text": "Syntax:" }, { "code": null, "e": 26843, "s": 26745, "text": "def func(): <--\n |\n | (recursive call)\n |\n func() ----\n" }, { "code": null, "e": 26925, "s": 26843, "text": "Example 1:A Fibonacci sequence is the integer sequence of 0, 1, 1, 2, 3, 5, 8...." }, { "code": "# Program to print the fibonacci series upto n_terms # Recursive functiondef recursive_fibonacci(n): if n <= 1: return n else: return(recursive_fibonacci(n-1) + recursive_fibonacci(n-2)) n_terms = 10 # check if the number of terms is validif n_terms <= 0: print(\"Invalid input ! Please input a positive value\")else: print(\"Fibonacci series:\") for i in range(n_terms): print(recursive_fibonacci(i))", "e": 27356, "s": 26925, "text": null }, { "code": null, "e": 27364, "s": 27356, "text": "Output:" }, { "code": null, "e": 27406, "s": 27364, "text": "Fibonacci series:\n0\n1\n1\n2\n3\n5\n8\n13\n21\n34\n" }, { "code": null, "e": 27473, "s": 27406, "text": "Example 2:The factorial of 6 is denoted as 6! = 1*2*3*4*5*6 = 720." }, { "code": "# Program to print factorial of a number # recursively. # Recursive functiondef recursive_factorial(n): if n == 1: return n else: return n * recursive_factorial(n-1) # user inputnum = 6 # check if the input is valid or notif num < 0: print(\"Invalid input ! Please enter a positive number.\") elif num == 0: print(\"Factorial of number 0 is 1\") else: print(\"Factorial of number\", num, \"=\", recursive_factorial(num)) ", "e": 27930, "s": 27473, "text": null }, { "code": null, "e": 27938, "s": 27930, "text": "Output:" }, { "code": null, "e": 27966, "s": 27938, "text": "Factorial of number 6 = 720" }, { "code": null, "e": 28317, "s": 27966, "text": "A unique type of recursion where the last procedure of a function is a recursive call. The recursion may be automated away by performing the request in the current stack frame and returning the output instead of generating a new stack frame. The tail-recursion may be optimized by the compiler which makes it better than non-tail recursive functions." }, { "code": null, "e": 28809, "s": 28317, "text": "Is it possible to optimize a program by making use of a tail-recursive function instead of non-tail recursive function?Considering the function given below in order to calculate the factorial of n, we can observe that the function looks like a tail-recursive at first but it is a non-tail-recursive function. If we observe closely, we can see that the value returned by Recur_facto(n-1) is used in Recur_facto(n), so the call to Recur_facto(n-1) is not the last thing done by Recur_facto(n)." }, { "code": "# Program to calculate factorial of a number# using a Non-Tail-Recursive function. # non-tail recursive functiondef Recur_facto(n): if (n == 0): return 1 return n * Recur_facto(n-1) # print the resultprint(Recur_facto(6))", "e": 29060, "s": 28809, "text": null }, { "code": null, "e": 29068, "s": 29060, "text": "Output:" }, { "code": null, "e": 29072, "s": 29068, "text": "720" }, { "code": null, "e": 29335, "s": 29072, "text": "We can write the given function Recur_facto as a tail-recursive function. The idea is to use one more argument and in the second argument, we accommodate the value of the factorial. When n reaches 0, return the final value of the factorial of the desired number." }, { "code": "# Program to calculate factorial of a number# using a Tail-Recursive function. # A tail recursive function def Recur_facto(n, a = 1): if (n == 0): return a return Recur_facto(n - 1, n * a) # print the resultprint(Recur_facto(6))", "e": 29593, "s": 29335, "text": null }, { "code": null, "e": 29601, "s": 29593, "text": "Output:" }, { "code": null, "e": 29605, "s": 29601, "text": "720" }, { "code": null, "e": 29619, "s": 29605, "text": "python-basics" }, { "code": null, "e": 29634, "s": 29619, "text": "tail-recursion" }, { "code": null, "e": 29641, "s": 29634, "text": "Python" }, { "code": null, "e": 29739, "s": 29641, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29757, "s": 29739, "text": "Python Dictionary" }, { "code": null, "e": 29792, "s": 29757, "text": "Read a file line by line in Python" }, { "code": null, "e": 29824, "s": 29792, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29846, "s": 29824, "text": "Enumerate() in Python" }, { "code": null, "e": 29888, "s": 29846, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 29918, "s": 29888, "text": "Iterate over a list in Python" }, { "code": null, "e": 29944, "s": 29918, "text": "Python String | replace()" }, { "code": null, "e": 29973, "s": 29944, "text": "*args and **kwargs in Python" }, { "code": null, "e": 30017, "s": 29973, "text": "Reading and Writing to text files in Python" } ]
Count of arrangements of RGB balls with no duplicates in a set - GeeksforGeeks
17 Jan, 2022 Given R red balls, G green balls, B blue balls. A set can have 1, 2, or 3 balls. Also, a set could have all balls of the same color or all balls of different colors. All other possible sets are not considered valid. The task is to calculate the minimum possible sets required to place all balls. Examples: Input: R = 4, G = 2, B = 4Output: 4Explanation: There can be 4 sets which satisfies all condition mentioned above {R, R, R}, {B, B, B}, {G, R}, {G, B}.Therefore, the answer is 4. Input: R = 1, G = 7, B = 1Output: 3Explanation: There are 3 valid sets {R, G, B}, {G, G, G}, {G, G, G} Approach: This problem is analysis-based. Follow the steps below to solve the given problem. The problem statement can be solved with careful case analysis. Without loss of generality assume that R<=G<=B. So there will be at least R sets formed. Subtract R from G and B. All the sets formed from this step will have different balls in them. The remaining balls will be 0, G – R, B – R. For the remaining balls form sets of the same balls. After the above step remaining balls will be 0, (G – R)%3, (B – R)%3. Now there can be 3 cases: 2nd term is 0 and 3rd term is zero. No extra set will be required. (2nd term is 1 and 3rd term is 1) or (2nd term is 0 and 3rd term is 2 or vice versa). 1 extra set will be required. In all other cases, 2 more sets will be required. Check all the above conditions carefully and print the answer. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ Program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Function to calculate minimum sets// required with given conditionsint minimumSetBalls(int R, int G, int B){ // Push values R, G, B // in a vector and sort them vector<int> balls; balls.push_back(R); balls.push_back(G); balls.push_back(B); // Sort the vector sort(balls.begin(), balls.end()); // Store the answer int ans = 0; ans += balls[0]; balls[1] -= balls[0]; balls[2] -= balls[0]; balls[0] = 0; // Check all mentioned conditions ans += balls[1] / 3; balls[1] %= 3; ans += balls[2] / 3; balls[2] %= 3; if (balls[1] == 0 && balls[2] == 0) { // No extra set required } else if (balls[1] == 1 && balls[2] == 1) { ans++; // 1 extra set is required } else if ((balls[1] == 2 && balls[2] == 0) || (balls[1] == 0 && balls[2] == 2)) { ans++; // 1 extra set is required } else { // 2 extra sets will be required ans += 2; } return ans;} // Driver Codeint main(){ int R = 4, G = 2, B = 4; cout << minimumSetBalls(R, G, B);} // Java program for the above approachimport java.io.*;import java.util.*; public class GFG{ // Function to calculate minimum sets// required with given conditionsstatic int minimumSetBalls(int R, int G, int B){ // Push values R, G, B // in a vector and sort them ArrayList<Integer> balls = new ArrayList<Integer>(); balls.add(R); balls.add(G); balls.add(B); // Sort the vector Collections.sort(balls); ; // Store the answer int ans = 0; ans += balls.get(0); balls.set(1,balls.get(1) - balls.get(0)); balls.set(2,balls.get(2) - balls.get(0)); balls.set(0,0); // Check all mentioned conditions ans += balls.get(1) / 3; balls.set(1, balls.get(1) % 3); ans += balls.get(2) / 3; balls.set(2,balls.get(2) % 3); if (balls.get(1) == 0 && balls.get(2) == 0) { // No extra set required } else if (balls.get(1) == 1 && balls.get(2) == 1) { ans++; // 1 extra set is required } else if ((balls.get(1) == 2 && balls.get(2) == 0) || (balls.get(1) == 0 && balls.get(2) == 2)) { ans++; // 1 extra set is required } else { // 2 extra sets will be required ans += 2; } return ans;} // Driver Codepublic static void main(String []args){ int R = 4, G = 2, B = 4; System.out.println( minimumSetBalls(R, G, B));}} // This code is contributed by AnkThon # Python3 Program to implement the above approach # Function to calculate minimum sets# required with given conditionsdef minimumSetBalls(R, G, B) : # Push values R, G, B # in a vector and sort them balls = []; balls.append(R); balls.append(G); balls.append(B); # Sort the vector balls.sort(); # Store the answer ans = 0; ans += balls[0]; balls[1] -= balls[0]; balls[2] -= balls[0]; balls[0] = 0; # Check all mentioned conditions ans += balls[1] // 3; balls[1] %= 3; ans += balls[2] // 3; balls[2] %= 3; if (balls[1] == 0 and balls[2] == 0) : pass elif (balls[1] == 1 and balls[2] == 1) : ans += 1; # 1 extra set is required elif ((balls[1] == 2 and balls[2] == 0) or (balls[1] == 0 and balls[2] == 2)) : ans += 1; # 1 extra set is required else : # 2 extra sets will be required ans += 2; return ans; # Driver Codeif __name__ == "__main__" : R = 4; G = 2; B = 4; print(minimumSetBalls(R, G, B)); # This code is contributed by AnkThon // C# program for the above approachusing System;using System.Collections.Generic; class GFG{ // Function to calculate minimum sets// required with given conditionsstatic int minimumSetBalls(int R, int G, int B){ // Push values R, G, B // in a vector and sort them List<int> balls = new List<int>(); balls.Add(R); balls.Add(G); balls.Add(B); // Sort the vector balls.Sort(); // Store the answer int ans = 0; ans += balls[0]; balls[1] -= balls[0]; balls[2] -= balls[0]; balls[0] = 0; // Check all mentioned conditions ans += balls[1] / 3; balls[1] %= 3; ans += balls[2] / 3; balls[2] %= 3; if (balls[1] == 0 && balls[2] == 0) { // No extra set required } else if (balls[1] == 1 && balls[2] == 1) { ans++; // 1 extra set is required } else if ((balls[1] == 2 && balls[2] == 0) || (balls[1] == 0 && balls[2] == 2)) { ans++; // 1 extra set is required } else { // 2 extra sets will be required ans += 2; } return ans;} // Driver Codepublic static void Main(){ int R = 4, G = 2, B = 4; Console.WriteLine( minimumSetBalls(R, G, B));}} // This code is contributed by sanjoy_62. <script> // JavaScript Program to implement // the above approach // Function to calculate minimum sets // required with given conditions function minimumSetBalls(R, G, B) { // Push values R, G, B // in a vector and sort them let balls = []; balls.push(R); balls.push(G); balls.push(B); // Sort the vector balls.sort(function (a, b) { return a - b }) // Store the answer let ans = 0; ans += balls[0]; balls[1] -= balls[0]; balls[2] -= balls[0]; balls[0] = 0; // Check all mentioned conditions ans += Math.floor(balls[1] / 3); balls[1] %= 3; ans += Math.floor(balls[2] / 3); balls[2] %= 3; if (balls[1] == 0 && balls[2] == 0) { // No extra set required } else if (balls[1] == 1 && balls[2] == 1) { ans++; // 1 extra set is required } else if ((balls[1] == 2 && balls[2] == 0) || (balls[1] == 0 && balls[2] == 2)) { ans++; // 1 extra set is required } else { // 2 extra sets will be required ans += 2; } return ans; } // Driver Code let R = 4, G = 2, B = 4; document.write(minimumSetBalls(R, G, B)); // This code is contributed by Potta Lokesh </script> 4 Time Complexity: O(1) Auxiliary Space: O(1) sanjoy_62 ankthon lokeshpotta20 simranarora5sos Combinatorial Greedy Greedy Combinatorial Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Ways to sum to N using Natural Numbers up to K with repetitions allowed Combinations with repetitions Generate all possible combinations of K numbers that sums to N Largest substring with same Characters Generate all possible combinations of at most X characters from a given array Dijkstra's shortest path algorithm | Greedy Algo-7 Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5 Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2 Program for array rotation Huffman Coding | Greedy Algo-3
[ { "code": null, "e": 26697, "s": 26669, "text": "\n17 Jan, 2022" }, { "code": null, "e": 26993, "s": 26697, "text": "Given R red balls, G green balls, B blue balls. A set can have 1, 2, or 3 balls. Also, a set could have all balls of the same color or all balls of different colors. All other possible sets are not considered valid. The task is to calculate the minimum possible sets required to place all balls." }, { "code": null, "e": 27004, "s": 26993, "text": "Examples: " }, { "code": null, "e": 27184, "s": 27004, "text": "Input: R = 4, G = 2, B = 4Output: 4Explanation: There can be 4 sets which satisfies all condition mentioned above {R, R, R}, {B, B, B}, {G, R}, {G, B}.Therefore, the answer is 4. " }, { "code": null, "e": 27287, "s": 27184, "text": "Input: R = 1, G = 7, B = 1Output: 3Explanation: There are 3 valid sets {R, G, B}, {G, G, G}, {G, G, G}" }, { "code": null, "e": 27381, "s": 27287, "text": "Approach: This problem is analysis-based. Follow the steps below to solve the given problem. " }, { "code": null, "e": 27445, "s": 27381, "text": "The problem statement can be solved with careful case analysis." }, { "code": null, "e": 27493, "s": 27445, "text": "Without loss of generality assume that R<=G<=B." }, { "code": null, "e": 27629, "s": 27493, "text": "So there will be at least R sets formed. Subtract R from G and B. All the sets formed from this step will have different balls in them." }, { "code": null, "e": 27727, "s": 27629, "text": "The remaining balls will be 0, G – R, B – R. For the remaining balls form sets of the same balls." }, { "code": null, "e": 27797, "s": 27727, "text": "After the above step remaining balls will be 0, (G – R)%3, (B – R)%3." }, { "code": null, "e": 27823, "s": 27797, "text": "Now there can be 3 cases:" }, { "code": null, "e": 27890, "s": 27823, "text": "2nd term is 0 and 3rd term is zero. No extra set will be required." }, { "code": null, "e": 28006, "s": 27890, "text": "(2nd term is 1 and 3rd term is 1) or (2nd term is 0 and 3rd term is 2 or vice versa). 1 extra set will be required." }, { "code": null, "e": 28056, "s": 28006, "text": "In all other cases, 2 more sets will be required." }, { "code": null, "e": 28119, "s": 28056, "text": "Check all the above conditions carefully and print the answer." }, { "code": null, "e": 28170, "s": 28119, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 28174, "s": 28170, "text": "C++" }, { "code": null, "e": 28179, "s": 28174, "text": "Java" }, { "code": null, "e": 28187, "s": 28179, "text": "Python3" }, { "code": null, "e": 28190, "s": 28187, "text": "C#" }, { "code": null, "e": 28201, "s": 28190, "text": "Javascript" }, { "code": "// C++ Program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Function to calculate minimum sets// required with given conditionsint minimumSetBalls(int R, int G, int B){ // Push values R, G, B // in a vector and sort them vector<int> balls; balls.push_back(R); balls.push_back(G); balls.push_back(B); // Sort the vector sort(balls.begin(), balls.end()); // Store the answer int ans = 0; ans += balls[0]; balls[1] -= balls[0]; balls[2] -= balls[0]; balls[0] = 0; // Check all mentioned conditions ans += balls[1] / 3; balls[1] %= 3; ans += balls[2] / 3; balls[2] %= 3; if (balls[1] == 0 && balls[2] == 0) { // No extra set required } else if (balls[1] == 1 && balls[2] == 1) { ans++; // 1 extra set is required } else if ((balls[1] == 2 && balls[2] == 0) || (balls[1] == 0 && balls[2] == 2)) { ans++; // 1 extra set is required } else { // 2 extra sets will be required ans += 2; } return ans;} // Driver Codeint main(){ int R = 4, G = 2, B = 4; cout << minimumSetBalls(R, G, B);}", "e": 29419, "s": 28201, "text": null }, { "code": "// Java program for the above approachimport java.io.*;import java.util.*; public class GFG{ // Function to calculate minimum sets// required with given conditionsstatic int minimumSetBalls(int R, int G, int B){ // Push values R, G, B // in a vector and sort them ArrayList<Integer> balls = new ArrayList<Integer>(); balls.add(R); balls.add(G); balls.add(B); // Sort the vector Collections.sort(balls); ; // Store the answer int ans = 0; ans += balls.get(0); balls.set(1,balls.get(1) - balls.get(0)); balls.set(2,balls.get(2) - balls.get(0)); balls.set(0,0); // Check all mentioned conditions ans += balls.get(1) / 3; balls.set(1, balls.get(1) % 3); ans += balls.get(2) / 3; balls.set(2,balls.get(2) % 3); if (balls.get(1) == 0 && balls.get(2) == 0) { // No extra set required } else if (balls.get(1) == 1 && balls.get(2) == 1) { ans++; // 1 extra set is required } else if ((balls.get(1) == 2 && balls.get(2) == 0) || (balls.get(1) == 0 && balls.get(2) == 2)) { ans++; // 1 extra set is required } else { // 2 extra sets will be required ans += 2; } return ans;} // Driver Codepublic static void main(String []args){ int R = 4, G = 2, B = 4; System.out.println( minimumSetBalls(R, G, B));}} // This code is contributed by AnkThon", "e": 30877, "s": 29419, "text": null }, { "code": "# Python3 Program to implement the above approach # Function to calculate minimum sets# required with given conditionsdef minimumSetBalls(R, G, B) : # Push values R, G, B # in a vector and sort them balls = []; balls.append(R); balls.append(G); balls.append(B); # Sort the vector balls.sort(); # Store the answer ans = 0; ans += balls[0]; balls[1] -= balls[0]; balls[2] -= balls[0]; balls[0] = 0; # Check all mentioned conditions ans += balls[1] // 3; balls[1] %= 3; ans += balls[2] // 3; balls[2] %= 3; if (balls[1] == 0 and balls[2] == 0) : pass elif (balls[1] == 1 and balls[2] == 1) : ans += 1; # 1 extra set is required elif ((balls[1] == 2 and balls[2] == 0) or (balls[1] == 0 and balls[2] == 2)) : ans += 1; # 1 extra set is required else : # 2 extra sets will be required ans += 2; return ans; # Driver Codeif __name__ == \"__main__\" : R = 4; G = 2; B = 4; print(minimumSetBalls(R, G, B)); # This code is contributed by AnkThon", "e": 31960, "s": 30877, "text": null }, { "code": "// C# program for the above approachusing System;using System.Collections.Generic; class GFG{ // Function to calculate minimum sets// required with given conditionsstatic int minimumSetBalls(int R, int G, int B){ // Push values R, G, B // in a vector and sort them List<int> balls = new List<int>(); balls.Add(R); balls.Add(G); balls.Add(B); // Sort the vector balls.Sort(); // Store the answer int ans = 0; ans += balls[0]; balls[1] -= balls[0]; balls[2] -= balls[0]; balls[0] = 0; // Check all mentioned conditions ans += balls[1] / 3; balls[1] %= 3; ans += balls[2] / 3; balls[2] %= 3; if (balls[1] == 0 && balls[2] == 0) { // No extra set required } else if (balls[1] == 1 && balls[2] == 1) { ans++; // 1 extra set is required } else if ((balls[1] == 2 && balls[2] == 0) || (balls[1] == 0 && balls[2] == 2)) { ans++; // 1 extra set is required } else { // 2 extra sets will be required ans += 2; } return ans;} // Driver Codepublic static void Main(){ int R = 4, G = 2, B = 4; Console.WriteLine( minimumSetBalls(R, G, B));}} // This code is contributed by sanjoy_62.", "e": 33256, "s": 31960, "text": null }, { "code": "<script> // JavaScript Program to implement // the above approach // Function to calculate minimum sets // required with given conditions function minimumSetBalls(R, G, B) { // Push values R, G, B // in a vector and sort them let balls = []; balls.push(R); balls.push(G); balls.push(B); // Sort the vector balls.sort(function (a, b) { return a - b }) // Store the answer let ans = 0; ans += balls[0]; balls[1] -= balls[0]; balls[2] -= balls[0]; balls[0] = 0; // Check all mentioned conditions ans += Math.floor(balls[1] / 3); balls[1] %= 3; ans += Math.floor(balls[2] / 3); balls[2] %= 3; if (balls[1] == 0 && balls[2] == 0) { // No extra set required } else if (balls[1] == 1 && balls[2] == 1) { ans++; // 1 extra set is required } else if ((balls[1] == 2 && balls[2] == 0) || (balls[1] == 0 && balls[2] == 2)) { ans++; // 1 extra set is required } else { // 2 extra sets will be required ans += 2; } return ans; } // Driver Code let R = 4, G = 2, B = 4; document.write(minimumSetBalls(R, G, B)); // This code is contributed by Potta Lokesh </script>", "e": 34893, "s": 33256, "text": null }, { "code": null, "e": 34895, "s": 34893, "text": "4" }, { "code": null, "e": 34941, "s": 34897, "text": "Time Complexity: O(1) Auxiliary Space: O(1)" }, { "code": null, "e": 34951, "s": 34941, "text": "sanjoy_62" }, { "code": null, "e": 34959, "s": 34951, "text": "ankthon" }, { "code": null, "e": 34973, "s": 34959, "text": "lokeshpotta20" }, { "code": null, "e": 34989, "s": 34973, "text": "simranarora5sos" }, { "code": null, "e": 35003, "s": 34989, "text": "Combinatorial" }, { "code": null, "e": 35010, "s": 35003, "text": "Greedy" }, { "code": null, "e": 35017, "s": 35010, "text": "Greedy" }, { "code": null, "e": 35031, "s": 35017, "text": "Combinatorial" }, { "code": null, "e": 35129, "s": 35031, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35201, "s": 35129, "text": "Ways to sum to N using Natural Numbers up to K with repetitions allowed" }, { "code": null, "e": 35231, "s": 35201, "text": "Combinations with repetitions" }, { "code": null, "e": 35294, "s": 35231, "text": "Generate all possible combinations of K numbers that sums to N" }, { "code": null, "e": 35333, "s": 35294, "text": "Largest substring with same Characters" }, { "code": null, "e": 35411, "s": 35333, "text": "Generate all possible combinations of at most X characters from a given array" }, { "code": null, "e": 35462, "s": 35411, "text": "Dijkstra's shortest path algorithm | Greedy Algo-7" }, { "code": null, "e": 35513, "s": 35462, "text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5" }, { "code": null, "e": 35571, "s": 35513, "text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2" }, { "code": null, "e": 35598, "s": 35571, "text": "Program for array rotation" } ]
Matplotlib.pyplot.legend() in Python - GeeksforGeeks
12 Apr, 2020 Matplotlib is one of the most popular Python packages used for data visualization. It is a cross-platform library for making 2D plots from data in arrays. Pyplot is a collection of command style functions that make matplotlib work like MATLAB. Each pyplot function makes some change to a figure: e.g., creates a figure, creates a plotting area in a figure, plots some lines in a plotting area, decorates the plot with labels, etc. A legend is an area describing the elements of the graph. In the matplotlib library, there’s a function called legend() which is used to Place a legend on the axes. The attribute Loc in legend() is used to specify the location of the legend.Default value of loc is loc=”best” (upper left). The strings ‘upper left’, ‘upper right’, ‘lower left’, ‘lower right’ place the legend at the corresponding corner of the axes/figure. The attribute bbox_to_anchor=(x, y) of legend() function is used to specify the coordinates of the legend, and the attribute ncol represents the number of columns that the legend has.It’s default value is 1. Syntax: matplotlib.pyplot.legend([“blue”, “green”], bbox_to_anchor=(0.75, 1.15), ncol=2) The Following are some more attributes of function legend() : shadow: [None or bool] Whether to draw a shadow behind the legend.It’s Default value is None. markerscale: [None or int or float] The relative size of legend markers compared with the originally drawn ones.The Default is None. numpoints: [None or int] The number of marker points in the legend when creating a legend entry for a Line2D (line).The Default is None. fontsize: The font size of the legend.If the value is numeric the size will be the absolute font size in points. facecolor: [None or “inherit” or color] The legend’s background color. edgecolor: [None or “inherit” or color] The legend’s background patch edge color. Example 1: import numpy as npimport matplotlib.pyplot as plt # X-axis valuesx = [1, 2, 3, 4, 5] # Y-axis values y = [1, 4, 9, 16, 25] # Function to plot plt.plot(x, y) # Function add a legend plt.legend(['single element']) # function to show the plotplt.show() Output : Example 2: # importing modulesimport numpy as npimport matplotlib.pyplot as plt # Y-axis valuesy1 = [2, 3, 4.5] # Y-axis values y2 = [1, 1.5, 5] # Function to plot plt.plot(y1)plt.plot(y2) # Function add a legend plt.legend(["blue", "green"], loc ="lower right") # function to show the plotplt.show() Output : Example 3: import numpy as npimport matplotlib.pyplot as plt # X-axis valuesx = np.arange(5) # Y-axis valuesy1 = [1, 2, 3, 4, 5] # Y-axis values y2 = [1, 4, 9, 16, 25] # Function to plot plt.plot(x, y1, label ='Numbers')plt.plot(x, y2, label ='Square of numbers') # Function add a legend plt.legend() # function to show the plotplt.show() Output : Example 4: import numpy as npimport matplotlib.pyplot as plt x = np.linspace(0, 10, 1000)fig, ax = plt.subplots() ax.plot(x, np.sin(x), '--b', label ='Sine')ax.plot(x, np.cos(x), c ='r', label ='Cosine')ax.axis('equal') leg = ax.legend(loc ="lower left"); Output: Example 5: # importing modulesimport numpy as npimport matplotlib.pyplot as plt # X-axis valuesx = [0, 1, 2, 3, 4, 5, 6, 7, 8] # Y-axis valuesy1 = [0, 3, 6, 9, 12, 15, 18, 21, 24]# Y-axis values y2 = [0, 1, 2, 3, 4, 5, 6, 7, 8] # Function to plot plt.plot(y1, label ="y = x")plt.plot(y2, label ="y = 3x") # Function add a legend plt.legend(bbox_to_anchor =(0.75, 1.15), ncol = 2) # function to show the plotplt.show() Output: Python-matplotlib 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 Read a file line by line in Python Taking input in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe
[ { "code": null, "e": 31572, "s": 31544, "text": "\n12 Apr, 2020" }, { "code": null, "e": 32003, "s": 31572, "text": "Matplotlib is one of the most popular Python packages used for data visualization. It is a cross-platform library for making 2D plots from data in arrays. Pyplot is a collection of command style functions that make matplotlib work like MATLAB. Each pyplot function makes some change to a figure: e.g., creates a figure, creates a plotting area in a figure, plots some lines in a plotting area, decorates the plot with labels, etc." }, { "code": null, "e": 32168, "s": 32003, "text": "A legend is an area describing the elements of the graph. In the matplotlib library, there’s a function called legend() which is used to Place a legend on the axes." }, { "code": null, "e": 32427, "s": 32168, "text": "The attribute Loc in legend() is used to specify the location of the legend.Default value of loc is loc=”best” (upper left). The strings ‘upper left’, ‘upper right’, ‘lower left’, ‘lower right’ place the legend at the corresponding corner of the axes/figure." }, { "code": null, "e": 32635, "s": 32427, "text": "The attribute bbox_to_anchor=(x, y) of legend() function is used to specify the coordinates of the legend, and the attribute ncol represents the number of columns that the legend has.It’s default value is 1." }, { "code": null, "e": 32643, "s": 32635, "text": "Syntax:" }, { "code": null, "e": 32724, "s": 32643, "text": "matplotlib.pyplot.legend([“blue”, “green”], bbox_to_anchor=(0.75, 1.15), ncol=2)" }, { "code": null, "e": 32786, "s": 32724, "text": "The Following are some more attributes of function legend() :" }, { "code": null, "e": 32880, "s": 32786, "text": "shadow: [None or bool] Whether to draw a shadow behind the legend.It’s Default value is None." }, { "code": null, "e": 33013, "s": 32880, "text": "markerscale: [None or int or float] The relative size of legend markers compared with the originally drawn ones.The Default is None." }, { "code": null, "e": 33150, "s": 33013, "text": "numpoints: [None or int] The number of marker points in the legend when creating a legend entry for a Line2D (line).The Default is None." }, { "code": null, "e": 33263, "s": 33150, "text": "fontsize: The font size of the legend.If the value is numeric the size will be the absolute font size in points." }, { "code": null, "e": 33334, "s": 33263, "text": "facecolor: [None or “inherit” or color] The legend’s background color." }, { "code": null, "e": 33416, "s": 33334, "text": "edgecolor: [None or “inherit” or color] The legend’s background patch edge color." }, { "code": null, "e": 33427, "s": 33416, "text": "Example 1:" }, { "code": "import numpy as npimport matplotlib.pyplot as plt # X-axis valuesx = [1, 2, 3, 4, 5] # Y-axis values y = [1, 4, 9, 16, 25] # Function to plot plt.plot(x, y) # Function add a legend plt.legend(['single element']) # function to show the plotplt.show()", "e": 33684, "s": 33427, "text": null }, { "code": null, "e": 33693, "s": 33684, "text": "Output :" }, { "code": null, "e": 33704, "s": 33693, "text": "Example 2:" }, { "code": "# importing modulesimport numpy as npimport matplotlib.pyplot as plt # Y-axis valuesy1 = [2, 3, 4.5] # Y-axis values y2 = [1, 1.5, 5] # Function to plot plt.plot(y1)plt.plot(y2) # Function add a legend plt.legend([\"blue\", \"green\"], loc =\"lower right\") # function to show the plotplt.show()", "e": 34001, "s": 33704, "text": null }, { "code": null, "e": 34010, "s": 34001, "text": "Output :" }, { "code": null, "e": 34021, "s": 34010, "text": "Example 3:" }, { "code": "import numpy as npimport matplotlib.pyplot as plt # X-axis valuesx = np.arange(5) # Y-axis valuesy1 = [1, 2, 3, 4, 5] # Y-axis values y2 = [1, 4, 9, 16, 25] # Function to plot plt.plot(x, y1, label ='Numbers')plt.plot(x, y2, label ='Square of numbers') # Function add a legend plt.legend() # function to show the plotplt.show()", "e": 34357, "s": 34021, "text": null }, { "code": null, "e": 34366, "s": 34357, "text": "Output :" }, { "code": null, "e": 34377, "s": 34366, "text": "Example 4:" }, { "code": "import numpy as npimport matplotlib.pyplot as plt x = np.linspace(0, 10, 1000)fig, ax = plt.subplots() ax.plot(x, np.sin(x), '--b', label ='Sine')ax.plot(x, np.cos(x), c ='r', label ='Cosine')ax.axis('equal') leg = ax.legend(loc =\"lower left\");", "e": 34625, "s": 34377, "text": null }, { "code": null, "e": 34633, "s": 34625, "text": "Output:" }, { "code": null, "e": 34644, "s": 34633, "text": "Example 5:" }, { "code": "# importing modulesimport numpy as npimport matplotlib.pyplot as plt # X-axis valuesx = [0, 1, 2, 3, 4, 5, 6, 7, 8] # Y-axis valuesy1 = [0, 3, 6, 9, 12, 15, 18, 21, 24]# Y-axis values y2 = [0, 1, 2, 3, 4, 5, 6, 7, 8] # Function to plot plt.plot(y1, label =\"y = x\")plt.plot(y2, label =\"y = 3x\") # Function add a legend plt.legend(bbox_to_anchor =(0.75, 1.15), ncol = 2) # function to show the plotplt.show()", "e": 35063, "s": 34644, "text": null }, { "code": null, "e": 35071, "s": 35063, "text": "Output:" }, { "code": null, "e": 35089, "s": 35071, "text": "Python-matplotlib" }, { "code": null, "e": 35096, "s": 35089, "text": "Python" }, { "code": null, "e": 35194, "s": 35096, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35222, "s": 35194, "text": "Read JSON file using Python" }, { "code": null, "e": 35272, "s": 35222, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 35294, "s": 35272, "text": "Python map() function" }, { "code": null, "e": 35338, "s": 35294, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 35356, "s": 35338, "text": "Python Dictionary" }, { "code": null, "e": 35391, "s": 35356, "text": "Read a file line by line in Python" }, { "code": null, "e": 35414, "s": 35391, "text": "Taking input in Python" }, { "code": null, "e": 35446, "s": 35414, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 35468, "s": 35446, "text": "Enumerate() in Python" } ]
Minimum steps to delete a string after repeated deletion of palindrome substrings - GeeksforGeeks
26 Apr, 2021 Given a string containing characters as integers only. We need to delete all characters of this string in a minimum number of steps wherein one step we can delete the substring which is a palindrome. After deleting a substring remaining parts are concatenated. Examples: Input : s = “2553432” Output : 2 We can delete all character of above string in 2 steps, first deleting the substring s[3, 5] “343” and then remaining string completely s[0, 3] “2552” Input : s = “1234” Output : 4 We can delete all character of above string in 4 steps only because each character need to be deleted separately. No substring of length 2 is a palindrome in above string. We can solve this problem using Dynamic programming. Let dp[i][j] denotes the number of steps it takes to delete the substring s[i, j]. Each character will be deleted alone or as part of some substring so in the first case we will delete the character itself and call subproblem (i+1, j). In the second case, we will iterate the overall occurrence of the current character on the right side, if K is the index of one such occurrence then the problem will reduce to two subproblems (i+1, K – 1) and (K+1, j). We can reach this subproblem (i+1, K-1) because we can just delete the same character and call for the mid substring. We need to take care of a case when the first two characters are the same in that case we can directly reduce to the subproblem (i+2, j).So after the above discussion of the relation among subproblems, we can write dp relation as follows, dp[i][j] = min(1 + dp[i+1][j], dp[i+1][K-1] + dp[K+1][j], where s[i] == s[K] 1 + dp[i+2][j] ) The total time complexity of the above solution is O(n^3) C++ Java Python 3 C# PHP Javascript // C++ program to find minimum step to delete a string#include <bits/stdc++.h>using namespace std; /* method returns minimum step for deleting the string, where in one step a palindrome is removed */int minStepToDeleteString(string str){ int N = str.length(); // declare dp array and initialize it with 0s int dp[N + 1][N + 1]; for (int i = 0; i <= N; i++) for (int j = 0; j <= N; j++) dp[i][j] = 0; // loop for substring length we are considering for (int len = 1; len <= N; len++) { // loop with two variables i and j, denoting // starting and ending of substrings for (int i = 0, j = len - 1; j < N; i++, j++) { // If substring length is 1, then 1 step // will be needed if (len == 1) dp[i][j] = 1; else { // delete the ith char individually // and assign result for subproblem (i+1,j) dp[i][j] = 1 + dp[i + 1][j]; // if current and next char are same, // choose min from current and subproblem // (i+2,j) if (str[i] == str[i + 1]) dp[i][j] = min(1 + dp[i + 2][j], dp[i][j]); /* loop over all right characters and suppose Kth char is same as ith character then choose minimum from current and two substring after ignoring ith and Kth char */ for (int K = i + 2; K <= j; K++) if (str[i] == str[K]) dp[i][j] = min(dp[i+1][K-1] + dp[K+1][j], dp[i][j]); } } } /* Uncomment below snippet to print actual dp tablex for (int i = 0; i < N; i++, cout << endl) for (int j = 0; j < N; j++) cout << dp[i][j] << " "; */ return dp[0][N - 1];} // Driver code to test above methodsint main(){ string str = "2553432"; cout << minStepToDeleteString(str) << endl; return 0;} // Java program to find minimum step to// delete a stringpublic class GFG{ /* method returns minimum step for deleting the string, where in one step a palindrome is removed */ static int minStepToDeleteString(String str) { int N = str.length(); // declare dp array and initialize it with 0s int[][] dp = new int[N + 1][N + 1]; for (int i = 0; i <= N; i++) for (int j = 0; j <= N; j++) dp[i][j] = 0; // loop for substring length we are considering for (int len = 1; len <= N; len++) { // loop with two variables i and j, denoting // starting and ending of substrings for (int i = 0, j = len - 1; j < N; i++, j++) { // If substring length is 1, then 1 step // will be needed if (len == 1) dp[i][j] = 1; else { // delete the ith char individually // and assign result for // subproblem (i+1,j) dp[i][j] = 1 + dp[i + 1][j]; // if current and next char are same, // choose min from current and // subproblem (i+2, j) if (str.charAt(i) == str.charAt(i + 1)) dp[i][j] = Math.min(1 + dp[i + 2][j], dp[i][j]); /* loop over all right characters and suppose Kth char is same as ith character then choose minimum from current and two substring after ignoring ith and Kth char */ for (int K = i + 2; K <= j; K++) if (str.charAt(i) == str.charAt(K)) dp[i][j] = Math.min( dp[i + 1][K - 1] + dp[K + 1][j], dp[i][j]); } } } /* Uncomment below snippet to print actual dp tablex for (int i = 0; i < N; i++){ System.out.println(); for (int j = 0; j < N; j++) System.out.print(dp[i][j] + " "); } */ return dp[0][N - 1]; } // Driver code to test above methods public static void main(String args[]) { String str = "2553432"; System.out.println(minStepToDeleteString(str)); }}// This code is contributed by Sumit Ghosh # Python 3 program to find minimum# step to delete a string # method returns minimum step for# deleting the string, where in one# step a palindrome is removeddef minStepToDeleteString(str): N = len(str) # declare dp array and initialize # it with 0s dp = [[0 for x in range(N + 1)] for y in range(N + 1)] # loop for substring length # we are considering for l in range(1, N + 1): # loop with two variables i and j, denoting # starting and ending of substrings i = 0 j = l - 1 while j < N: # If substring length is 1, # then 1 step will be needed if (l == 1): dp[i][j] = 1 else: # delete the ith char individually # and assign result for subproblem (i+1,j) dp[i][j] = 1 + dp[i + 1][j] # if current and next char are # same, choose min from current # and subproblem (i+2,j) if (str[i] == str[i + 1]): dp[i][j] = min(1 + dp[i + 2][j], dp[i][j]) ''' loop over all right characters and suppose Kth char is same as ith character then choose minimum from current and two substring after ignoring ith and Kth char ''' for K in range(i + 2, j + 1): if (str[i] == str[K]): dp[i][j] = min(dp[i + 1][K - 1] + dp[K + 1][j], dp[i][j]) i += 1 j += 1 # Uncomment below snippet to print # actual dp tablex # for (int i = 0; i < N; i++, cout << endl) # for (int j = 0; j < N; j++) # cout << dp[i][j] << " "; return dp[0][N - 1] # Driver Codeif __name__ == "__main__": str = "2553432" print( minStepToDeleteString(str)) # This code is contributed by ChitraNayal // C# program to find minimum step to// delete a stringusing System; class GFG { /* method returns minimum step for deleting the string, where in one step a palindrome is removed */ static int minStepToDeleteString(string str) { int N = str.Length; // declare dp array and initialize it // with 0s int [,]dp = new int[N + 1,N + 1]; for (int i = 0; i <= N; i++) for (int j = 0; j <= N; j++) dp[i,j] = 0; // loop for substring length we are // considering for (int len = 1; len <= N; len++) { // loop with two variables i and j, // denoting starting and ending of // substrings for (int i = 0, j = len - 1; j < N; i++, j++) { // If substring length is 1, then 1 // step will be needed if (len == 1) dp[i,j] = 1; else { // delete the ith char individually // and assign result for // subproblem (i+1,j) dp[i,j] = 1 + dp[i + 1,j]; // if current and next char are same, // choose min from current and // subproblem (i+2, j) if (str[i] == str[i + 1]) dp[i,j] = Math.Min(1 + dp[i + 2,j], dp[i,j]); /* loop over all right characters and suppose Kth char is same as ith character then choose minimum from current and two substring after ignoring ith and Kth char */ for (int K = i + 2; K <= j; K++) if (str[i] == str[K]) dp[i,j] = Math.Min( dp[i + 1,K - 1] + dp[K + 1,j], dp[i,j]); } } } /* Uncomment below snippet to print actual dp tablex for (int i = 0; i < N; i++){ System.out.println(); for (int j = 0; j < N; j++) System.out.print(dp[i][j] + " "); } */ return dp[0,N - 1]; } // Driver code to test above methods public static void Main() { string str = "2553432"; Console.Write(minStepToDeleteString(str)); }} // This code is contributed by nitin mittal <?php// PHP program to find minimum step// to delete a string // method returns minimum step for// deleting the string, where in one// step a palindrome is removed */function minStepToDeleteString($str){ $N = strlen($str); // declare dp array and initialize // it with 0s $dp[$N + 1][$N + 1] = array(array()); for ($i = 0; $i <= $N; $i++) for ($j = 0; $j <= $N; $j++) $dp[$i][$j] = 0; // loop for substring length we // are considering for ($len = 1; $len <= $N; $len++) { // loop with two variables i and j, denoting // starting and ending of substrings for ($i = 0, $j = $len - 1; $j < $N; $i++, $j++) { // If substring length is 1, then // 1 step will be needed if ($len == 1) $dp[$i][$j] = 1; else { // delete the ith char individually // and assign result for subproblem (i+1,j) $dp[$i][$j] = 1 + $dp[$i + 1][$j]; // if current and next char are same, // choose min from current and subproblem // (i+2,j) if ($str[$i] == $str[$i + 1]) $dp[$i][$j] = min(1 + $dp[$i + 2][$j], $dp[$i][$j]); /* loop over all right characters and suppose Kth char is same as ith character then choose minimum from current and two substring after ignoring ith and Kth char */ for ($K = $i + 2; $K <= $j; $K++) if ($str[$i] == $str[$K]) $dp[$i][$j] = min($dp[$i + 1][$K - 1] + $dp[$K + 1][$j], $dp[$i][$j]); } } } /* Uncomment below snippet to print actual dp tablex for (int i = 0; i < N; i++, cout << endl) for (int j = 0; j < N; j++) cout << dp[i][j] << " "; */ return $dp[0][$N - 1];} // Driver code$str = "2553432";echo minStepToDeleteString($str), "\n"; // This code is contributed by ajit.?> <script>// Java Script program to find minimum step to// delete a string /* method returns minimum step for deleting the string, where in one step a palindrome is removed */ function minStepToDeleteString(str) { let N = str.length; // declare dp array and initialize it with 0s let dp = new Array(N + 1); for (let i = 0; i <= N; i++) { dp[i]=new Array(N+1); for (let j = 0; j <= N; j++) dp[i][j] = 0; } // loop for substring length we are considering for (let len = 1; len <= N; len++) { // loop with two variables i and j, denoting // starting and ending of substrings for (let i = 0, j = len - 1; j < N; i++, j++) { // If substring length is 1, then 1 step // will be needed if (len == 1) dp[i][j] = 1; else { // delete the ith char individually // and assign result for // subproblem (i+1,j) dp[i][j] = 1 + dp[i + 1][j]; // if current and next char are same, // choose min from current and // subproblem (i+2, j) if (str[i] == str[i+1]) dp[i][j] = Math.min(1 + dp[i + 2][j], dp[i][j]); /* loop over all right characters and suppose Kth char is same as ith character then choose minimum from current and two substring after ignoring ith and Kth char */ for (let K = i + 2; K <= j; K++) if (str[i] == str[K]) dp[i][j] = Math.min( dp[i + 1][K - 1] + dp[K + 1][j], dp[i][j]); } } } /* Uncomment below snippet to print actual dp tablex for (int i = 0; i < N; i++){ System.out.println(); for (int j = 0; j < N; j++) System.out.print(dp[i][j] + " "); } */ return dp[0][N - 1]; } // Driver code to test above methods let str = "2553432"; document.write(minStepToDeleteString(str)); // This code is contributed by avanitrachhadiya2155</script> Output: 2 nitin mittal ukasp jit_t avanitrachhadiya2155 palindrome Dynamic Programming Strings Strings Dynamic Programming palindrome Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Bellman–Ford Algorithm | DP-23 Floyd Warshall Algorithm | DP-16 Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Edit Distance | DP-5 Sieve of Eratosthenes 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 Check for Balanced Brackets in an expression (well-formedness) using Stack
[ { "code": null, "e": 26611, "s": 26583, "text": "\n26 Apr, 2021" }, { "code": null, "e": 26874, "s": 26611, "text": "Given a string containing characters as integers only. We need to delete all characters of this string in a minimum number of steps wherein one step we can delete the substring which is a palindrome. After deleting a substring remaining parts are concatenated. " }, { "code": null, "e": 26884, "s": 26874, "text": "Examples:" }, { "code": null, "e": 27277, "s": 26884, "text": "Input : s = “2553432”\nOutput : 2\nWe can delete all character of above string in\n2 steps, first deleting the substring s[3, 5] “343” \nand then remaining string completely s[0, 3] “2552”\n\nInput : s = “1234”\nOutput : 4\nWe can delete all character of above string in 4 \nsteps only because each character need to be deleted \nseparately. No substring of length 2 is a palindrome \nin above string." }, { "code": null, "e": 28143, "s": 27277, "text": "We can solve this problem using Dynamic programming. Let dp[i][j] denotes the number of steps it takes to delete the substring s[i, j]. Each character will be deleted alone or as part of some substring so in the first case we will delete the character itself and call subproblem (i+1, j). In the second case, we will iterate the overall occurrence of the current character on the right side, if K is the index of one such occurrence then the problem will reduce to two subproblems (i+1, K – 1) and (K+1, j). We can reach this subproblem (i+1, K-1) because we can just delete the same character and call for the mid substring. We need to take care of a case when the first two characters are the same in that case we can directly reduce to the subproblem (i+2, j).So after the above discussion of the relation among subproblems, we can write dp relation as follows, " }, { "code": null, "e": 28258, "s": 28143, "text": "dp[i][j] = min(1 + dp[i+1][j],\n dp[i+1][K-1] + dp[K+1][j], where s[i] == s[K]\n 1 + dp[i+2][j] )" }, { "code": null, "e": 28318, "s": 28258, "text": "The total time complexity of the above solution is O(n^3) " }, { "code": null, "e": 28322, "s": 28318, "text": "C++" }, { "code": null, "e": 28327, "s": 28322, "text": "Java" }, { "code": null, "e": 28336, "s": 28327, "text": "Python 3" }, { "code": null, "e": 28339, "s": 28336, "text": "C#" }, { "code": null, "e": 28343, "s": 28339, "text": "PHP" }, { "code": null, "e": 28354, "s": 28343, "text": "Javascript" }, { "code": "// C++ program to find minimum step to delete a string#include <bits/stdc++.h>using namespace std; /* method returns minimum step for deleting the string, where in one step a palindrome is removed */int minStepToDeleteString(string str){ int N = str.length(); // declare dp array and initialize it with 0s int dp[N + 1][N + 1]; for (int i = 0; i <= N; i++) for (int j = 0; j <= N; j++) dp[i][j] = 0; // loop for substring length we are considering for (int len = 1; len <= N; len++) { // loop with two variables i and j, denoting // starting and ending of substrings for (int i = 0, j = len - 1; j < N; i++, j++) { // If substring length is 1, then 1 step // will be needed if (len == 1) dp[i][j] = 1; else { // delete the ith char individually // and assign result for subproblem (i+1,j) dp[i][j] = 1 + dp[i + 1][j]; // if current and next char are same, // choose min from current and subproblem // (i+2,j) if (str[i] == str[i + 1]) dp[i][j] = min(1 + dp[i + 2][j], dp[i][j]); /* loop over all right characters and suppose Kth char is same as ith character then choose minimum from current and two substring after ignoring ith and Kth char */ for (int K = i + 2; K <= j; K++) if (str[i] == str[K]) dp[i][j] = min(dp[i+1][K-1] + dp[K+1][j], dp[i][j]); } } } /* Uncomment below snippet to print actual dp tablex for (int i = 0; i < N; i++, cout << endl) for (int j = 0; j < N; j++) cout << dp[i][j] << \" \"; */ return dp[0][N - 1];} // Driver code to test above methodsint main(){ string str = \"2553432\"; cout << minStepToDeleteString(str) << endl; return 0;}", "e": 30429, "s": 28354, "text": null }, { "code": "// Java program to find minimum step to// delete a stringpublic class GFG{ /* method returns minimum step for deleting the string, where in one step a palindrome is removed */ static int minStepToDeleteString(String str) { int N = str.length(); // declare dp array and initialize it with 0s int[][] dp = new int[N + 1][N + 1]; for (int i = 0; i <= N; i++) for (int j = 0; j <= N; j++) dp[i][j] = 0; // loop for substring length we are considering for (int len = 1; len <= N; len++) { // loop with two variables i and j, denoting // starting and ending of substrings for (int i = 0, j = len - 1; j < N; i++, j++) { // If substring length is 1, then 1 step // will be needed if (len == 1) dp[i][j] = 1; else { // delete the ith char individually // and assign result for // subproblem (i+1,j) dp[i][j] = 1 + dp[i + 1][j]; // if current and next char are same, // choose min from current and // subproblem (i+2, j) if (str.charAt(i) == str.charAt(i + 1)) dp[i][j] = Math.min(1 + dp[i + 2][j], dp[i][j]); /* loop over all right characters and suppose Kth char is same as ith character then choose minimum from current and two substring after ignoring ith and Kth char */ for (int K = i + 2; K <= j; K++) if (str.charAt(i) == str.charAt(K)) dp[i][j] = Math.min( dp[i + 1][K - 1] + dp[K + 1][j], dp[i][j]); } } } /* Uncomment below snippet to print actual dp tablex for (int i = 0; i < N; i++){ System.out.println(); for (int j = 0; j < N; j++) System.out.print(dp[i][j] + \" \"); } */ return dp[0][N - 1]; } // Driver code to test above methods public static void main(String args[]) { String str = \"2553432\"; System.out.println(minStepToDeleteString(str)); }}// This code is contributed by Sumit Ghosh", "e": 33048, "s": 30429, "text": null }, { "code": "# Python 3 program to find minimum# step to delete a string # method returns minimum step for# deleting the string, where in one# step a palindrome is removeddef minStepToDeleteString(str): N = len(str) # declare dp array and initialize # it with 0s dp = [[0 for x in range(N + 1)] for y in range(N + 1)] # loop for substring length # we are considering for l in range(1, N + 1): # loop with two variables i and j, denoting # starting and ending of substrings i = 0 j = l - 1 while j < N: # If substring length is 1, # then 1 step will be needed if (l == 1): dp[i][j] = 1 else: # delete the ith char individually # and assign result for subproblem (i+1,j) dp[i][j] = 1 + dp[i + 1][j] # if current and next char are # same, choose min from current # and subproblem (i+2,j) if (str[i] == str[i + 1]): dp[i][j] = min(1 + dp[i + 2][j], dp[i][j]) ''' loop over all right characters and suppose Kth char is same as ith character then choose minimum from current and two substring after ignoring ith and Kth char ''' for K in range(i + 2, j + 1): if (str[i] == str[K]): dp[i][j] = min(dp[i + 1][K - 1] + dp[K + 1][j], dp[i][j]) i += 1 j += 1 # Uncomment below snippet to print # actual dp tablex # for (int i = 0; i < N; i++, cout << endl) # for (int j = 0; j < N; j++) # cout << dp[i][j] << \" \"; return dp[0][N - 1] # Driver Codeif __name__ == \"__main__\": str = \"2553432\" print( minStepToDeleteString(str)) # This code is contributed by ChitraNayal", "e": 35022, "s": 33048, "text": null }, { "code": "// C# program to find minimum step to// delete a stringusing System; class GFG { /* method returns minimum step for deleting the string, where in one step a palindrome is removed */ static int minStepToDeleteString(string str) { int N = str.Length; // declare dp array and initialize it // with 0s int [,]dp = new int[N + 1,N + 1]; for (int i = 0; i <= N; i++) for (int j = 0; j <= N; j++) dp[i,j] = 0; // loop for substring length we are // considering for (int len = 1; len <= N; len++) { // loop with two variables i and j, // denoting starting and ending of // substrings for (int i = 0, j = len - 1; j < N; i++, j++) { // If substring length is 1, then 1 // step will be needed if (len == 1) dp[i,j] = 1; else { // delete the ith char individually // and assign result for // subproblem (i+1,j) dp[i,j] = 1 + dp[i + 1,j]; // if current and next char are same, // choose min from current and // subproblem (i+2, j) if (str[i] == str[i + 1]) dp[i,j] = Math.Min(1 + dp[i + 2,j], dp[i,j]); /* loop over all right characters and suppose Kth char is same as ith character then choose minimum from current and two substring after ignoring ith and Kth char */ for (int K = i + 2; K <= j; K++) if (str[i] == str[K]) dp[i,j] = Math.Min( dp[i + 1,K - 1] + dp[K + 1,j], dp[i,j]); } } } /* Uncomment below snippet to print actual dp tablex for (int i = 0; i < N; i++){ System.out.println(); for (int j = 0; j < N; j++) System.out.print(dp[i][j] + \" \"); } */ return dp[0,N - 1]; } // Driver code to test above methods public static void Main() { string str = \"2553432\"; Console.Write(minStepToDeleteString(str)); }} // This code is contributed by nitin mittal", "e": 37596, "s": 35022, "text": null }, { "code": "<?php// PHP program to find minimum step// to delete a string // method returns minimum step for// deleting the string, where in one// step a palindrome is removed */function minStepToDeleteString($str){ $N = strlen($str); // declare dp array and initialize // it with 0s $dp[$N + 1][$N + 1] = array(array()); for ($i = 0; $i <= $N; $i++) for ($j = 0; $j <= $N; $j++) $dp[$i][$j] = 0; // loop for substring length we // are considering for ($len = 1; $len <= $N; $len++) { // loop with two variables i and j, denoting // starting and ending of substrings for ($i = 0, $j = $len - 1; $j < $N; $i++, $j++) { // If substring length is 1, then // 1 step will be needed if ($len == 1) $dp[$i][$j] = 1; else { // delete the ith char individually // and assign result for subproblem (i+1,j) $dp[$i][$j] = 1 + $dp[$i + 1][$j]; // if current and next char are same, // choose min from current and subproblem // (i+2,j) if ($str[$i] == $str[$i + 1]) $dp[$i][$j] = min(1 + $dp[$i + 2][$j], $dp[$i][$j]); /* loop over all right characters and suppose Kth char is same as ith character then choose minimum from current and two substring after ignoring ith and Kth char */ for ($K = $i + 2; $K <= $j; $K++) if ($str[$i] == $str[$K]) $dp[$i][$j] = min($dp[$i + 1][$K - 1] + $dp[$K + 1][$j], $dp[$i][$j]); } } } /* Uncomment below snippet to print actual dp tablex for (int i = 0; i < N; i++, cout << endl) for (int j = 0; j < N; j++) cout << dp[i][j] << \" \"; */ return $dp[0][$N - 1];} // Driver code$str = \"2553432\";echo minStepToDeleteString($str), \"\\n\"; // This code is contributed by ajit.?>", "e": 39770, "s": 37596, "text": null }, { "code": "<script>// Java Script program to find minimum step to// delete a string /* method returns minimum step for deleting the string, where in one step a palindrome is removed */ function minStepToDeleteString(str) { let N = str.length; // declare dp array and initialize it with 0s let dp = new Array(N + 1); for (let i = 0; i <= N; i++) { dp[i]=new Array(N+1); for (let j = 0; j <= N; j++) dp[i][j] = 0; } // loop for substring length we are considering for (let len = 1; len <= N; len++) { // loop with two variables i and j, denoting // starting and ending of substrings for (let i = 0, j = len - 1; j < N; i++, j++) { // If substring length is 1, then 1 step // will be needed if (len == 1) dp[i][j] = 1; else { // delete the ith char individually // and assign result for // subproblem (i+1,j) dp[i][j] = 1 + dp[i + 1][j]; // if current and next char are same, // choose min from current and // subproblem (i+2, j) if (str[i] == str[i+1]) dp[i][j] = Math.min(1 + dp[i + 2][j], dp[i][j]); /* loop over all right characters and suppose Kth char is same as ith character then choose minimum from current and two substring after ignoring ith and Kth char */ for (let K = i + 2; K <= j; K++) if (str[i] == str[K]) dp[i][j] = Math.min( dp[i + 1][K - 1] + dp[K + 1][j], dp[i][j]); } } } /* Uncomment below snippet to print actual dp tablex for (int i = 0; i < N; i++){ System.out.println(); for (int j = 0; j < N; j++) System.out.print(dp[i][j] + \" \"); } */ return dp[0][N - 1]; } // Driver code to test above methods let str = \"2553432\"; document.write(minStepToDeleteString(str)); // This code is contributed by avanitrachhadiya2155</script>", "e": 42350, "s": 39770, "text": null }, { "code": null, "e": 42359, "s": 42350, "text": "Output: " }, { "code": null, "e": 42361, "s": 42359, "text": "2" }, { "code": null, "e": 42374, "s": 42361, "text": "nitin mittal" }, { "code": null, "e": 42380, "s": 42374, "text": "ukasp" }, { "code": null, "e": 42386, "s": 42380, "text": "jit_t" }, { "code": null, "e": 42407, "s": 42386, "text": "avanitrachhadiya2155" }, { "code": null, "e": 42418, "s": 42407, "text": "palindrome" }, { "code": null, "e": 42438, "s": 42418, "text": "Dynamic Programming" }, { "code": null, "e": 42446, "s": 42438, "text": "Strings" }, { "code": null, "e": 42454, "s": 42446, "text": "Strings" }, { "code": null, "e": 42474, "s": 42454, "text": "Dynamic Programming" }, { "code": null, "e": 42485, "s": 42474, "text": "palindrome" }, { "code": null, "e": 42583, "s": 42485, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 42614, "s": 42583, "text": "Bellman–Ford Algorithm | DP-23" }, { "code": null, "e": 42647, "s": 42614, "text": "Floyd Warshall Algorithm | DP-16" }, { "code": null, "e": 42715, "s": 42647, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" }, { "code": null, "e": 42736, "s": 42715, "text": "Edit Distance | DP-5" }, { "code": null, "e": 42758, "s": 42736, "text": "Sieve of Eratosthenes" }, { "code": null, "e": 42804, "s": 42758, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 42829, "s": 42804, "text": "Reverse a string in Java" }, { "code": null, "e": 42889, "s": 42829, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 42904, "s": 42889, "text": "C++ Data Types" } ]
Apache Hive - Getting Started With HQL Database Creation And Drop Database - GeeksforGeeks
21 Sep, 2021 Pre-requisite: Hive 3.1.2 Installation, Hadoop 3.1.2 Installation HiveQL or HQL is a Hive query language that we used to process or query structured data on Hive. HQL syntaxes are very much similar to MySQL but have some significant differences. We will use the hive command, which is a bash shell script to complete our hive demo using CLI(Command Line Interface). We can easily start hive shell by simply typing hive in the terminal. Make sure that the /bin directory of your hive installation is mentioned in the .basrc file. The .bashrc file executes automatically when the user logs into the system and all necessary commands mentioned in this script file will run. We can simply check whether the /bin directory is available or not by simply opening it with the command as shown below. sudo gedit ~/.bashrc In case if the path is not added then add it so that we can directly run the hive shell from the terminal without moving to the hive directory. Otherwise, we can start hive manually by moving to apache-hive-3.1.2/bin/ directory and by pressing the hive command. Before performing hive make sure that all of your Hadoop daemons are started and working. We can simply start all the Hadoop daemon with the below command. start-dfs.sh # this will start namenode, datanode and secondary namenode start-yarn.sh # this will start node manager and resource manager jps # To check running daemons The Database is a storage schema that contains multiple tables. The Hive Databases refer to the namespace of tables. If you don’t specify the database name by default Hive uses its default database for table creation and other purposes. Creating a Database allows multiple users to create tables with a similar name in different schemas so that their names don’t match. So, let’s start our hive shell for performing our tasks with the below command. hive See the already existing databases using the below command. show databases; # this will show the existing databases Create Database Syntax: We can create a database with the help of the below command but if the database already exists then, in that case, Hive will throw an error. CREATE DATABASE|SCHEMA <database name> # we can use DATABASE or SCHEMA for creation of DB Example: CREATE DATABASE Test; # create database with name Test show databases; # this will show the existing databases If we again try to create a Test database hive will throw an error/warning that the database with the name Test already exists. In general, we don’t want to get an error if the database exists. So we use the create database command with [IF NOT EXIST] clause. This will do not throw any error. CREATE DATABASE|SCHEMA [IF NOT EXISTS] <database name> Example: CREATE SCHEMA IF NOT EXISTS Test1; SHOW DATABASES; Syntax To Drop Existing Databases: DROP DATABASE <db_name>; or DROP DATABASE IF EXIST <db_name> # The IF EXIST clause again is used to suppress error Example: DROP DATABASE IF EXISTS Test; DROP DATABASE Test1; Now quit hive shell with quit command. quit; sweetyty Apache-Hive Hadoop Hadoop Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Hadoop MapReduce - Data Flow Hadoop - Pros and Cons Hive - Alter Table Hadoop - Schedulers and Types of Schedulers Import and Export Data using SQOOP How to Create Table in Hive? MapReduce - Combiners Top 10 Hadoop Analytics Tools For Big Data How MapReduce completes a task? MapReduce - Understanding With Real-Life Example
[ { "code": null, "e": 25591, "s": 25563, "text": "\n21 Sep, 2021" }, { "code": null, "e": 25657, "s": 25591, "text": "Pre-requisite: Hive 3.1.2 Installation, Hadoop 3.1.2 Installation" }, { "code": null, "e": 26384, "s": 25657, "text": "HiveQL or HQL is a Hive query language that we used to process or query structured data on Hive. HQL syntaxes are very much similar to MySQL but have some significant differences. We will use the hive command, which is a bash shell script to complete our hive demo using CLI(Command Line Interface). We can easily start hive shell by simply typing hive in the terminal. Make sure that the /bin directory of your hive installation is mentioned in the .basrc file. The .bashrc file executes automatically when the user logs into the system and all necessary commands mentioned in this script file will run. We can simply check whether the /bin directory is available or not by simply opening it with the command as shown below. " }, { "code": null, "e": 26407, "s": 26384, "text": "sudo gedit ~/.bashrc " }, { "code": null, "e": 26669, "s": 26407, "text": "In case if the path is not added then add it so that we can directly run the hive shell from the terminal without moving to the hive directory. Otherwise, we can start hive manually by moving to apache-hive-3.1.2/bin/ directory and by pressing the hive command." }, { "code": null, "e": 26826, "s": 26669, "text": "Before performing hive make sure that all of your Hadoop daemons are started and working. We can simply start all the Hadoop daemon with the below command. " }, { "code": null, "e": 27065, "s": 26826, "text": "start-dfs.sh # this will start namenode, datanode and secondary namenode\n\nstart-yarn.sh # this will start node manager and resource manager \n\njps # To check running daemons" }, { "code": null, "e": 27435, "s": 27065, "text": "The Database is a storage schema that contains multiple tables. The Hive Databases refer to the namespace of tables. If you don’t specify the database name by default Hive uses its default database for table creation and other purposes. Creating a Database allows multiple users to create tables with a similar name in different schemas so that their names don’t match." }, { "code": null, "e": 27515, "s": 27435, "text": "So, let’s start our hive shell for performing our tasks with the below command." }, { "code": null, "e": 27520, "s": 27515, "text": "hive" }, { "code": null, "e": 27580, "s": 27520, "text": "See the already existing databases using the below command." }, { "code": null, "e": 27655, "s": 27580, "text": "show databases; # this will show the existing databases " }, { "code": null, "e": 27679, "s": 27655, "text": "Create Database Syntax:" }, { "code": null, "e": 27820, "s": 27679, "text": "We can create a database with the help of the below command but if the database already exists then, in that case, Hive will throw an error." }, { "code": null, "e": 27913, "s": 27820, "text": "CREATE DATABASE|SCHEMA <database name> # we can use DATABASE or SCHEMA for creation of DB" }, { "code": null, "e": 27922, "s": 27913, "text": "Example:" }, { "code": null, "e": 28063, "s": 27922, "text": "CREATE DATABASE Test; # create database with name Test\n\nshow databases; # this will show the existing databases " }, { "code": null, "e": 28357, "s": 28063, "text": "If we again try to create a Test database hive will throw an error/warning that the database with the name Test already exists. In general, we don’t want to get an error if the database exists. So we use the create database command with [IF NOT EXIST] clause. This will do not throw any error." }, { "code": null, "e": 28412, "s": 28357, "text": "CREATE DATABASE|SCHEMA [IF NOT EXISTS] <database name>" }, { "code": null, "e": 28421, "s": 28412, "text": "Example:" }, { "code": null, "e": 28473, "s": 28421, "text": "CREATE SCHEMA IF NOT EXISTS Test1;\n\nSHOW DATABASES;" }, { "code": null, "e": 28508, "s": 28473, "text": "Syntax To Drop Existing Databases:" }, { "code": null, "e": 28626, "s": 28508, "text": "DROP DATABASE <db_name>; or DROP DATABASE IF EXIST <db_name> # The IF EXIST clause again is used to suppress error" }, { "code": null, "e": 28635, "s": 28626, "text": "Example:" }, { "code": null, "e": 28689, "s": 28635, "text": "DROP DATABASE IF EXISTS Test;\n\nDROP DATABASE Test1; " }, { "code": null, "e": 28728, "s": 28689, "text": "Now quit hive shell with quit command." }, { "code": null, "e": 28734, "s": 28728, "text": "quit;" }, { "code": null, "e": 28743, "s": 28734, "text": "sweetyty" }, { "code": null, "e": 28755, "s": 28743, "text": "Apache-Hive" }, { "code": null, "e": 28762, "s": 28755, "text": "Hadoop" }, { "code": null, "e": 28769, "s": 28762, "text": "Hadoop" }, { "code": null, "e": 28867, "s": 28769, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28896, "s": 28867, "text": "Hadoop MapReduce - Data Flow" }, { "code": null, "e": 28919, "s": 28896, "text": "Hadoop - Pros and Cons" }, { "code": null, "e": 28938, "s": 28919, "text": "Hive - Alter Table" }, { "code": null, "e": 28982, "s": 28938, "text": "Hadoop - Schedulers and Types of Schedulers" }, { "code": null, "e": 29017, "s": 28982, "text": "Import and Export Data using SQOOP" }, { "code": null, "e": 29046, "s": 29017, "text": "How to Create Table in Hive?" }, { "code": null, "e": 29068, "s": 29046, "text": "MapReduce - Combiners" }, { "code": null, "e": 29111, "s": 29068, "text": "Top 10 Hadoop Analytics Tools For Big Data" }, { "code": null, "e": 29143, "s": 29111, "text": "How MapReduce completes a task?" } ]
Count number of ways to reach destination in a Maze using BFS - GeeksforGeeks
14 Aug, 2021 Given a maze with obstacles, count number of paths to reach rightmost-bottom most cell from the topmost-leftmost cell. A cell in the given maze has value -1 if it is a blockage or dead-end, else 0. From a given cell, we are allowed to move to cells (i+1, j) and (i, j+1) only. Examples: Input: mat[][] = { {1, 0, 0, 1}, {1, 1, 1, 1}, {1, 0, 1, 1}} Output: 2 Input: mat[][] = { {1, 1, 1, 1}, {1, 0, 1, 1}, {0, 1, 1, 1}, {1, 1, 1, 1}} Output: 4 Approach: The idea is to use a queue and apply bfs and use a variable count to store the number of possible paths. Make a pair of row and column and insert (0, 0) into the queue. Now keep popping pairs from queue, if the popped value is the end of matrix then increment count, otherwise check if the next column can give a valid move or the next row can give a valid move and according to that, insert the corresponding row, column pair into the queue. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; #define m 4#define n 3 // Function to return the number of valid// paths in the given mazeint Maze(int matrix[n][m]){ queue<pair<int, int> > q; // Insert the starting point i.e. // (0, 0) in the queue q.push(make_pair(0, 0)); // To store the count of possible paths int count = 0; while (!q.empty()) { pair<int, int> p = q.front(); q.pop(); // Increment the count of paths since // it is the destination if (p.first == n - 1 && p.second == m - 1) count++; // If moving to the next row is a valid move if (p.first + 1 < n && matrix[p.first + 1][p.second] == 1) { q.push(make_pair(p.first + 1, p.second)); } // If moving to the next column is a valid move if (p.second + 1 < m && matrix[p.first][p.second + 1] == 1) { q.push(make_pair(p.first, p.second + 1)); } } return count;} // Driver codeint main(){ // Matrix to represent maze int matrix[n][m] = { { 1, 0, 0, 1 }, { 1, 1, 1, 1 }, { 1, 0, 1, 1 } }; cout << Maze(matrix); return 0;} // Java implementation of the approachimport java.util.*;class GFG{static int m = 4;static int n = 3;static class pair{ int first, second; public pair(int first, int second) { this.first = first; this.second = second; }} // Function to return the number of valid// paths in the given mazestatic int Maze(int matrix[][]){ Queue<pair> q = new LinkedList<>(); // Insert the starting point i.e. // (0, 0) in the queue q.add(new pair(0, 0)); // To store the count of possible paths int count = 0; while (!q.isEmpty()) { pair p = q.peek(); q.remove(); // Increment the count of paths since // it is the destination if (p.first == n - 1 && p.second == m - 1) count++; // If moving to the next row is a valid move if (p.first + 1 < n && matrix[p.first + 1][p.second] == 1) { q.add(new pair(p.first + 1, p.second)); } // If moving to the next column is a valid move if (p.second + 1 < m && matrix[p.first][p.second + 1] == 1) { q.add(new pair(p.first, p.second + 1)); } } return count;} // Driver codepublic static void main(String[] args){ // Matrix to represent maze int matrix[][] = {{ 1, 0, 0, 1 }, { 1, 1, 1, 1 }, { 1, 0, 1, 1 }}; System.out.println(Maze(matrix));}} // This code is contributed by Princi Singh # Python3 implementation of the approachfrom collections import dequem = 4n = 3 # Function to return the number of valid# paths in the given mazedef Maze(matrix): q = deque() # Insert the starting poi.e. # (0, 0) in the queue q.append((0, 0)) # To store the count of possible paths count = 0 while (len(q) > 0): p = q.popleft() # Increment the count of paths since # it is the destination if (p[0] == n - 1 and p[1] == m - 1): count += 1 # If moving to the next row is a valid move if (p[0] + 1 < n and matrix[p[0] + 1][p[1]] == 1): q.append((p[0] + 1, p[1])) # If moving to the next column is a valid move if (p[1] + 1 < m and matrix[p[0]][p[1] + 1] == 1): q.append((p[0], p[1] + 1)) return count # Driver code # Matrix to represent mazematrix = [ [ 1, 0, 0, 1 ], [ 1, 1, 1, 1 ], [ 1, 0, 1, 1 ] ] print(Maze(matrix)) # This code is contributed by Mohit Kumar // C# implementation of the approachusing System;using System.Collections.Generic; class GFG{static int m = 4;static int n = 3;class pair{ public int first, second; public pair(int first, int second) { this.first = first; this.second = second; }} // Function to return the number of valid// paths in the given mazestatic int Maze(int [,]matrix){ Queue<pair> q = new Queue<pair>(); // Insert the starting point i.e. // (0, 0) in the queue q.Enqueue(new pair(0, 0)); // To store the count of possible paths int count = 0; while (q.Count != 0) { pair p = q.Peek(); q.Dequeue(); // Increment the count of paths since // it is the destination if (p.first == n - 1 && p.second == m - 1) count++; // If moving to the next row is a valid move if (p.first + 1 < n && matrix[p.first + 1, p.second] == 1) { q.Enqueue(new pair(p.first + 1, p.second)); } // If moving to the next column is a valid move if (p.second + 1 < m && matrix[p.first, p.second + 1] == 1) { q.Enqueue(new pair(p.first, p.second + 1)); } } return count;} // Driver codepublic static void Main(String[] args){ // Matrix to represent maze int [,]matrix = {{ 1, 0, 0, 1 }, { 1, 1, 1, 1 }, { 1, 0, 1, 1 }}; Console.WriteLine(Maze(matrix));}} // This code is contributed by PrinciRaj1992 <script> // Javascript implementation of the approachvar m = 4;var n = 3; // Function to return the number of valid// paths in the given mazefunction Maze(matrix){ var q = []; // Insert the starting point i.e. // (0, 0) in the queue q.push([0, 0]); // To store the count of possible paths var count = 0; while (q.length != 0) { var p = q[0]; q.shift(); // Increment the count of paths since // it is the destination if (p[0] == n - 1 && p[1] == m - 1) count++; // If moving to the next row is a valid move if (p[0] + 1 < n && matrix[p[0] + 1][p[1]] == 1) { q.push([p[0] + 1, p[1]]); } // If moving to the next column is a valid move if (p[1] + 1 < m && matrix[p[0]][p[1] + 1] == 1) { q.push([p[0], p[1] + 1]); } } return count;} // Driver code // Matrix to represent mazevar matrix = [ [ 1, 0, 0, 1 ], [ 1, 1, 1, 1 ], [ 1, 0, 1, 1 ] ]; document.write( Maze(matrix)); // This code is contributed by rutvik_56 </script> 2 Time Complexity: O(N * M). Auxiliary Space: O(N * M). mohit kumar 29 princi singh princiraj1992 rutvik_56 pankajsharmagfg BFS Data Structures Matrix Queue Data Structures Matrix Queue BFS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Start Learning DSA? Introduction to Tree Data Structure Program to implement Singly Linked List in C++ using class Hash Functions and list/types of Hash functions Insertion in a B+ tree Matrix Chain Multiplication | DP-8 Program to find largest element in an array Print a given matrix in spiral form Rat in a Maze | Backtracking-2 Sudoku | Backtracking-7
[ { "code": null, "e": 26297, "s": 26269, "text": "\n14 Aug, 2021" }, { "code": null, "e": 26574, "s": 26297, "text": "Given a maze with obstacles, count number of paths to reach rightmost-bottom most cell from the topmost-leftmost cell. A cell in the given maze has value -1 if it is a blockage or dead-end, else 0. From a given cell, we are allowed to move to cells (i+1, j) and (i, j+1) only." }, { "code": null, "e": 26585, "s": 26574, "text": "Examples: " }, { "code": null, "e": 26656, "s": 26585, "text": "Input: mat[][] = { {1, 0, 0, 1}, {1, 1, 1, 1}, {1, 0, 1, 1}} Output: 2" }, { "code": null, "e": 26743, "s": 26656, "text": "Input: mat[][] = { {1, 1, 1, 1}, {1, 0, 1, 1}, {0, 1, 1, 1}, {1, 1, 1, 1}} Output: 4 " }, { "code": null, "e": 27196, "s": 26743, "text": "Approach: The idea is to use a queue and apply bfs and use a variable count to store the number of possible paths. Make a pair of row and column and insert (0, 0) into the queue. Now keep popping pairs from queue, if the popped value is the end of matrix then increment count, otherwise check if the next column can give a valid move or the next row can give a valid move and according to that, insert the corresponding row, column pair into the queue." }, { "code": null, "e": 27249, "s": 27196, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 27253, "s": 27249, "text": "C++" }, { "code": null, "e": 27258, "s": 27253, "text": "Java" }, { "code": null, "e": 27266, "s": 27258, "text": "Python3" }, { "code": null, "e": 27269, "s": 27266, "text": "C#" }, { "code": null, "e": 27280, "s": 27269, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; #define m 4#define n 3 // Function to return the number of valid// paths in the given mazeint Maze(int matrix[n][m]){ queue<pair<int, int> > q; // Insert the starting point i.e. // (0, 0) in the queue q.push(make_pair(0, 0)); // To store the count of possible paths int count = 0; while (!q.empty()) { pair<int, int> p = q.front(); q.pop(); // Increment the count of paths since // it is the destination if (p.first == n - 1 && p.second == m - 1) count++; // If moving to the next row is a valid move if (p.first + 1 < n && matrix[p.first + 1][p.second] == 1) { q.push(make_pair(p.first + 1, p.second)); } // If moving to the next column is a valid move if (p.second + 1 < m && matrix[p.first][p.second + 1] == 1) { q.push(make_pair(p.first, p.second + 1)); } } return count;} // Driver codeint main(){ // Matrix to represent maze int matrix[n][m] = { { 1, 0, 0, 1 }, { 1, 1, 1, 1 }, { 1, 0, 1, 1 } }; cout << Maze(matrix); return 0;}", "e": 28525, "s": 27280, "text": null }, { "code": "// Java implementation of the approachimport java.util.*;class GFG{static int m = 4;static int n = 3;static class pair{ int first, second; public pair(int first, int second) { this.first = first; this.second = second; }} // Function to return the number of valid// paths in the given mazestatic int Maze(int matrix[][]){ Queue<pair> q = new LinkedList<>(); // Insert the starting point i.e. // (0, 0) in the queue q.add(new pair(0, 0)); // To store the count of possible paths int count = 0; while (!q.isEmpty()) { pair p = q.peek(); q.remove(); // Increment the count of paths since // it is the destination if (p.first == n - 1 && p.second == m - 1) count++; // If moving to the next row is a valid move if (p.first + 1 < n && matrix[p.first + 1][p.second] == 1) { q.add(new pair(p.first + 1, p.second)); } // If moving to the next column is a valid move if (p.second + 1 < m && matrix[p.first][p.second + 1] == 1) { q.add(new pair(p.first, p.second + 1)); } } return count;} // Driver codepublic static void main(String[] args){ // Matrix to represent maze int matrix[][] = {{ 1, 0, 0, 1 }, { 1, 1, 1, 1 }, { 1, 0, 1, 1 }}; System.out.println(Maze(matrix));}} // This code is contributed by Princi Singh", "e": 29992, "s": 28525, "text": null }, { "code": "# Python3 implementation of the approachfrom collections import dequem = 4n = 3 # Function to return the number of valid# paths in the given mazedef Maze(matrix): q = deque() # Insert the starting poi.e. # (0, 0) in the queue q.append((0, 0)) # To store the count of possible paths count = 0 while (len(q) > 0): p = q.popleft() # Increment the count of paths since # it is the destination if (p[0] == n - 1 and p[1] == m - 1): count += 1 # If moving to the next row is a valid move if (p[0] + 1 < n and matrix[p[0] + 1][p[1]] == 1): q.append((p[0] + 1, p[1])) # If moving to the next column is a valid move if (p[1] + 1 < m and matrix[p[0]][p[1] + 1] == 1): q.append((p[0], p[1] + 1)) return count # Driver code # Matrix to represent mazematrix = [ [ 1, 0, 0, 1 ], [ 1, 1, 1, 1 ], [ 1, 0, 1, 1 ] ] print(Maze(matrix)) # This code is contributed by Mohit Kumar", "e": 31018, "s": 29992, "text": null }, { "code": "// C# implementation of the approachusing System;using System.Collections.Generic; class GFG{static int m = 4;static int n = 3;class pair{ public int first, second; public pair(int first, int second) { this.first = first; this.second = second; }} // Function to return the number of valid// paths in the given mazestatic int Maze(int [,]matrix){ Queue<pair> q = new Queue<pair>(); // Insert the starting point i.e. // (0, 0) in the queue q.Enqueue(new pair(0, 0)); // To store the count of possible paths int count = 0; while (q.Count != 0) { pair p = q.Peek(); q.Dequeue(); // Increment the count of paths since // it is the destination if (p.first == n - 1 && p.second == m - 1) count++; // If moving to the next row is a valid move if (p.first + 1 < n && matrix[p.first + 1, p.second] == 1) { q.Enqueue(new pair(p.first + 1, p.second)); } // If moving to the next column is a valid move if (p.second + 1 < m && matrix[p.first, p.second + 1] == 1) { q.Enqueue(new pair(p.first, p.second + 1)); } } return count;} // Driver codepublic static void Main(String[] args){ // Matrix to represent maze int [,]matrix = {{ 1, 0, 0, 1 }, { 1, 1, 1, 1 }, { 1, 0, 1, 1 }}; Console.WriteLine(Maze(matrix));}} // This code is contributed by PrinciRaj1992", "e": 32519, "s": 31018, "text": null }, { "code": "<script> // Javascript implementation of the approachvar m = 4;var n = 3; // Function to return the number of valid// paths in the given mazefunction Maze(matrix){ var q = []; // Insert the starting point i.e. // (0, 0) in the queue q.push([0, 0]); // To store the count of possible paths var count = 0; while (q.length != 0) { var p = q[0]; q.shift(); // Increment the count of paths since // it is the destination if (p[0] == n - 1 && p[1] == m - 1) count++; // If moving to the next row is a valid move if (p[0] + 1 < n && matrix[p[0] + 1][p[1]] == 1) { q.push([p[0] + 1, p[1]]); } // If moving to the next column is a valid move if (p[1] + 1 < m && matrix[p[0]][p[1] + 1] == 1) { q.push([p[0], p[1] + 1]); } } return count;} // Driver code // Matrix to represent mazevar matrix = [ [ 1, 0, 0, 1 ], [ 1, 1, 1, 1 ], [ 1, 0, 1, 1 ] ]; document.write( Maze(matrix)); // This code is contributed by rutvik_56 </script>", "e": 33662, "s": 32519, "text": null }, { "code": null, "e": 33664, "s": 33662, "text": "2" }, { "code": null, "e": 33722, "s": 33666, "text": "Time Complexity: O(N * M). Auxiliary Space: O(N * M). " }, { "code": null, "e": 33737, "s": 33722, "text": "mohit kumar 29" }, { "code": null, "e": 33750, "s": 33737, "text": "princi singh" }, { "code": null, "e": 33764, "s": 33750, "text": "princiraj1992" }, { "code": null, "e": 33774, "s": 33764, "text": "rutvik_56" }, { "code": null, "e": 33790, "s": 33774, "text": "pankajsharmagfg" }, { "code": null, "e": 33794, "s": 33790, "text": "BFS" }, { "code": null, "e": 33810, "s": 33794, "text": "Data Structures" }, { "code": null, "e": 33817, "s": 33810, "text": "Matrix" }, { "code": null, "e": 33823, "s": 33817, "text": "Queue" }, { "code": null, "e": 33839, "s": 33823, "text": "Data Structures" }, { "code": null, "e": 33846, "s": 33839, "text": "Matrix" }, { "code": null, "e": 33852, "s": 33846, "text": "Queue" }, { "code": null, "e": 33856, "s": 33852, "text": "BFS" }, { "code": null, "e": 33954, "s": 33856, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33981, "s": 33954, "text": "How to Start Learning DSA?" }, { "code": null, "e": 34017, "s": 33981, "text": "Introduction to Tree Data Structure" }, { "code": null, "e": 34076, "s": 34017, "text": "Program to implement Singly Linked List in C++ using class" }, { "code": null, "e": 34124, "s": 34076, "text": "Hash Functions and list/types of Hash functions" }, { "code": null, "e": 34147, "s": 34124, "text": "Insertion in a B+ tree" }, { "code": null, "e": 34182, "s": 34147, "text": "Matrix Chain Multiplication | DP-8" }, { "code": null, "e": 34226, "s": 34182, "text": "Program to find largest element in an array" }, { "code": null, "e": 34262, "s": 34226, "text": "Print a given matrix in spiral form" }, { "code": null, "e": 34293, "s": 34262, "text": "Rat in a Maze | Backtracking-2" } ]
Measure execution time with high precision in C/C++ - GeeksforGeeks
07 Mar, 2019 Execution time : The execution time or CPU time of a given task is defined as the time spent by the system executing that task in other way you can say the time during which a program is running.There are multiple way to measure execution time of a program, in this article i will discuss 5 different way tomeasure execution time of a program. Using time() function in C & C++.time() : time() function returns the time since the Epoch(jan 1 1970) in seconds.Header File : “time.h”Prototype / Syntax : time_t time(time_t *tloc);Return Value : On success, the value of time in seconds since the Epoch is returned, on error -1 is returned.Below program to demonstrate how to measure execution time using time() function.#include <bits/stdc++.h>using namespace std; // A sample function whose time taken to// be measuredvoid fun(){ for (int i=0; i<10; i++) { }} int main(){ /* Time function returns the time since the Epoch(jan 1 1970). Returned time is in seconds. */ time_t start, end; /* You can call it like this : start = time(NULL); in both the way start contain total time in seconds since the Epoch. */ time(&start); // unsync the I/O of C and C++. ios_base::sync_with_stdio(false); fun(); // Recording end time. time(&end); // Calculating total time taken by the program. double time_taken = double(end - start); cout << "Time taken by program is : " << fixed << time_taken << setprecision(5); cout << " sec " << endl; return 0;}Output:Time taken by program is : 0.000000 sec Using clock() function in C & C++.clock() : clock() returns the number of clock ticks elapsed since the program was launched.Header File : “time.h”Prototype / Syntax : clock_t clock(void);Return Value : On success, the value returned is the CPU time used so far as a clock_t; To get the number of seconds used, divide by CLOCKS_PER_SEC.on error -1 is returned.Below program to demonstrate how to measure execution time using clock() function.you can also see this#include <bits/stdc++.h>using namespace std; // A sample function whose time taken to// be measuredvoid fun(){ for (int i=0; i<10; i++) { }} int main(){ /* clock_t clock(void) returns the number of clock ticks elapsed since the program was launched.To get the number of seconds used by the CPU, you will need to divide by CLOCKS_PER_SEC.where CLOCKS_PER_SEC is 1000000 on typical 32 bit system. */ clock_t start, end; /* Recording the starting clock tick.*/ start = clock(); fun(); // Recording the end clock tick. end = clock(); // Calculating total time taken by the program. double time_taken = double(end - start) / double(CLOCKS_PER_SEC); cout << "Time taken by program is : " << fixed << time_taken << setprecision(5); cout << " sec " << endl; return 0;}Output:Time taken by program is : 0.000001 sec using gettimeofday() function in C & C++.gettimeofday() : The function gettimeofday() can get the time as well as timezone.Header File : “sys/time.h”.Prototype / Syntax : int gettimeofday(struct timeval *tv, struct timezone *tz);The tv argument is a struct timeval and gives the number of seconds and micro seconds since theEpoch.struct timeval {time_t tv_sec; // secondssuseconds_t tv_usec; // microseconds};Return Value : return 0 for success, or -1 for failure.Below program to demonstrate how to measure execution time using gettimeofday() function.#include <bits/stdc++.h>#include <sys/time.h>using namespace std; // A sample function whose time taken to// be measuredvoid fun(){ for (int i=0; i<10; i++) { }} int main(){ /* The function gettimeofday() can get the time as well as timezone. int gettimeofday(struct timeval *tv, struct timezone *tz); The tv argument is a struct timeval and gives the number of seconds and micro seconds since the Epoch. struct timeval { time_t tv_sec; // seconds suseconds_t tv_usec; // microseconds }; */ struct timeval start, end; // start timer. gettimeofday(&start, NULL); // unsync the I/O of C and C++. ios_base::sync_with_stdio(false); fun(); // stop timer. gettimeofday(&end, NULL); // Calculating total time taken by the program. double time_taken; time_taken = (end.tv_sec - start.tv_sec) * 1e6; time_taken = (time_taken + (end.tv_usec - start.tv_usec)) * 1e-6; cout << "Time taken by program is : " << fixed << time_taken << setprecision(6); cout << " sec" << endl; return 0;}Output:Time taken by program is : 0.000029 sec Using clock_gettime() function in C & C++.clock_gettime() : The clock_gettime() function gets the current time of the clock specified by clock_id, and puts it into the buffer pointed to by tp.Header File : “time.h”.Prototype / Syntax : int clock_gettime( clockid_t clock_id, struct timespec *tp );tp parameter points to a structure containing atleast the following members :struct timespec {time_t tv_sec; //secondslong tv_nsec; //nanoseconds};Return Value : return 0 for success, or -1 for failure.clock_id : clock id = CLOCK_REALTIME,CLOCK_PROCESS_CPUTIME_ID, CLOCK_MONOTONIC ... etc.CLOCK_REALTIME : clock that measures real i.e., wall-clock) time.CLOCK_PROCESS_CPUTIME_ID : High-resolution per-process timer from the CPU.CLOCK_MONOTONIC : High resolution timer that is unaffected by system date changes (e.g. NTP daemons).Below program to demonstrate how to measure execution time using clock_gettime() function.#include <bits/stdc++.h>#include <sys/time.h>using namespace std; // A sample function whose time taken to// be measuredvoid fun(){ for (int i=0; i<10; i++) { }} int main(){ /* int clock_gettime( clockid_t clock_id, struct timespec *tp ); The clock_gettime() function gets the current time of the clock specified by clock_id, and puts it into the buffer pointed to by tp.tp parameter points to a structure containing atleast the following members: struct timespec { time_t tv_sec; // seconds long tv_nsec; // nanoseconds }; clock id = CLOCK_REALTIME, CLOCK_PROCESS_CPUTIME_ID, CLOCK_MONOTONIC ...etc CLOCK_REALTIME : clock that measures real (i.e., wall-clock) time. CLOCK_PROCESS_CPUTIME_ID : High-resolution per-process timer from the CPU. CLOCK_MONOTONIC : High resolution timer that is unaffected by system date changes (e.g. NTP daemons). */ struct timespec start, end; // start timer. // clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &start); // clock_gettime(CLOCK_REALTIME, &start); clock_gettime(CLOCK_MONOTONIC, &start); // unsync the I/O of C and C++. ios_base::sync_with_stdio(false); fun(); // stop timer. // clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &end); // clock_gettime(CLOCK_REALTIME, &end); clock_gettime(CLOCK_MONOTONIC, &end); // Calculating total time taken by the program. double time_taken; time_taken = (end.tv_sec - start.tv_sec) * 1e9; time_taken = (time_taken + (end.tv_nsec - start.tv_nsec)) * 1e-9; cout << "Time taken by program is : " << fixed << time_taken << setprecision(9); cout << " sec" << endl; return 0;}Output:Time taken by program is : 0.000028 sec Using chrono::high_resolution_clock in C++.chrono : Chrono library is used to deal with date and time. This library was designed to deal with the fact that timers and clocks might be different on different systems and thus to improve over time in terms of precision.chrono is the name of a header, but also of a sub-namespace, All the elements in this header are not defined directly under the std namespace (like most of the standard library) but under the std::chrono namespace.Below program to demonstrate how to measure execution time using high_resolution_clock function. For detail info on chrono library see this and this#include <bits/stdc++.h>#include <chrono>using namespace std; // A sample function whose time taken to// be measuredvoid fun(){ for (int i=0; i<10; i++) { }} int main(){ auto start = chrono::high_resolution_clock::now(); // unsync the I/O of C and C++. ios_base::sync_with_stdio(false); fun(); auto end = chrono::high_resolution_clock::now(); // Calculating total time taken by the program. double time_taken = chrono::duration_cast<chrono::nanoseconds>(end - start).count(); time_taken *= 1e-9; cout << "Time taken by program is : " << fixed << time_taken << setprecision(9); cout << " sec" << endl; return 0;}Output:Time taken by program is : 0.000024 sec My Personal Notes arrow_drop_upSave Using time() function in C & C++.time() : time() function returns the time since the Epoch(jan 1 1970) in seconds.Header File : “time.h”Prototype / Syntax : time_t time(time_t *tloc);Return Value : On success, the value of time in seconds since the Epoch is returned, on error -1 is returned.Below program to demonstrate how to measure execution time using time() function.#include <bits/stdc++.h>using namespace std; // A sample function whose time taken to// be measuredvoid fun(){ for (int i=0; i<10; i++) { }} int main(){ /* Time function returns the time since the Epoch(jan 1 1970). Returned time is in seconds. */ time_t start, end; /* You can call it like this : start = time(NULL); in both the way start contain total time in seconds since the Epoch. */ time(&start); // unsync the I/O of C and C++. ios_base::sync_with_stdio(false); fun(); // Recording end time. time(&end); // Calculating total time taken by the program. double time_taken = double(end - start); cout << "Time taken by program is : " << fixed << time_taken << setprecision(5); cout << " sec " << endl; return 0;}Output:Time taken by program is : 0.000000 sec time() : time() function returns the time since the Epoch(jan 1 1970) in seconds.Header File : “time.h”Prototype / Syntax : time_t time(time_t *tloc);Return Value : On success, the value of time in seconds since the Epoch is returned, on error -1 is returned. Below program to demonstrate how to measure execution time using time() function. #include <bits/stdc++.h>using namespace std; // A sample function whose time taken to// be measuredvoid fun(){ for (int i=0; i<10; i++) { }} int main(){ /* Time function returns the time since the Epoch(jan 1 1970). Returned time is in seconds. */ time_t start, end; /* You can call it like this : start = time(NULL); in both the way start contain total time in seconds since the Epoch. */ time(&start); // unsync the I/O of C and C++. ios_base::sync_with_stdio(false); fun(); // Recording end time. time(&end); // Calculating total time taken by the program. double time_taken = double(end - start); cout << "Time taken by program is : " << fixed << time_taken << setprecision(5); cout << " sec " << endl; return 0;} Time taken by program is : 0.000000 sec Using clock() function in C & C++.clock() : clock() returns the number of clock ticks elapsed since the program was launched.Header File : “time.h”Prototype / Syntax : clock_t clock(void);Return Value : On success, the value returned is the CPU time used so far as a clock_t; To get the number of seconds used, divide by CLOCKS_PER_SEC.on error -1 is returned.Below program to demonstrate how to measure execution time using clock() function.you can also see this#include <bits/stdc++.h>using namespace std; // A sample function whose time taken to// be measuredvoid fun(){ for (int i=0; i<10; i++) { }} int main(){ /* clock_t clock(void) returns the number of clock ticks elapsed since the program was launched.To get the number of seconds used by the CPU, you will need to divide by CLOCKS_PER_SEC.where CLOCKS_PER_SEC is 1000000 on typical 32 bit system. */ clock_t start, end; /* Recording the starting clock tick.*/ start = clock(); fun(); // Recording the end clock tick. end = clock(); // Calculating total time taken by the program. double time_taken = double(end - start) / double(CLOCKS_PER_SEC); cout << "Time taken by program is : " << fixed << time_taken << setprecision(5); cout << " sec " << endl; return 0;}Output:Time taken by program is : 0.000001 sec clock() : clock() returns the number of clock ticks elapsed since the program was launched.Header File : “time.h”Prototype / Syntax : clock_t clock(void);Return Value : On success, the value returned is the CPU time used so far as a clock_t; To get the number of seconds used, divide by CLOCKS_PER_SEC.on error -1 is returned. Below program to demonstrate how to measure execution time using clock() function.you can also see this #include <bits/stdc++.h>using namespace std; // A sample function whose time taken to// be measuredvoid fun(){ for (int i=0; i<10; i++) { }} int main(){ /* clock_t clock(void) returns the number of clock ticks elapsed since the program was launched.To get the number of seconds used by the CPU, you will need to divide by CLOCKS_PER_SEC.where CLOCKS_PER_SEC is 1000000 on typical 32 bit system. */ clock_t start, end; /* Recording the starting clock tick.*/ start = clock(); fun(); // Recording the end clock tick. end = clock(); // Calculating total time taken by the program. double time_taken = double(end - start) / double(CLOCKS_PER_SEC); cout << "Time taken by program is : " << fixed << time_taken << setprecision(5); cout << " sec " << endl; return 0;} Time taken by program is : 0.000001 sec using gettimeofday() function in C & C++.gettimeofday() : The function gettimeofday() can get the time as well as timezone.Header File : “sys/time.h”.Prototype / Syntax : int gettimeofday(struct timeval *tv, struct timezone *tz);The tv argument is a struct timeval and gives the number of seconds and micro seconds since theEpoch.struct timeval {time_t tv_sec; // secondssuseconds_t tv_usec; // microseconds};Return Value : return 0 for success, or -1 for failure.Below program to demonstrate how to measure execution time using gettimeofday() function.#include <bits/stdc++.h>#include <sys/time.h>using namespace std; // A sample function whose time taken to// be measuredvoid fun(){ for (int i=0; i<10; i++) { }} int main(){ /* The function gettimeofday() can get the time as well as timezone. int gettimeofday(struct timeval *tv, struct timezone *tz); The tv argument is a struct timeval and gives the number of seconds and micro seconds since the Epoch. struct timeval { time_t tv_sec; // seconds suseconds_t tv_usec; // microseconds }; */ struct timeval start, end; // start timer. gettimeofday(&start, NULL); // unsync the I/O of C and C++. ios_base::sync_with_stdio(false); fun(); // stop timer. gettimeofday(&end, NULL); // Calculating total time taken by the program. double time_taken; time_taken = (end.tv_sec - start.tv_sec) * 1e6; time_taken = (time_taken + (end.tv_usec - start.tv_usec)) * 1e-6; cout << "Time taken by program is : " << fixed << time_taken << setprecision(6); cout << " sec" << endl; return 0;}Output:Time taken by program is : 0.000029 sec gettimeofday() : The function gettimeofday() can get the time as well as timezone.Header File : “sys/time.h”.Prototype / Syntax : int gettimeofday(struct timeval *tv, struct timezone *tz);The tv argument is a struct timeval and gives the number of seconds and micro seconds since theEpoch.struct timeval {time_t tv_sec; // secondssuseconds_t tv_usec; // microseconds};Return Value : return 0 for success, or -1 for failure. Below program to demonstrate how to measure execution time using gettimeofday() function. #include <bits/stdc++.h>#include <sys/time.h>using namespace std; // A sample function whose time taken to// be measuredvoid fun(){ for (int i=0; i<10; i++) { }} int main(){ /* The function gettimeofday() can get the time as well as timezone. int gettimeofday(struct timeval *tv, struct timezone *tz); The tv argument is a struct timeval and gives the number of seconds and micro seconds since the Epoch. struct timeval { time_t tv_sec; // seconds suseconds_t tv_usec; // microseconds }; */ struct timeval start, end; // start timer. gettimeofday(&start, NULL); // unsync the I/O of C and C++. ios_base::sync_with_stdio(false); fun(); // stop timer. gettimeofday(&end, NULL); // Calculating total time taken by the program. double time_taken; time_taken = (end.tv_sec - start.tv_sec) * 1e6; time_taken = (time_taken + (end.tv_usec - start.tv_usec)) * 1e-6; cout << "Time taken by program is : " << fixed << time_taken << setprecision(6); cout << " sec" << endl; return 0;} Time taken by program is : 0.000029 sec Using clock_gettime() function in C & C++.clock_gettime() : The clock_gettime() function gets the current time of the clock specified by clock_id, and puts it into the buffer pointed to by tp.Header File : “time.h”.Prototype / Syntax : int clock_gettime( clockid_t clock_id, struct timespec *tp );tp parameter points to a structure containing atleast the following members :struct timespec {time_t tv_sec; //secondslong tv_nsec; //nanoseconds};Return Value : return 0 for success, or -1 for failure.clock_id : clock id = CLOCK_REALTIME,CLOCK_PROCESS_CPUTIME_ID, CLOCK_MONOTONIC ... etc.CLOCK_REALTIME : clock that measures real i.e., wall-clock) time.CLOCK_PROCESS_CPUTIME_ID : High-resolution per-process timer from the CPU.CLOCK_MONOTONIC : High resolution timer that is unaffected by system date changes (e.g. NTP daemons).Below program to demonstrate how to measure execution time using clock_gettime() function.#include <bits/stdc++.h>#include <sys/time.h>using namespace std; // A sample function whose time taken to// be measuredvoid fun(){ for (int i=0; i<10; i++) { }} int main(){ /* int clock_gettime( clockid_t clock_id, struct timespec *tp ); The clock_gettime() function gets the current time of the clock specified by clock_id, and puts it into the buffer pointed to by tp.tp parameter points to a structure containing atleast the following members: struct timespec { time_t tv_sec; // seconds long tv_nsec; // nanoseconds }; clock id = CLOCK_REALTIME, CLOCK_PROCESS_CPUTIME_ID, CLOCK_MONOTONIC ...etc CLOCK_REALTIME : clock that measures real (i.e., wall-clock) time. CLOCK_PROCESS_CPUTIME_ID : High-resolution per-process timer from the CPU. CLOCK_MONOTONIC : High resolution timer that is unaffected by system date changes (e.g. NTP daemons). */ struct timespec start, end; // start timer. // clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &start); // clock_gettime(CLOCK_REALTIME, &start); clock_gettime(CLOCK_MONOTONIC, &start); // unsync the I/O of C and C++. ios_base::sync_with_stdio(false); fun(); // stop timer. // clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &end); // clock_gettime(CLOCK_REALTIME, &end); clock_gettime(CLOCK_MONOTONIC, &end); // Calculating total time taken by the program. double time_taken; time_taken = (end.tv_sec - start.tv_sec) * 1e9; time_taken = (time_taken + (end.tv_nsec - start.tv_nsec)) * 1e-9; cout << "Time taken by program is : " << fixed << time_taken << setprecision(9); cout << " sec" << endl; return 0;}Output:Time taken by program is : 0.000028 sec clock_gettime() : The clock_gettime() function gets the current time of the clock specified by clock_id, and puts it into the buffer pointed to by tp.Header File : “time.h”.Prototype / Syntax : int clock_gettime( clockid_t clock_id, struct timespec *tp );tp parameter points to a structure containing atleast the following members :struct timespec {time_t tv_sec; //secondslong tv_nsec; //nanoseconds};Return Value : return 0 for success, or -1 for failure.clock_id : clock id = CLOCK_REALTIME,CLOCK_PROCESS_CPUTIME_ID, CLOCK_MONOTONIC ... etc.CLOCK_REALTIME : clock that measures real i.e., wall-clock) time.CLOCK_PROCESS_CPUTIME_ID : High-resolution per-process timer from the CPU.CLOCK_MONOTONIC : High resolution timer that is unaffected by system date changes (e.g. NTP daemons). Below program to demonstrate how to measure execution time using clock_gettime() function. #include <bits/stdc++.h>#include <sys/time.h>using namespace std; // A sample function whose time taken to// be measuredvoid fun(){ for (int i=0; i<10; i++) { }} int main(){ /* int clock_gettime( clockid_t clock_id, struct timespec *tp ); The clock_gettime() function gets the current time of the clock specified by clock_id, and puts it into the buffer pointed to by tp.tp parameter points to a structure containing atleast the following members: struct timespec { time_t tv_sec; // seconds long tv_nsec; // nanoseconds }; clock id = CLOCK_REALTIME, CLOCK_PROCESS_CPUTIME_ID, CLOCK_MONOTONIC ...etc CLOCK_REALTIME : clock that measures real (i.e., wall-clock) time. CLOCK_PROCESS_CPUTIME_ID : High-resolution per-process timer from the CPU. CLOCK_MONOTONIC : High resolution timer that is unaffected by system date changes (e.g. NTP daemons). */ struct timespec start, end; // start timer. // clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &start); // clock_gettime(CLOCK_REALTIME, &start); clock_gettime(CLOCK_MONOTONIC, &start); // unsync the I/O of C and C++. ios_base::sync_with_stdio(false); fun(); // stop timer. // clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &end); // clock_gettime(CLOCK_REALTIME, &end); clock_gettime(CLOCK_MONOTONIC, &end); // Calculating total time taken by the program. double time_taken; time_taken = (end.tv_sec - start.tv_sec) * 1e9; time_taken = (time_taken + (end.tv_nsec - start.tv_nsec)) * 1e-9; cout << "Time taken by program is : " << fixed << time_taken << setprecision(9); cout << " sec" << endl; return 0;} Time taken by program is : 0.000028 sec Using chrono::high_resolution_clock in C++.chrono : Chrono library is used to deal with date and time. This library was designed to deal with the fact that timers and clocks might be different on different systems and thus to improve over time in terms of precision.chrono is the name of a header, but also of a sub-namespace, All the elements in this header are not defined directly under the std namespace (like most of the standard library) but under the std::chrono namespace.Below program to demonstrate how to measure execution time using high_resolution_clock function. For detail info on chrono library see this and this#include <bits/stdc++.h>#include <chrono>using namespace std; // A sample function whose time taken to// be measuredvoid fun(){ for (int i=0; i<10; i++) { }} int main(){ auto start = chrono::high_resolution_clock::now(); // unsync the I/O of C and C++. ios_base::sync_with_stdio(false); fun(); auto end = chrono::high_resolution_clock::now(); // Calculating total time taken by the program. double time_taken = chrono::duration_cast<chrono::nanoseconds>(end - start).count(); time_taken *= 1e-9; cout << "Time taken by program is : " << fixed << time_taken << setprecision(9); cout << " sec" << endl; return 0;}Output:Time taken by program is : 0.000024 sec My Personal Notes arrow_drop_upSave chrono : Chrono library is used to deal with date and time. This library was designed to deal with the fact that timers and clocks might be different on different systems and thus to improve over time in terms of precision.chrono is the name of a header, but also of a sub-namespace, All the elements in this header are not defined directly under the std namespace (like most of the standard library) but under the std::chrono namespace. Below program to demonstrate how to measure execution time using high_resolution_clock function. For detail info on chrono library see this and this #include <bits/stdc++.h>#include <chrono>using namespace std; // A sample function whose time taken to// be measuredvoid fun(){ for (int i=0; i<10; i++) { }} int main(){ auto start = chrono::high_resolution_clock::now(); // unsync the I/O of C and C++. ios_base::sync_with_stdio(false); fun(); auto end = chrono::high_resolution_clock::now(); // Calculating total time taken by the program. double time_taken = chrono::duration_cast<chrono::nanoseconds>(end - start).count(); time_taken *= 1e-9; cout << "Time taken by program is : " << fixed << time_taken << setprecision(9); cout << " sec" << endl; return 0;} Time taken by program is : 0.000024 sec Analysis C Language C Programs C++ C++ Programs CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Time Complexity and Space Complexity Complexity of different operations in Binary tree, Binary Search Tree and AVL tree Time Complexity of building a heap Analysis of Algorithms | Big-O analysis Analysis of different sorting techniques Arrays in C/C++ Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc() std::sort() in C++ STL Bitwise Operators in C/C++ Multidimensional Arrays in C / C++
[ { "code": null, "e": 26431, "s": 26403, "text": "\n07 Mar, 2019" }, { "code": null, "e": 26775, "s": 26431, "text": "Execution time : The execution time or CPU time of a given task is defined as the time spent by the system executing that task in other way you can say the time during which a program is running.There are multiple way to measure execution time of a program, in this article i will discuss 5 different way tomeasure execution time of a program." }, { "code": null, "e": 35285, "s": 26775, "text": "Using time() function in C & C++.time() : time() function returns the time since the Epoch(jan 1 1970) in seconds.Header File : “time.h”Prototype / Syntax : time_t time(time_t *tloc);Return Value : On success, the value of time in seconds since the Epoch is returned, on error -1 is returned.Below program to demonstrate how to measure execution time using time() function.#include <bits/stdc++.h>using namespace std; // A sample function whose time taken to// be measuredvoid fun(){ for (int i=0; i<10; i++) { }} int main(){ /* Time function returns the time since the Epoch(jan 1 1970). Returned time is in seconds. */ time_t start, end; /* You can call it like this : start = time(NULL); in both the way start contain total time in seconds since the Epoch. */ time(&start); // unsync the I/O of C and C++. ios_base::sync_with_stdio(false); fun(); // Recording end time. time(&end); // Calculating total time taken by the program. double time_taken = double(end - start); cout << \"Time taken by program is : \" << fixed << time_taken << setprecision(5); cout << \" sec \" << endl; return 0;}Output:Time taken by program is : 0.000000 sec\nUsing clock() function in C & C++.clock() : clock() returns the number of clock ticks elapsed since the program was launched.Header File : “time.h”Prototype / Syntax : clock_t clock(void);Return Value : On success, the value returned is the CPU time used so far as a clock_t; To get the number of seconds used, divide by CLOCKS_PER_SEC.on error -1 is returned.Below program to demonstrate how to measure execution time using clock() function.you can also see this#include <bits/stdc++.h>using namespace std; // A sample function whose time taken to// be measuredvoid fun(){ for (int i=0; i<10; i++) { }} int main(){ /* clock_t clock(void) returns the number of clock ticks elapsed since the program was launched.To get the number of seconds used by the CPU, you will need to divide by CLOCKS_PER_SEC.where CLOCKS_PER_SEC is 1000000 on typical 32 bit system. */ clock_t start, end; /* Recording the starting clock tick.*/ start = clock(); fun(); // Recording the end clock tick. end = clock(); // Calculating total time taken by the program. double time_taken = double(end - start) / double(CLOCKS_PER_SEC); cout << \"Time taken by program is : \" << fixed << time_taken << setprecision(5); cout << \" sec \" << endl; return 0;}Output:Time taken by program is : 0.000001 sec\nusing gettimeofday() function in C & C++.gettimeofday() : The function gettimeofday() can get the time as well as timezone.Header File : “sys/time.h”.Prototype / Syntax : int gettimeofday(struct timeval *tv, struct timezone *tz);The tv argument is a struct timeval and gives the number of seconds and micro seconds since theEpoch.struct timeval {time_t tv_sec; // secondssuseconds_t tv_usec; // microseconds};Return Value : return 0 for success, or -1 for failure.Below program to demonstrate how to measure execution time using gettimeofday() function.#include <bits/stdc++.h>#include <sys/time.h>using namespace std; // A sample function whose time taken to// be measuredvoid fun(){ for (int i=0; i<10; i++) { }} int main(){ /* The function gettimeofday() can get the time as well as timezone. int gettimeofday(struct timeval *tv, struct timezone *tz); The tv argument is a struct timeval and gives the number of seconds and micro seconds since the Epoch. struct timeval { time_t tv_sec; // seconds suseconds_t tv_usec; // microseconds }; */ struct timeval start, end; // start timer. gettimeofday(&start, NULL); // unsync the I/O of C and C++. ios_base::sync_with_stdio(false); fun(); // stop timer. gettimeofday(&end, NULL); // Calculating total time taken by the program. double time_taken; time_taken = (end.tv_sec - start.tv_sec) * 1e6; time_taken = (time_taken + (end.tv_usec - start.tv_usec)) * 1e-6; cout << \"Time taken by program is : \" << fixed << time_taken << setprecision(6); cout << \" sec\" << endl; return 0;}Output:Time taken by program is : 0.000029 sec\nUsing clock_gettime() function in C & C++.clock_gettime() : The clock_gettime() function gets the current time of the clock specified by clock_id, and puts it into the buffer pointed to by tp.Header File : “time.h”.Prototype / Syntax : int clock_gettime( clockid_t clock_id, struct timespec *tp );tp parameter points to a structure containing atleast the following members :struct timespec {time_t tv_sec; //secondslong tv_nsec; //nanoseconds};Return Value : return 0 for success, or -1 for failure.clock_id : clock id = CLOCK_REALTIME,CLOCK_PROCESS_CPUTIME_ID, CLOCK_MONOTONIC ... etc.CLOCK_REALTIME : clock that measures real i.e., wall-clock) time.CLOCK_PROCESS_CPUTIME_ID : High-resolution per-process timer from the CPU.CLOCK_MONOTONIC : High resolution timer that is unaffected by system date changes (e.g. NTP daemons).Below program to demonstrate how to measure execution time using clock_gettime() function.#include <bits/stdc++.h>#include <sys/time.h>using namespace std; // A sample function whose time taken to// be measuredvoid fun(){ for (int i=0; i<10; i++) { }} int main(){ /* int clock_gettime( clockid_t clock_id, struct timespec *tp ); The clock_gettime() function gets the current time of the clock specified by clock_id, and puts it into the buffer pointed to by tp.tp parameter points to a structure containing atleast the following members: struct timespec { time_t tv_sec; // seconds long tv_nsec; // nanoseconds }; clock id = CLOCK_REALTIME, CLOCK_PROCESS_CPUTIME_ID, CLOCK_MONOTONIC ...etc CLOCK_REALTIME : clock that measures real (i.e., wall-clock) time. CLOCK_PROCESS_CPUTIME_ID : High-resolution per-process timer from the CPU. CLOCK_MONOTONIC : High resolution timer that is unaffected by system date changes (e.g. NTP daemons). */ struct timespec start, end; // start timer. // clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &start); // clock_gettime(CLOCK_REALTIME, &start); clock_gettime(CLOCK_MONOTONIC, &start); // unsync the I/O of C and C++. ios_base::sync_with_stdio(false); fun(); // stop timer. // clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &end); // clock_gettime(CLOCK_REALTIME, &end); clock_gettime(CLOCK_MONOTONIC, &end); // Calculating total time taken by the program. double time_taken; time_taken = (end.tv_sec - start.tv_sec) * 1e9; time_taken = (time_taken + (end.tv_nsec - start.tv_nsec)) * 1e-9; cout << \"Time taken by program is : \" << fixed << time_taken << setprecision(9); cout << \" sec\" << endl; return 0;}Output:Time taken by program is : 0.000028 sec\nUsing chrono::high_resolution_clock in C++.chrono : Chrono library is used to deal with date and time. This library was designed to deal with the fact that timers and clocks might be different on different systems and thus to improve over time in terms of precision.chrono is the name of a header, but also of a sub-namespace, All the elements in this header are not defined directly under the std namespace (like most of the standard library) but under the std::chrono namespace.Below program to demonstrate how to measure execution time using high_resolution_clock function. For detail info on chrono library see this and this#include <bits/stdc++.h>#include <chrono>using namespace std; // A sample function whose time taken to// be measuredvoid fun(){ for (int i=0; i<10; i++) { }} int main(){ auto start = chrono::high_resolution_clock::now(); // unsync the I/O of C and C++. ios_base::sync_with_stdio(false); fun(); auto end = chrono::high_resolution_clock::now(); // Calculating total time taken by the program. double time_taken = chrono::duration_cast<chrono::nanoseconds>(end - start).count(); time_taken *= 1e-9; cout << \"Time taken by program is : \" << fixed << time_taken << setprecision(9); cout << \" sec\" << endl; return 0;}Output:Time taken by program is : 0.000024 sec\nMy Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 36511, "s": 35285, "text": "Using time() function in C & C++.time() : time() function returns the time since the Epoch(jan 1 1970) in seconds.Header File : “time.h”Prototype / Syntax : time_t time(time_t *tloc);Return Value : On success, the value of time in seconds since the Epoch is returned, on error -1 is returned.Below program to demonstrate how to measure execution time using time() function.#include <bits/stdc++.h>using namespace std; // A sample function whose time taken to// be measuredvoid fun(){ for (int i=0; i<10; i++) { }} int main(){ /* Time function returns the time since the Epoch(jan 1 1970). Returned time is in seconds. */ time_t start, end; /* You can call it like this : start = time(NULL); in both the way start contain total time in seconds since the Epoch. */ time(&start); // unsync the I/O of C and C++. ios_base::sync_with_stdio(false); fun(); // Recording end time. time(&end); // Calculating total time taken by the program. double time_taken = double(end - start); cout << \"Time taken by program is : \" << fixed << time_taken << setprecision(5); cout << \" sec \" << endl; return 0;}Output:Time taken by program is : 0.000000 sec\n" }, { "code": null, "e": 36771, "s": 36511, "text": "time() : time() function returns the time since the Epoch(jan 1 1970) in seconds.Header File : “time.h”Prototype / Syntax : time_t time(time_t *tloc);Return Value : On success, the value of time in seconds since the Epoch is returned, on error -1 is returned." }, { "code": null, "e": 36853, "s": 36771, "text": "Below program to demonstrate how to measure execution time using time() function." }, { "code": "#include <bits/stdc++.h>using namespace std; // A sample function whose time taken to// be measuredvoid fun(){ for (int i=0; i<10; i++) { }} int main(){ /* Time function returns the time since the Epoch(jan 1 1970). Returned time is in seconds. */ time_t start, end; /* You can call it like this : start = time(NULL); in both the way start contain total time in seconds since the Epoch. */ time(&start); // unsync the I/O of C and C++. ios_base::sync_with_stdio(false); fun(); // Recording end time. time(&end); // Calculating total time taken by the program. double time_taken = double(end - start); cout << \"Time taken by program is : \" << fixed << time_taken << setprecision(5); cout << \" sec \" << endl; return 0;}", "e": 37659, "s": 36853, "text": null }, { "code": null, "e": 37700, "s": 37659, "text": "Time taken by program is : 0.000000 sec\n" }, { "code": null, "e": 39062, "s": 37700, "text": "Using clock() function in C & C++.clock() : clock() returns the number of clock ticks elapsed since the program was launched.Header File : “time.h”Prototype / Syntax : clock_t clock(void);Return Value : On success, the value returned is the CPU time used so far as a clock_t; To get the number of seconds used, divide by CLOCKS_PER_SEC.on error -1 is returned.Below program to demonstrate how to measure execution time using clock() function.you can also see this#include <bits/stdc++.h>using namespace std; // A sample function whose time taken to// be measuredvoid fun(){ for (int i=0; i<10; i++) { }} int main(){ /* clock_t clock(void) returns the number of clock ticks elapsed since the program was launched.To get the number of seconds used by the CPU, you will need to divide by CLOCKS_PER_SEC.where CLOCKS_PER_SEC is 1000000 on typical 32 bit system. */ clock_t start, end; /* Recording the starting clock tick.*/ start = clock(); fun(); // Recording the end clock tick. end = clock(); // Calculating total time taken by the program. double time_taken = double(end - start) / double(CLOCKS_PER_SEC); cout << \"Time taken by program is : \" << fixed << time_taken << setprecision(5); cout << \" sec \" << endl; return 0;}Output:Time taken by program is : 0.000001 sec\n" }, { "code": null, "e": 39389, "s": 39062, "text": "clock() : clock() returns the number of clock ticks elapsed since the program was launched.Header File : “time.h”Prototype / Syntax : clock_t clock(void);Return Value : On success, the value returned is the CPU time used so far as a clock_t; To get the number of seconds used, divide by CLOCKS_PER_SEC.on error -1 is returned." }, { "code": null, "e": 39493, "s": 39389, "text": "Below program to demonstrate how to measure execution time using clock() function.you can also see this" }, { "code": "#include <bits/stdc++.h>using namespace std; // A sample function whose time taken to// be measuredvoid fun(){ for (int i=0; i<10; i++) { }} int main(){ /* clock_t clock(void) returns the number of clock ticks elapsed since the program was launched.To get the number of seconds used by the CPU, you will need to divide by CLOCKS_PER_SEC.where CLOCKS_PER_SEC is 1000000 on typical 32 bit system. */ clock_t start, end; /* Recording the starting clock tick.*/ start = clock(); fun(); // Recording the end clock tick. end = clock(); // Calculating total time taken by the program. double time_taken = double(end - start) / double(CLOCKS_PER_SEC); cout << \"Time taken by program is : \" << fixed << time_taken << setprecision(5); cout << \" sec \" << endl; return 0;}", "e": 40345, "s": 39493, "text": null }, { "code": null, "e": 40386, "s": 40345, "text": "Time taken by program is : 0.000001 sec\n" }, { "code": null, "e": 42152, "s": 40386, "text": "using gettimeofday() function in C & C++.gettimeofday() : The function gettimeofday() can get the time as well as timezone.Header File : “sys/time.h”.Prototype / Syntax : int gettimeofday(struct timeval *tv, struct timezone *tz);The tv argument is a struct timeval and gives the number of seconds and micro seconds since theEpoch.struct timeval {time_t tv_sec; // secondssuseconds_t tv_usec; // microseconds};Return Value : return 0 for success, or -1 for failure.Below program to demonstrate how to measure execution time using gettimeofday() function.#include <bits/stdc++.h>#include <sys/time.h>using namespace std; // A sample function whose time taken to// be measuredvoid fun(){ for (int i=0; i<10; i++) { }} int main(){ /* The function gettimeofday() can get the time as well as timezone. int gettimeofday(struct timeval *tv, struct timezone *tz); The tv argument is a struct timeval and gives the number of seconds and micro seconds since the Epoch. struct timeval { time_t tv_sec; // seconds suseconds_t tv_usec; // microseconds }; */ struct timeval start, end; // start timer. gettimeofday(&start, NULL); // unsync the I/O of C and C++. ios_base::sync_with_stdio(false); fun(); // stop timer. gettimeofday(&end, NULL); // Calculating total time taken by the program. double time_taken; time_taken = (end.tv_sec - start.tv_sec) * 1e6; time_taken = (time_taken + (end.tv_usec - start.tv_usec)) * 1e-6; cout << \"Time taken by program is : \" << fixed << time_taken << setprecision(6); cout << \" sec\" << endl; return 0;}Output:Time taken by program is : 0.000029 sec\n" }, { "code": null, "e": 42576, "s": 42152, "text": "gettimeofday() : The function gettimeofday() can get the time as well as timezone.Header File : “sys/time.h”.Prototype / Syntax : int gettimeofday(struct timeval *tv, struct timezone *tz);The tv argument is a struct timeval and gives the number of seconds and micro seconds since theEpoch.struct timeval {time_t tv_sec; // secondssuseconds_t tv_usec; // microseconds};Return Value : return 0 for success, or -1 for failure." }, { "code": null, "e": 42666, "s": 42576, "text": "Below program to demonstrate how to measure execution time using gettimeofday() function." }, { "code": "#include <bits/stdc++.h>#include <sys/time.h>using namespace std; // A sample function whose time taken to// be measuredvoid fun(){ for (int i=0; i<10; i++) { }} int main(){ /* The function gettimeofday() can get the time as well as timezone. int gettimeofday(struct timeval *tv, struct timezone *tz); The tv argument is a struct timeval and gives the number of seconds and micro seconds since the Epoch. struct timeval { time_t tv_sec; // seconds suseconds_t tv_usec; // microseconds }; */ struct timeval start, end; // start timer. gettimeofday(&start, NULL); // unsync the I/O of C and C++. ios_base::sync_with_stdio(false); fun(); // stop timer. gettimeofday(&end, NULL); // Calculating total time taken by the program. double time_taken; time_taken = (end.tv_sec - start.tv_sec) * 1e6; time_taken = (time_taken + (end.tv_usec - start.tv_usec)) * 1e-6; cout << \"Time taken by program is : \" << fixed << time_taken << setprecision(6); cout << \" sec\" << endl; return 0;}", "e": 43832, "s": 42666, "text": null }, { "code": null, "e": 43873, "s": 43832, "text": "Time taken by program is : 0.000029 sec\n" }, { "code": null, "e": 46638, "s": 43873, "text": "Using clock_gettime() function in C & C++.clock_gettime() : The clock_gettime() function gets the current time of the clock specified by clock_id, and puts it into the buffer pointed to by tp.Header File : “time.h”.Prototype / Syntax : int clock_gettime( clockid_t clock_id, struct timespec *tp );tp parameter points to a structure containing atleast the following members :struct timespec {time_t tv_sec; //secondslong tv_nsec; //nanoseconds};Return Value : return 0 for success, or -1 for failure.clock_id : clock id = CLOCK_REALTIME,CLOCK_PROCESS_CPUTIME_ID, CLOCK_MONOTONIC ... etc.CLOCK_REALTIME : clock that measures real i.e., wall-clock) time.CLOCK_PROCESS_CPUTIME_ID : High-resolution per-process timer from the CPU.CLOCK_MONOTONIC : High resolution timer that is unaffected by system date changes (e.g. NTP daemons).Below program to demonstrate how to measure execution time using clock_gettime() function.#include <bits/stdc++.h>#include <sys/time.h>using namespace std; // A sample function whose time taken to// be measuredvoid fun(){ for (int i=0; i<10; i++) { }} int main(){ /* int clock_gettime( clockid_t clock_id, struct timespec *tp ); The clock_gettime() function gets the current time of the clock specified by clock_id, and puts it into the buffer pointed to by tp.tp parameter points to a structure containing atleast the following members: struct timespec { time_t tv_sec; // seconds long tv_nsec; // nanoseconds }; clock id = CLOCK_REALTIME, CLOCK_PROCESS_CPUTIME_ID, CLOCK_MONOTONIC ...etc CLOCK_REALTIME : clock that measures real (i.e., wall-clock) time. CLOCK_PROCESS_CPUTIME_ID : High-resolution per-process timer from the CPU. CLOCK_MONOTONIC : High resolution timer that is unaffected by system date changes (e.g. NTP daemons). */ struct timespec start, end; // start timer. // clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &start); // clock_gettime(CLOCK_REALTIME, &start); clock_gettime(CLOCK_MONOTONIC, &start); // unsync the I/O of C and C++. ios_base::sync_with_stdio(false); fun(); // stop timer. // clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &end); // clock_gettime(CLOCK_REALTIME, &end); clock_gettime(CLOCK_MONOTONIC, &end); // Calculating total time taken by the program. double time_taken; time_taken = (end.tv_sec - start.tv_sec) * 1e9; time_taken = (time_taken + (end.tv_nsec - start.tv_nsec)) * 1e-9; cout << \"Time taken by program is : \" << fixed << time_taken << setprecision(9); cout << \" sec\" << endl; return 0;}Output:Time taken by program is : 0.000028 sec\n" }, { "code": null, "e": 47423, "s": 46638, "text": "clock_gettime() : The clock_gettime() function gets the current time of the clock specified by clock_id, and puts it into the buffer pointed to by tp.Header File : “time.h”.Prototype / Syntax : int clock_gettime( clockid_t clock_id, struct timespec *tp );tp parameter points to a structure containing atleast the following members :struct timespec {time_t tv_sec; //secondslong tv_nsec; //nanoseconds};Return Value : return 0 for success, or -1 for failure.clock_id : clock id = CLOCK_REALTIME,CLOCK_PROCESS_CPUTIME_ID, CLOCK_MONOTONIC ... etc.CLOCK_REALTIME : clock that measures real i.e., wall-clock) time.CLOCK_PROCESS_CPUTIME_ID : High-resolution per-process timer from the CPU.CLOCK_MONOTONIC : High resolution timer that is unaffected by system date changes (e.g. NTP daemons)." }, { "code": null, "e": 47514, "s": 47423, "text": "Below program to demonstrate how to measure execution time using clock_gettime() function." }, { "code": "#include <bits/stdc++.h>#include <sys/time.h>using namespace std; // A sample function whose time taken to// be measuredvoid fun(){ for (int i=0; i<10; i++) { }} int main(){ /* int clock_gettime( clockid_t clock_id, struct timespec *tp ); The clock_gettime() function gets the current time of the clock specified by clock_id, and puts it into the buffer pointed to by tp.tp parameter points to a structure containing atleast the following members: struct timespec { time_t tv_sec; // seconds long tv_nsec; // nanoseconds }; clock id = CLOCK_REALTIME, CLOCK_PROCESS_CPUTIME_ID, CLOCK_MONOTONIC ...etc CLOCK_REALTIME : clock that measures real (i.e., wall-clock) time. CLOCK_PROCESS_CPUTIME_ID : High-resolution per-process timer from the CPU. CLOCK_MONOTONIC : High resolution timer that is unaffected by system date changes (e.g. NTP daemons). */ struct timespec start, end; // start timer. // clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &start); // clock_gettime(CLOCK_REALTIME, &start); clock_gettime(CLOCK_MONOTONIC, &start); // unsync the I/O of C and C++. ios_base::sync_with_stdio(false); fun(); // stop timer. // clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &end); // clock_gettime(CLOCK_REALTIME, &end); clock_gettime(CLOCK_MONOTONIC, &end); // Calculating total time taken by the program. double time_taken; time_taken = (end.tv_sec - start.tv_sec) * 1e9; time_taken = (time_taken + (end.tv_nsec - start.tv_nsec)) * 1e-9; cout << \"Time taken by program is : \" << fixed << time_taken << setprecision(9); cout << \" sec\" << endl; return 0;}", "e": 49316, "s": 47514, "text": null }, { "code": null, "e": 49357, "s": 49316, "text": "Time taken by program is : 0.000028 sec\n" }, { "code": null, "e": 50752, "s": 49357, "text": "Using chrono::high_resolution_clock in C++.chrono : Chrono library is used to deal with date and time. This library was designed to deal with the fact that timers and clocks might be different on different systems and thus to improve over time in terms of precision.chrono is the name of a header, but also of a sub-namespace, All the elements in this header are not defined directly under the std namespace (like most of the standard library) but under the std::chrono namespace.Below program to demonstrate how to measure execution time using high_resolution_clock function. For detail info on chrono library see this and this#include <bits/stdc++.h>#include <chrono>using namespace std; // A sample function whose time taken to// be measuredvoid fun(){ for (int i=0; i<10; i++) { }} int main(){ auto start = chrono::high_resolution_clock::now(); // unsync the I/O of C and C++. ios_base::sync_with_stdio(false); fun(); auto end = chrono::high_resolution_clock::now(); // Calculating total time taken by the program. double time_taken = chrono::duration_cast<chrono::nanoseconds>(end - start).count(); time_taken *= 1e-9; cout << \"Time taken by program is : \" << fixed << time_taken << setprecision(9); cout << \" sec\" << endl; return 0;}Output:Time taken by program is : 0.000024 sec\nMy Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 51190, "s": 50752, "text": "chrono : Chrono library is used to deal with date and time. This library was designed to deal with the fact that timers and clocks might be different on different systems and thus to improve over time in terms of precision.chrono is the name of a header, but also of a sub-namespace, All the elements in this header are not defined directly under the std namespace (like most of the standard library) but under the std::chrono namespace." }, { "code": null, "e": 51339, "s": 51190, "text": "Below program to demonstrate how to measure execution time using high_resolution_clock function. For detail info on chrono library see this and this" }, { "code": "#include <bits/stdc++.h>#include <chrono>using namespace std; // A sample function whose time taken to// be measuredvoid fun(){ for (int i=0; i<10; i++) { }} int main(){ auto start = chrono::high_resolution_clock::now(); // unsync the I/O of C and C++. ios_base::sync_with_stdio(false); fun(); auto end = chrono::high_resolution_clock::now(); // Calculating total time taken by the program. double time_taken = chrono::duration_cast<chrono::nanoseconds>(end - start).count(); time_taken *= 1e-9; cout << \"Time taken by program is : \" << fixed << time_taken << setprecision(9); cout << \" sec\" << endl; return 0;}", "e": 52024, "s": 51339, "text": null }, { "code": null, "e": 52065, "s": 52024, "text": "Time taken by program is : 0.000024 sec\n" }, { "code": null, "e": 52074, "s": 52065, "text": "Analysis" }, { "code": null, "e": 52085, "s": 52074, "text": "C Language" }, { "code": null, "e": 52096, "s": 52085, "text": "C Programs" }, { "code": null, "e": 52100, "s": 52096, "text": "C++" }, { "code": null, "e": 52113, "s": 52100, "text": "C++ Programs" }, { "code": null, "e": 52117, "s": 52113, "text": "CPP" }, { "code": null, "e": 52215, "s": 52117, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 52252, "s": 52215, "text": "Time Complexity and Space Complexity" }, { "code": null, "e": 52335, "s": 52252, "text": "Complexity of different operations in Binary tree, Binary Search Tree and AVL tree" }, { "code": null, "e": 52370, "s": 52335, "text": "Time Complexity of building a heap" }, { "code": null, "e": 52410, "s": 52370, "text": "Analysis of Algorithms | Big-O analysis" }, { "code": null, "e": 52451, "s": 52410, "text": "Analysis of different sorting techniques" }, { "code": null, "e": 52467, "s": 52451, "text": "Arrays in C/C++" }, { "code": null, "e": 52545, "s": 52467, "text": "Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()" }, { "code": null, "e": 52568, "s": 52545, "text": "std::sort() in C++ STL" }, { "code": null, "e": 52595, "s": 52568, "text": "Bitwise Operators in C/C++" } ]
How to change image on hover with CSS ? - GeeksforGeeks
26 Nov, 2020 The approach of this article is to change an image when the user hovering the mouse over it. This task can be simply done by using the CSS background-image property in combination with the :hover pseudo-class to replace or change the image on mouseover. Example: HTML <!DOCTYPE html><html lang="en"> <head> <title> How to Change Image on Hover in CSS </title> <style> .sudo { width: 230px; height: 195px; margin: 50px; background-image: url("https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190417124305/250.png"); } .sudo:hover { background-image: url("https://media.geeksforgeeks.org/wp-content/uploads/rk.png"); } </style></head> <body> <h2>GeeksForGeeks</h2> <h2> How to change image on hover with CSS </h2> <div class="sudo"></div></body> </html> Output: Before hovering the mouse over the image: After hovering the mouse over the image: Supported Browsers are listed below: Google Chrome Internet Explorer Firefox Opera Safari Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. CSS-Misc HTML-Misc CSS HTML Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to set space between the flexbox ? Design a web page using HTML and CSS Form validation using jQuery How to style a checkbox using CSS? Search Bar using HTML, CSS and JavaScript How to set the default value for an HTML <select> element ? Hide or show elements in HTML using display property How to set input type date in dd-mm-yyyy format using HTML ? REST API (Introduction) How to Insert Form Data into Database using PHP ?
[ { "code": null, "e": 26647, "s": 26619, "text": "\n26 Nov, 2020" }, { "code": null, "e": 26902, "s": 26647, "text": "The approach of this article is to change an image when the user hovering the mouse over it. This task can be simply done by using the CSS background-image property in combination with the :hover pseudo-class to replace or change the image on mouseover. " }, { "code": null, "e": 26911, "s": 26902, "text": "Example:" }, { "code": null, "e": 26916, "s": 26911, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <title> How to Change Image on Hover in CSS </title> <style> .sudo { width: 230px; height: 195px; margin: 50px; background-image: url(\"https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190417124305/250.png\"); } .sudo:hover { background-image: url(\"https://media.geeksforgeeks.org/wp-content/uploads/rk.png\"); } </style></head> <body> <h2>GeeksForGeeks</h2> <h2> How to change image on hover with CSS </h2> <div class=\"sudo\"></div></body> </html>", "e": 27560, "s": 26916, "text": null }, { "code": null, "e": 27568, "s": 27560, "text": "Output:" }, { "code": null, "e": 27610, "s": 27568, "text": "Before hovering the mouse over the image:" }, { "code": null, "e": 27652, "s": 27610, "text": "After hovering the mouse over the image: " }, { "code": null, "e": 27689, "s": 27652, "text": "Supported Browsers are listed below:" }, { "code": null, "e": 27703, "s": 27689, "text": "Google Chrome" }, { "code": null, "e": 27721, "s": 27703, "text": "Internet Explorer" }, { "code": null, "e": 27729, "s": 27721, "text": "Firefox" }, { "code": null, "e": 27735, "s": 27729, "text": "Opera" }, { "code": null, "e": 27742, "s": 27735, "text": "Safari" }, { "code": null, "e": 27879, "s": 27742, "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": 27888, "s": 27879, "text": "CSS-Misc" }, { "code": null, "e": 27898, "s": 27888, "text": "HTML-Misc" }, { "code": null, "e": 27902, "s": 27898, "text": "CSS" }, { "code": null, "e": 27907, "s": 27902, "text": "HTML" }, { "code": null, "e": 27924, "s": 27907, "text": "Web Technologies" }, { "code": null, "e": 27951, "s": 27924, "text": "Web technologies Questions" }, { "code": null, "e": 27956, "s": 27951, "text": "HTML" }, { "code": null, "e": 28054, "s": 27956, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28093, "s": 28054, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 28130, "s": 28093, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 28159, "s": 28130, "text": "Form validation using jQuery" }, { "code": null, "e": 28194, "s": 28159, "text": "How to style a checkbox using CSS?" }, { "code": null, "e": 28236, "s": 28194, "text": "Search Bar using HTML, CSS and JavaScript" }, { "code": null, "e": 28296, "s": 28236, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 28349, "s": 28296, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 28410, "s": 28349, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 28434, "s": 28410, "text": "REST API (Introduction)" } ]
How to get element-wise true division of an array using Numpy? - GeeksforGeeks
02 Sep, 2020 True Division in Python3 returns a floating result containing the remainder of the division. To get the true division of an array, NumPy library has a function numpy.true_divide(x1, x2). This function gives us the value of true division done on the arrays passed in the function. To get the element-wise division we need to enter the first parameter as an array and the second parameter as a single element. Syntax: np.true_divide(x1,x2) Parameters: x1: The dividend array x2: divisor (can be an array or an element) Return: If inputs are scalar then scalar; otherwise array with arr1 / arr2(element- wise) i.e. true division Now, let’s see an example: Example 1: Python3 # import libraryimport numpy as np # create 1d-arrayx = np.arange(5) print("Original array:", x) # apply true division # on each array elementrslt = np.true_divide(x, 4) print("After the element-wise division:", rslt) Output : Original array: [0 1 2 3 4] After the element-wise division: [0. 0.25 0.5 0.75 1. ] Example 2: Python3 # import libraryimport numpy as np # create a 1d-arrayx = np.arange(10) print("Original array:", x) # apply true division # on each array elementrslt = np.true_divide(x, 3) print("After the element-wise division:", rslt) Output: Original array: [0 1 2 3 4 5 6 7 8 9]After the element-wise division: [0. 0.33333333 0.66666667 1. 1.33333333 1.666666672. 2.33333333 2.66666667 3. ] Python numpy-Mathematical Function Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python | Get unique values from a list Python | os.path.join() method Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n02 Sep, 2020" }, { "code": null, "e": 25945, "s": 25537, "text": "True Division in Python3 returns a floating result containing the remainder of the division. To get the true division of an array, NumPy library has a function numpy.true_divide(x1, x2). This function gives us the value of true division done on the arrays passed in the function. To get the element-wise division we need to enter the first parameter as an array and the second parameter as a single element." }, { "code": null, "e": 25987, "s": 25945, "text": "Syntax: np.true_divide(x1,x2) Parameters:" }, { "code": null, "e": 26010, "s": 25987, "text": "x1: The dividend array" }, { "code": null, "e": 26054, "s": 26010, "text": "x2: divisor (can be an array or an element)" }, { "code": null, "e": 26163, "s": 26054, "text": "Return: If inputs are scalar then scalar; otherwise array with arr1 / arr2(element- wise) i.e. true division" }, { "code": null, "e": 26190, "s": 26163, "text": "Now, let’s see an example:" }, { "code": null, "e": 26202, "s": 26190, "text": "Example 1: " }, { "code": null, "e": 26210, "s": 26202, "text": "Python3" }, { "code": "# import libraryimport numpy as np # create 1d-arrayx = np.arange(5) print(\"Original array:\", x) # apply true division # on each array elementrslt = np.true_divide(x, 4) print(\"After the element-wise division:\", rslt)", "e": 26444, "s": 26210, "text": null }, { "code": null, "e": 26453, "s": 26444, "text": "Output :" }, { "code": null, "e": 26541, "s": 26453, "text": "Original array: [0 1 2 3 4]\nAfter the element-wise division: [0. 0.25 0.5 0.75 1. ]" }, { "code": null, "e": 26553, "s": 26541, "text": "Example 2: " }, { "code": null, "e": 26561, "s": 26553, "text": "Python3" }, { "code": "# import libraryimport numpy as np # create a 1d-arrayx = np.arange(10) print(\"Original array:\", x) # apply true division # on each array elementrslt = np.true_divide(x, 3) print(\"After the element-wise division:\", rslt)", "e": 26797, "s": 26561, "text": null }, { "code": null, "e": 26805, "s": 26797, "text": "Output:" }, { "code": null, "e": 26955, "s": 26805, "text": "Original array: [0 1 2 3 4 5 6 7 8 9]After the element-wise division: [0. 0.33333333 0.66666667 1. 1.33333333 1.666666672. 2.33333333 2.66666667 3. ]" }, { "code": null, "e": 26990, "s": 26955, "text": "Python numpy-Mathematical Function" }, { "code": null, "e": 27003, "s": 26990, "text": "Python-numpy" }, { "code": null, "e": 27010, "s": 27003, "text": "Python" }, { "code": null, "e": 27108, "s": 27010, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27140, "s": 27108, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27182, "s": 27140, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27224, "s": 27182, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27251, "s": 27224, "text": "Python Classes and Objects" }, { "code": null, "e": 27307, "s": 27251, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27329, "s": 27307, "text": "Defaultdict in Python" }, { "code": null, "e": 27368, "s": 27329, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27399, "s": 27368, "text": "Python | os.path.join() method" }, { "code": null, "e": 27428, "s": 27399, "text": "Create a directory in Python" } ]
Java.Lang.Long class in Java - GeeksforGeeks
20 Apr, 2022 Long class is a wrapper class for the primitive type long which contains several methods to effectively deal with a long value like converting it to a string representation, and vice-versa. An object of Long class can hold a single long value. There are mainly two constructors to initialize a Long object- Long(long b): Creates a Long object initialized with the value provided. Syntax : public Long(long b) Parameters : b : value with which to initialize Long(String s): Creates a Long object initialized with the long value provided by string representation. Default radix is taken to be 10. Syntax : public Long(String s) throws NumberFormatException Parameters : s : string representation of the long value Throws : NumberFormatException : If the string provided does not represent any long value. Methods: 1. toString(): Returns the string corresponding to the long value. Syntax : public String toString(long b) Parameters : b : long value for which string representation required. 2. toHexString() : Returns the string corresponding to the long value in hexadecimal form, that is it returns a string representing the long value in hex characters-[0-9][a-f] Syntax : public String toHexString(long b) Parameters : b : long value for which hex string representation required. 3. toOctalString() : Returns the string corresponding to the long value in octal form, that is it returns a string representing the long value in octal characters-[0-7] Syntax : public String toOctalString(long b) Parameters : b : long value for which octal string representation required. 4. toBinaryString() : Returns the string corresponding to the long value in binary digits, that is it returns a string representing the long value in hex characters-[0/1] Syntax : public String toBinaryString(long b) Parameters : b : long value for which binary string representation required. 5. valueOf() : returns the Long object initialized with the value provided. Syntax : public static Long valueOf(long b) Parameters : b : a long value Another overloaded function valueOf(String val,long radix) which provides function similar to new Long(Long.parseLong(val,radix)) Syntax : public static Long valueOf(String val, long radix) throws NumberFormatException Parameters : val : String to be parsed into long value radix : radix to be used while parsing Throws : NumberFormatException : if String cannot be parsed to a long value in given radix. Another overloaded function valueOf(String val) which provides function similar to new Long(Long.parseInt(val,10)) Syntax : public static Long valueOf(String s) throws NumberFormatException Parameters : s : a String object to be parsed as long Throws : NumberFormatException : if String cannot be parsed to a long value in given radix. 6. parseLong() : returns long value by parsing the string in radix provided. Differs from valueOf() as it returns a primitive long value and valueOf() return Long object. Syntax : public static long parseInt(String val, int radix) throws NumberFormatException Parameters : val : String representation of long radix : radix to be used while parsing Throws : NumberFormatException : if String cannot be parsed to a long value in given radix. Another overloaded method containing only String as a parameter, radix is by default set to 10. Syntax : public static long parseLong(String val) throws NumberFormatException Parameters : val : String representation of long Throws : NumberFormatException : if String cannot be parsed to a long value in given radix. 7. getLong() : returns the Long object representing the value associated with the given system property or null if it does not exist. Syntax : public static Long getLong(String prop) Parameters : prop : System property Another overloaded method which returns the second argument if the property does not exist, that is it does not return null but a default value supplied by user. Syntax : public static Long getLong(String prop, long val) Parameters : prop : System property val : value to return if property does not exist. Another overloaded method which parses the value according to the value returned, that is if the value returned starts with “#”, than it is parsed as hexadecimal, if starts with “0”, than it is parsed as octal, else decimal. Syntax : public static Long getLong(String prop, Long val) Parameters : prop : System property val : value to return if property does not exist. 8. decode() : returns a Long object holding the decoded value of string provided. String provided must be of the following form else NumberFormatException will be thrown- Decimal- (Sign)Decimal_Number Hex- (Sign)”0x”Hex_Digits Hex- (Sign)”0X”Hex_Digits Octal- (Sign)”0′′Octal_Digits Syntax : public static Long decode(String s) throws NumberFormatException Parameters : s : encoded string to be parsed into long val Throws : NumberFormatException : If the string cannot be decoded into a long value 9. rotateLeft() : Returns a primitive long by rotating the bits left by given distance in two’s complement form of the value given. When rotating left, the most significant bit is moved to the right hand side, or least significant position i.e. cyclic movement of bits takes place. Negative distance signifies right rotation. Syntax : public static long rotateLeft(long val, int dist) Parameters : val : long value to be rotated dist : distance to rotate 10. rotateRight() : Returns a primitive long by rotating the bits right by given distance in the twos complement form of the value given. When rotating right, the least significant bit is moved to the left hand side, or most significant position i.e. cyclic movement of bits takes place. Negative distance signifies left rotation. Syntax : public static long rotateRight(long val, int dist) Parameters : val : long value to be rotated dist : distance to rotate Java // Java program to illustrate// various Long class methodspublic class Long_test{ public static void main(String args[]) { long b = 55; String bb = "45"; // Construct two Long objects Long x = new Long(b); Long y = new Long(bb); // toString() System.out.println("toString(b) = " + Long.toString(b)); // toHexString(),toOctalString(),toBinaryString() // converts into hexadecimal, octal and binary forms. System.out.println("toHexString(b) =" + Long.toHexString(b)); System.out.println("toOctalString(b) =" + Long.toOctalString(b)); System.out.println("toBinaryString(b) =" + Long.toBinaryString(b)); // valueOf(): return Long object // an overloaded method takes radix as well. Long z = Long.valueOf(b); System.out.println("valueOf(b) = " + z); z = Long.valueOf(bb); System.out.println("ValueOf(bb) = " + z); z = Long.valueOf(bb, 6); System.out.println("ValueOf(bb,6) = " + z); // parseLong(): return primitive long value // an overloaded method takes radix as well long zz = Long.parseLong(bb); System.out.println("parseLong(bb) = " + zz); zz = Long.parseLong(bb, 6); System.out.println("parseLong(bb,6) = " + zz); // getLong(): can be used to retrieve // long value of system property long prop = Long.getLong("sun.arch.data.model"); System.out.println("getLong(sun.arch.data.model) = " + prop); System.out.println("getLong(abcd) =" + Long.getLong("abcd")); // an overloaded getLong() method // which return default value if property not found. System.out.println("getLong(abcd,10) =" + Long.getLong("abcd", 10)); // decode() : decodes the hex,octal and decimal // string to corresponding long values. String decimal = "45"; String octal = "005"; String hex = "0x0f"; Long dec = Long.decode(decimal); System.out.println("decode(45) = " + dec); dec = Long.decode(octal); System.out.println("decode(005) = " + dec); dec = Long.decode(hex); System.out.println("decode(0x0f) = " + dec); // rotateLeft and rotateRight can be used // to rotate bits by specified distance long valrot = 2; System.out.println("rotateLeft(0000 0000 0000 0010 , 2) =" + Long.rotateLeft(valrot, 2)); System.out.println("rotateRight(0000 0000 0000 0010,3) =" + Long.rotateRight(valrot, 3)); }} Output: toString(b) = 55 toHexString(b) =37 toOctalString(b) =67 toBinaryString(b) =110111 valueOf(b) = 55 ValueOf(bb) = 45 ValueOf(bb,6) = 29 parseInt(bb) = 45 parseInt(bb,6) = 29 getLong(sun.arch.data.model) = 64 getLong(abcd) =null getLong(abcd,10) =10 decode(45) = 45 decode(005) = 5 decode(0x0f) = 15 rotateLeft(0000 0000 0000 0010 , 2) =8 rotateRight(0000 0000 0000 0010,3) =1073741824 Some more Long class methods are – 11. byteValue() : returns a byte value corresponding to this Long Object. Syntax : public byte byteValue() 12. shortValue() : returns a short value corresponding to this Long Object. Syntax : public short shortValue() 13. intValue() : returns a int value corresponding to this Long Object. Syntax : public int intValue() 14. longValue() : returns a long value corresponding to this Long Object. Syntax : public long longValue() 15. doubleValue() : returns a double value corresponding to this Long Object. Syntax : public double doubleValue() 16. floatValue() : returns a float value corresponding to this Long Object. Syntax : public float floatValue() 17. hashCode() : returns the hashcode corresponding to this Long Object. Syntax : public int hashCode() 18. bitcount() : Returns number of set bits in twos complement of the long given. Syntax : public static int bitCount(long i) Parameters : i : long value whose set bits to count 19. numberOfLeadingZeroes() : Returns number of 0 bits preceding the highest 1 bit in twos complement form of the value, i.e. if the number in twos complement form is 0000 1010 0000 0000, then this function would return 4. Syntax : public static int numberofLeadingZeroes(long i) Parameters : i : long value whose leading zeroes to count in twos complement form 20. numberOfTrailingZeroes() : Returns number of 0 bits following the last 1 bit in twos complement form of the value, i.e. if the number in twos complement form is 0000 1010 0000 0000, then this function would return 9. Syntax : public static int numberofTrailingZeroes(long i) Parameters : i : long value whose trailing zeroes to count in twos complement form 21. highestOneBit() : Returns a value with at most a single one bit, in the position of highest one bit in the value given. Returns 0 if the value given is 0, that is if the number is 0000 0000 0000 1111, than this function return 0000 0000 0000 1000 (one at highest one bit in the given number) Syntax : public static long highestOneBit(long i) Parameters : i : long value 22. LowestOneBit() : Returns a value with at most a single one bit, in the position of lowest one bit in the value given. Returns 0 if the value given is 0, that is if the number is 0000 0000 0000 1111, than this function return 0000 0000 0000 0001 (one at highest one bit in the given number) Syntax : public static long LowestOneBit(long i) Parameters : i : long value 23. equals() : Used to compare the equality of two Long objects. This methods returns true if both the objects contains same long value. Should be used only if checking for equality. In all other cases compareTo method should be preferred. Syntax : public boolean equals(Object obj) Parameters : obj : object to compare with 24. compareTo() : Used to compare two Long objects for numerical equality. This should be used when comparing two Long values for numerical equality as it would differentiate between less and greater values. Returns a value less than 0,0,value greater than 0 for less than,equal to and greater than. Syntax : public int compareTo(Long b) Parameters : b : Long object to compare with 25. compare() : Used to compare two primitive long values for numerical equality. As it is a static method therefore it can be used without creating any object of Long. Syntax : public static int compare(long x,long y) Parameters : x : long value y : another long value 26. signum() : returns -1 for negative values, 0 for 0 and +1 for values greater than 0. Syntax : public static int signum(long val) Parameters : val : long value for which signum is required. 27. reverse() : returns a primitive long value reversing the order of bits in two’s complement form of the given long value. Syntax : public static long reverseBytes(long val) Parameters : val : long value whose bits to reverse in order. 28. reverseBytes() : returns a primitive long value reversing the order of bytes in two’s complement form of the given long value. Syntax : public static long reverseBytes(long val) Parameters : val : long value whose bits to reverse in order. Java // Java program to illustrate// various Long methodspublic class Long_test{ public static void main(String args[]) { long b = 55; String bb = "45"; // Construct two Long objects Long x = new Long(b); Long y = new Long(bb); // xxxValue can be used to retrieve // xxx type value from long value. // xxx can be int,byte,short,long,double,float System.out.println("bytevalue(x) = " + x.byteValue()); System.out.println("shortvalue(x) = " + x.shortValue()); System.out.println("intvalue(x) = " + x.intValue()); System.out.println("longvalue(x) = " + x.longValue()); System.out.println("doublevalue(x) = " + x.doubleValue()); System.out.println("floatvalue(x) = " + x.floatValue()); long value = 45; // bitcount() : can be used to count set bits // in twos complement form of the number System.out.println("Long.bitcount(value)=" + Long.bitCount(value)); // numberOfTrailingZeroes and numberOfLeaadingZeroes // can be used to count prefix and postfix sequence of 0 System.out.println("Long.numberOfTrailingZeros(value)=" + Long.numberOfTrailingZeros(value)); System.out.println("Long.numberOfLeadingZeros(value)=" + Long.numberOfLeadingZeros(value)); // highestOneBit returns a value with one on highest // set bit position System.out.println("Long.highestOneBit(value)=" + Long.highestOneBit(value)); // highestOneBit returns a value with one on lowest // set bit position System.out.println("Long.lowestOneBit(value)=" + Long.lowestOneBit(value)); // reverse() can be used to reverse order of bits // reverseBytes() can be used to reverse order of bytes System.out.println("Long.reverse(value)=" + Long.reverse(value)); System.out.println("Long.reverseBytes(value)=" + Long.reverseBytes(value)); // signum() returns -1,0,1 for negative,0 and positive // values System.out.println("Long.signum(value)=" + Long.signum(value)); // hashcode() returns hashcode of the object int hash = x.hashCode(); System.out.println("hashcode(x) = " + hash); // equals returns boolean value representing equality boolean eq = x.equals(y); System.out.println("x.equals(y) = " + eq); // compare() used for comparing two int values int e = Long.compare(x, y); System.out.println("compare(x,y) = " + e); // compareTo() used for comparing this value with some // other value int f = x.compareTo(y); System.out.println("x.compareTo(y) = " + f); }} Output : bytevalue(x) = 55 shortvalue(x) = 55 intvalue(x) = 55 longvalue(x) = 55 doublevalue(x) = 55.0 floatvalue(x) = 55.0 Long.bitcount(value)=4 Long.numberOfTrailingZeros(value)=0 Long.numberOfLeadingZeros(value)=58 Long.highestOneBit(value)=32 Long.lowestOneBit(value)=1 Long.reverse(value)=-5476377146882523136 Long.reverseBytes(value)=3242591731706757120 Long.signum(value)=1 hashcode(x) = 55 x.equals(y) = false compare(x,y) = 1 x.compareTo(y) = 1 This article is contributed by Rishabh Mahrsee. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Akanksha_Rai abhishek0719kadiyan sumitgumber28 simmytarika5 Java-lang package java-Long java-wrapper-class Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Arrays in Java Split() String method in Java with examples For-each loop in Java Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples Reverse a string in Java Arrays.sort() in Java with examples Stream In Java Interfaces in Java How to iterate any Map in Java
[ { "code": null, "e": 24283, "s": 24255, "text": "\n20 Apr, 2022" }, { "code": null, "e": 24591, "s": 24283, "text": "Long class is a wrapper class for the primitive type long which contains several methods to effectively deal with a long value like converting it to a string representation, and vice-versa. An object of Long class can hold a single long value. There are mainly two constructors to initialize a Long object- " }, { "code": null, "e": 24664, "s": 24591, "text": "Long(long b): Creates a Long object initialized with the value provided." }, { "code": null, "e": 24741, "s": 24664, "text": "Syntax : public Long(long b)\nParameters :\nb : value with which to initialize" }, { "code": null, "e": 24879, "s": 24741, "text": "Long(String s): Creates a Long object initialized with the long value provided by string representation. Default radix is taken to be 10." }, { "code": null, "e": 25109, "s": 24879, "text": "Syntax : public Long(String s) \n throws NumberFormatException\nParameters :\ns : string representation of the long value \nThrows :\nNumberFormatException : If the string provided does not represent any long value." }, { "code": null, "e": 25120, "s": 25109, "text": "Methods: " }, { "code": null, "e": 25188, "s": 25120, "text": "1. toString(): Returns the string corresponding to the long value. " }, { "code": null, "e": 25298, "s": 25188, "text": "Syntax : public String toString(long b)\nParameters :\nb : long value for which string representation required." }, { "code": null, "e": 25474, "s": 25298, "text": "2. toHexString() : Returns the string corresponding to the long value in hexadecimal form, that is it returns a string representing the long value in hex characters-[0-9][a-f]" }, { "code": null, "e": 25591, "s": 25474, "text": "Syntax : public String toHexString(long b)\nParameters :\nb : long value for which hex string representation required." }, { "code": null, "e": 25761, "s": 25591, "text": "3. toOctalString() : Returns the string corresponding to the long value in octal form, that is it returns a string representing the long value in octal characters-[0-7] " }, { "code": null, "e": 25882, "s": 25761, "text": "Syntax : public String toOctalString(long b)\nParameters :\nb : long value for which octal string representation required." }, { "code": null, "e": 26055, "s": 25882, "text": "4. toBinaryString() : Returns the string corresponding to the long value in binary digits, that is it returns a string representing the long value in hex characters-[0/1] " }, { "code": null, "e": 26178, "s": 26055, "text": "Syntax : public String toBinaryString(long b)\nParameters :\nb : long value for which binary string representation required." }, { "code": null, "e": 26255, "s": 26178, "text": "5. valueOf() : returns the Long object initialized with the value provided. " }, { "code": null, "e": 26329, "s": 26255, "text": "Syntax : public static Long valueOf(long b)\nParameters :\nb : a long value" }, { "code": null, "e": 26460, "s": 26329, "text": "Another overloaded function valueOf(String val,long radix) which provides function similar to new Long(Long.parseLong(val,radix)) " }, { "code": null, "e": 26747, "s": 26460, "text": "Syntax : public static Long valueOf(String val, long radix)\n throws NumberFormatException\nParameters :\nval : String to be parsed into long value\nradix : radix to be used while parsing\nThrows :\nNumberFormatException : if String cannot be parsed to a long value in given radix." }, { "code": null, "e": 26863, "s": 26747, "text": "Another overloaded function valueOf(String val) which provides function similar to new Long(Long.parseInt(val,10)) " }, { "code": null, "e": 27095, "s": 26863, "text": "Syntax : public static Long valueOf(String s)\n throws NumberFormatException\nParameters :\ns : a String object to be parsed as long\nThrows :\nNumberFormatException : if String cannot be parsed to a long value in given radix." }, { "code": null, "e": 27267, "s": 27095, "text": "6. parseLong() : returns long value by parsing the string in radix provided. Differs from valueOf() as it returns a primitive long value and valueOf() return Long object. " }, { "code": null, "e": 27550, "s": 27267, "text": "Syntax : public static long parseInt(String val, int radix)\n throws NumberFormatException\nParameters :\nval : String representation of long \nradix : radix to be used while parsing\nThrows :\nNumberFormatException : if String cannot be parsed to a long value in given radix." }, { "code": null, "e": 27647, "s": 27550, "text": "Another overloaded method containing only String as a parameter, radix is by default set to 10. " }, { "code": null, "e": 27881, "s": 27647, "text": "Syntax : public static long parseLong(String val)\n throws NumberFormatException\nParameters :\nval : String representation of long \nThrows :\nNumberFormatException : if String cannot be parsed to a long value in given radix." }, { "code": null, "e": 28016, "s": 27881, "text": "7. getLong() : returns the Long object representing the value associated with the given system property or null if it does not exist. " }, { "code": null, "e": 28101, "s": 28016, "text": "Syntax : public static Long getLong(String prop)\nParameters :\nprop : System property" }, { "code": null, "e": 28264, "s": 28101, "text": "Another overloaded method which returns the second argument if the property does not exist, that is it does not return null but a default value supplied by user. " }, { "code": null, "e": 28409, "s": 28264, "text": "Syntax : public static Long getLong(String prop, long val)\nParameters :\nprop : System property\nval : value to return if property does not exist." }, { "code": null, "e": 28635, "s": 28409, "text": "Another overloaded method which parses the value according to the value returned, that is if the value returned starts with “#”, than it is parsed as hexadecimal, if starts with “0”, than it is parsed as octal, else decimal. " }, { "code": null, "e": 28780, "s": 28635, "text": "Syntax : public static Long getLong(String prop, Long val)\nParameters :\nprop : System property\nval : value to return if property does not exist." }, { "code": null, "e": 29064, "s": 28780, "text": "8. decode() : returns a Long object holding the decoded value of string provided. String provided must be of the following form else NumberFormatException will be thrown- Decimal- (Sign)Decimal_Number Hex- (Sign)”0x”Hex_Digits Hex- (Sign)”0X”Hex_Digits Octal- (Sign)”0′′Octal_Digits " }, { "code": null, "e": 29293, "s": 29064, "text": "Syntax : public static Long decode(String s)\n throws NumberFormatException\nParameters :\ns : encoded string to be parsed into long val\nThrows :\nNumberFormatException : If the string cannot be decoded into a long value" }, { "code": null, "e": 29620, "s": 29293, "text": "9. rotateLeft() : Returns a primitive long by rotating the bits left by given distance in two’s complement form of the value given. When rotating left, the most significant bit is moved to the right hand side, or least significant position i.e. cyclic movement of bits takes place. Negative distance signifies right rotation. " }, { "code": null, "e": 29749, "s": 29620, "text": "Syntax : public static long rotateLeft(long val, int dist)\nParameters :\nval : long value to be rotated\ndist : distance to rotate" }, { "code": null, "e": 30081, "s": 29749, "text": "10. rotateRight() : Returns a primitive long by rotating the bits right by given distance in the twos complement form of the value given. When rotating right, the least significant bit is moved to the left hand side, or most significant position i.e. cyclic movement of bits takes place. Negative distance signifies left rotation. " }, { "code": null, "e": 30211, "s": 30081, "text": "Syntax : public static long rotateRight(long val, int dist)\nParameters :\nval : long value to be rotated\ndist : distance to rotate" }, { "code": null, "e": 30216, "s": 30211, "text": "Java" }, { "code": "// Java program to illustrate// various Long class methodspublic class Long_test{ public static void main(String args[]) { long b = 55; String bb = \"45\"; // Construct two Long objects Long x = new Long(b); Long y = new Long(bb); // toString() System.out.println(\"toString(b) = \" + Long.toString(b)); // toHexString(),toOctalString(),toBinaryString() // converts into hexadecimal, octal and binary forms. System.out.println(\"toHexString(b) =\" + Long.toHexString(b)); System.out.println(\"toOctalString(b) =\" + Long.toOctalString(b)); System.out.println(\"toBinaryString(b) =\" + Long.toBinaryString(b)); // valueOf(): return Long object // an overloaded method takes radix as well. Long z = Long.valueOf(b); System.out.println(\"valueOf(b) = \" + z); z = Long.valueOf(bb); System.out.println(\"ValueOf(bb) = \" + z); z = Long.valueOf(bb, 6); System.out.println(\"ValueOf(bb,6) = \" + z); // parseLong(): return primitive long value // an overloaded method takes radix as well long zz = Long.parseLong(bb); System.out.println(\"parseLong(bb) = \" + zz); zz = Long.parseLong(bb, 6); System.out.println(\"parseLong(bb,6) = \" + zz); // getLong(): can be used to retrieve // long value of system property long prop = Long.getLong(\"sun.arch.data.model\"); System.out.println(\"getLong(sun.arch.data.model) = \" + prop); System.out.println(\"getLong(abcd) =\" + Long.getLong(\"abcd\")); // an overloaded getLong() method // which return default value if property not found. System.out.println(\"getLong(abcd,10) =\" + Long.getLong(\"abcd\", 10)); // decode() : decodes the hex,octal and decimal // string to corresponding long values. String decimal = \"45\"; String octal = \"005\"; String hex = \"0x0f\"; Long dec = Long.decode(decimal); System.out.println(\"decode(45) = \" + dec); dec = Long.decode(octal); System.out.println(\"decode(005) = \" + dec); dec = Long.decode(hex); System.out.println(\"decode(0x0f) = \" + dec); // rotateLeft and rotateRight can be used // to rotate bits by specified distance long valrot = 2; System.out.println(\"rotateLeft(0000 0000 0000 0010 , 2) =\" + Long.rotateLeft(valrot, 2)); System.out.println(\"rotateRight(0000 0000 0000 0010,3) =\" + Long.rotateRight(valrot, 3)); }}", "e": 32830, "s": 30216, "text": null }, { "code": null, "e": 32838, "s": 32830, "text": "Output:" }, { "code": null, "e": 33222, "s": 32838, "text": "toString(b) = 55\ntoHexString(b) =37\ntoOctalString(b) =67\ntoBinaryString(b) =110111\nvalueOf(b) = 55\nValueOf(bb) = 45\nValueOf(bb,6) = 29\nparseInt(bb) = 45\nparseInt(bb,6) = 29\ngetLong(sun.arch.data.model) = 64\ngetLong(abcd) =null\ngetLong(abcd,10) =10\ndecode(45) = 45\ndecode(005) = 5\ndecode(0x0f) = 15\nrotateLeft(0000 0000 0000 0010 , 2) =8\nrotateRight(0000 0000 0000 0010,3) =1073741824" }, { "code": null, "e": 33257, "s": 33222, "text": "Some more Long class methods are –" }, { "code": null, "e": 33332, "s": 33257, "text": "11. byteValue() : returns a byte value corresponding to this Long Object. " }, { "code": null, "e": 33365, "s": 33332, "text": "Syntax : public byte byteValue()" }, { "code": null, "e": 33442, "s": 33365, "text": "12. shortValue() : returns a short value corresponding to this Long Object. " }, { "code": null, "e": 33477, "s": 33442, "text": "Syntax : public short shortValue()" }, { "code": null, "e": 33550, "s": 33477, "text": "13. intValue() : returns a int value corresponding to this Long Object. " }, { "code": null, "e": 33581, "s": 33550, "text": "Syntax : public int intValue()" }, { "code": null, "e": 33656, "s": 33581, "text": "14. longValue() : returns a long value corresponding to this Long Object. " }, { "code": null, "e": 33689, "s": 33656, "text": "Syntax : public long longValue()" }, { "code": null, "e": 33768, "s": 33689, "text": "15. doubleValue() : returns a double value corresponding to this Long Object. " }, { "code": null, "e": 33805, "s": 33768, "text": "Syntax : public double doubleValue()" }, { "code": null, "e": 33882, "s": 33805, "text": "16. floatValue() : returns a float value corresponding to this Long Object. " }, { "code": null, "e": 33917, "s": 33882, "text": "Syntax : public float floatValue()" }, { "code": null, "e": 33991, "s": 33917, "text": "17. hashCode() : returns the hashcode corresponding to this Long Object. " }, { "code": null, "e": 34022, "s": 33991, "text": "Syntax : public int hashCode()" }, { "code": null, "e": 34105, "s": 34022, "text": "18. bitcount() : Returns number of set bits in twos complement of the long given. " }, { "code": null, "e": 34201, "s": 34105, "text": "Syntax : public static int bitCount(long i)\nParameters :\ni : long value whose set bits to count" }, { "code": null, "e": 34425, "s": 34201, "text": "19. numberOfLeadingZeroes() : Returns number of 0 bits preceding the highest 1 bit in twos complement form of the value, i.e. if the number in twos complement form is 0000 1010 0000 0000, then this function would return 4. " }, { "code": null, "e": 34564, "s": 34425, "text": "Syntax : public static int numberofLeadingZeroes(long i)\nParameters :\ni : long value whose leading zeroes to count in twos complement form" }, { "code": null, "e": 34786, "s": 34564, "text": "20. numberOfTrailingZeroes() : Returns number of 0 bits following the last 1 bit in twos complement form of the value, i.e. if the number in twos complement form is 0000 1010 0000 0000, then this function would return 9. " }, { "code": null, "e": 34927, "s": 34786, "text": "Syntax : public static int numberofTrailingZeroes(long i)\nParameters :\ni : long value whose trailing zeroes to count in twos complement form" }, { "code": null, "e": 35224, "s": 34927, "text": "21. highestOneBit() : Returns a value with at most a single one bit, in the position of highest one bit in the value given. Returns 0 if the value given is 0, that is if the number is 0000 0000 0000 1111, than this function return 0000 0000 0000 1000 (one at highest one bit in the given number) " }, { "code": null, "e": 35303, "s": 35224, "text": "Syntax : public static long highestOneBit(long i)\nParameters :\ni : long value " }, { "code": null, "e": 35598, "s": 35303, "text": "22. LowestOneBit() : Returns a value with at most a single one bit, in the position of lowest one bit in the value given. Returns 0 if the value given is 0, that is if the number is 0000 0000 0000 1111, than this function return 0000 0000 0000 0001 (one at highest one bit in the given number) " }, { "code": null, "e": 35676, "s": 35598, "text": "Syntax : public static long LowestOneBit(long i)\nParameters :\ni : long value " }, { "code": null, "e": 35917, "s": 35676, "text": "23. equals() : Used to compare the equality of two Long objects. This methods returns true if both the objects contains same long value. Should be used only if checking for equality. In all other cases compareTo method should be preferred. " }, { "code": null, "e": 36002, "s": 35917, "text": "Syntax : public boolean equals(Object obj)\nParameters :\nobj : object to compare with" }, { "code": null, "e": 36303, "s": 36002, "text": "24. compareTo() : Used to compare two Long objects for numerical equality. This should be used when comparing two Long values for numerical equality as it would differentiate between less and greater values. Returns a value less than 0,0,value greater than 0 for less than,equal to and greater than. " }, { "code": null, "e": 36386, "s": 36303, "text": "Syntax : public int compareTo(Long b)\nParameters :\nb : Long object to compare with" }, { "code": null, "e": 36556, "s": 36386, "text": "25. compare() : Used to compare two primitive long values for numerical equality. As it is a static method therefore it can be used without creating any object of Long. " }, { "code": null, "e": 36657, "s": 36556, "text": "Syntax : public static int compare(long x,long y)\nParameters :\nx : long value\ny : another long value" }, { "code": null, "e": 36747, "s": 36657, "text": "26. signum() : returns -1 for negative values, 0 for 0 and +1 for values greater than 0. " }, { "code": null, "e": 36851, "s": 36747, "text": "Syntax : public static int signum(long val)\nParameters :\nval : long value for which signum is required." }, { "code": null, "e": 36977, "s": 36851, "text": "27. reverse() : returns a primitive long value reversing the order of bits in two’s complement form of the given long value. " }, { "code": null, "e": 37090, "s": 36977, "text": "Syntax : public static long reverseBytes(long val)\nParameters :\nval : long value whose bits to reverse in order." }, { "code": null, "e": 37222, "s": 37090, "text": "28. reverseBytes() : returns a primitive long value reversing the order of bytes in two’s complement form of the given long value. " }, { "code": null, "e": 37335, "s": 37222, "text": "Syntax : public static long reverseBytes(long val)\nParameters :\nval : long value whose bits to reverse in order." }, { "code": null, "e": 37340, "s": 37335, "text": "Java" }, { "code": "// Java program to illustrate// various Long methodspublic class Long_test{ public static void main(String args[]) { long b = 55; String bb = \"45\"; // Construct two Long objects Long x = new Long(b); Long y = new Long(bb); // xxxValue can be used to retrieve // xxx type value from long value. // xxx can be int,byte,short,long,double,float System.out.println(\"bytevalue(x) = \" + x.byteValue()); System.out.println(\"shortvalue(x) = \" + x.shortValue()); System.out.println(\"intvalue(x) = \" + x.intValue()); System.out.println(\"longvalue(x) = \" + x.longValue()); System.out.println(\"doublevalue(x) = \" + x.doubleValue()); System.out.println(\"floatvalue(x) = \" + x.floatValue()); long value = 45; // bitcount() : can be used to count set bits // in twos complement form of the number System.out.println(\"Long.bitcount(value)=\" + Long.bitCount(value)); // numberOfTrailingZeroes and numberOfLeaadingZeroes // can be used to count prefix and postfix sequence of 0 System.out.println(\"Long.numberOfTrailingZeros(value)=\" + Long.numberOfTrailingZeros(value)); System.out.println(\"Long.numberOfLeadingZeros(value)=\" + Long.numberOfLeadingZeros(value)); // highestOneBit returns a value with one on highest // set bit position System.out.println(\"Long.highestOneBit(value)=\" + Long.highestOneBit(value)); // highestOneBit returns a value with one on lowest // set bit position System.out.println(\"Long.lowestOneBit(value)=\" + Long.lowestOneBit(value)); // reverse() can be used to reverse order of bits // reverseBytes() can be used to reverse order of bytes System.out.println(\"Long.reverse(value)=\" + Long.reverse(value)); System.out.println(\"Long.reverseBytes(value)=\" + Long.reverseBytes(value)); // signum() returns -1,0,1 for negative,0 and positive // values System.out.println(\"Long.signum(value)=\" + Long.signum(value)); // hashcode() returns hashcode of the object int hash = x.hashCode(); System.out.println(\"hashcode(x) = \" + hash); // equals returns boolean value representing equality boolean eq = x.equals(y); System.out.println(\"x.equals(y) = \" + eq); // compare() used for comparing two int values int e = Long.compare(x, y); System.out.println(\"compare(x,y) = \" + e); // compareTo() used for comparing this value with some // other value int f = x.compareTo(y); System.out.println(\"x.compareTo(y) = \" + f); }}", "e": 40235, "s": 37340, "text": null }, { "code": null, "e": 40245, "s": 40235, "text": "Output : " }, { "code": null, "e": 40691, "s": 40245, "text": "bytevalue(x) = 55\nshortvalue(x) = 55\nintvalue(x) = 55\nlongvalue(x) = 55\ndoublevalue(x) = 55.0\nfloatvalue(x) = 55.0\nLong.bitcount(value)=4\nLong.numberOfTrailingZeros(value)=0\nLong.numberOfLeadingZeros(value)=58\nLong.highestOneBit(value)=32\nLong.lowestOneBit(value)=1\nLong.reverse(value)=-5476377146882523136\nLong.reverseBytes(value)=3242591731706757120\nLong.signum(value)=1\nhashcode(x) = 55\nx.equals(y) = false\ncompare(x,y) = 1\nx.compareTo(y) = 1" }, { "code": null, "e": 41115, "s": 40691, "text": "This article is contributed by Rishabh Mahrsee. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 41128, "s": 41115, "text": "Akanksha_Rai" }, { "code": null, "e": 41148, "s": 41128, "text": "abhishek0719kadiyan" }, { "code": null, "e": 41162, "s": 41148, "text": "sumitgumber28" }, { "code": null, "e": 41175, "s": 41162, "text": "simmytarika5" }, { "code": null, "e": 41193, "s": 41175, "text": "Java-lang package" }, { "code": null, "e": 41203, "s": 41193, "text": "java-Long" }, { "code": null, "e": 41222, "s": 41203, "text": "java-wrapper-class" }, { "code": null, "e": 41227, "s": 41222, "text": "Java" }, { "code": null, "e": 41232, "s": 41227, "text": "Java" }, { "code": null, "e": 41330, "s": 41232, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 41345, "s": 41330, "text": "Arrays in Java" }, { "code": null, "e": 41389, "s": 41345, "text": "Split() String method in Java with examples" }, { "code": null, "e": 41411, "s": 41389, "text": "For-each loop in Java" }, { "code": null, "e": 41462, "s": 41411, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 41492, "s": 41462, "text": "HashMap in Java with Examples" }, { "code": null, "e": 41517, "s": 41492, "text": "Reverse a string in Java" }, { "code": null, "e": 41553, "s": 41517, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 41568, "s": 41553, "text": "Stream In Java" }, { "code": null, "e": 41587, "s": 41568, "text": "Interfaces in Java" } ]
Building K-pop Idol Identifier with Amazon Rekognition | by Ricky Kim | Towards Data Science
Building a data science model from scratch is quite a big job. There are many elements that make up a single model, many steps involved, and many iterations needed to create a decent model. Even though going through these steps will definitely help you to have a deeper understanding of the algorithm being used in the model, sometimes you just don’t have enough time to go through all the trials and errors especially when you have a tight deadline to meet. Image recognition is a field in machine learning that has been intensively explored by many tech giants such as Google, Amazon, Microsoft. Among all the features of image processing, probably what’s most being discussed is facial recognition. There are lots of debates on ethical aspects of the technology, but that is beyond the scope of this post. I will simply share what I have tried with Amazon Rekognition, and hope you can get something out of this post. The urge to write this post started when I played around with Amazon Rekognition demo on their web interface. It provides many useful services like “object and scene detection”, “facial recognition”, “facial analysis”, and “celebrity recognition”. I tried with a few pictures, and everything ran smoothly until I got to “celebrity recognition”. Celebrity recognition first seemed to work fine until I tried with K-pop celebrities’ pictures. The performance of the recognition significantly dropped with K-pop celebrities. Sometimes it gives me the right answer, sometimes it cannot recognise, sometimes it gives me the wrong name. By the way, the above picture is Tzuyu from a group called Twice, which is my favourite K-pop girl group, and I cannot accept that Amazon recognises this picture as Seolhyun (who’s a member of another group called AOA). So I decided to write a simple Python script using Amazon Rekognition which can accurately detect the members of Twice. In addition to short code blocks you can find in the post, I will attach the link for the whole Jupyter Notebook at the end of this post. This post is based on the tutorial “Build Your Own Face Recognition Service Using Amazon Rekognition”, but modified from the original code to fit the specific purpose of the project. There are a few prerequisites in order for you to run below steps in your Jupyter Notebook. Amazon AWS accountAWS credentials configured with AWS CLIThe latest version of Boto3 Amazon AWS account AWS credentials configured with AWS CLI The latest version of Boto3 Let’s first start by importing some packages that will be directly used for the next step. import boto3from PIL import Image%matplotlib inline Now we need to have an image that we want to process. I chose the same image that I tried with the above web interface demo, and we will send this image to Rekognition API to get the result of its image recognition. (The image can also be found in the Github link that I will share at the end of this post.) Let’s take a quick look at the image. display(Image.open('Tzuyu.jpeg')) The most basic task we can ask Rekognition is facial recognition with the given image, and this can be done with just a few lines of codes. import iorekognition = boto3.client('rekognition')image = Image.open("Tzuyu.jpeg")stream = io.BytesIO()image.save(stream,format="JPEG")image_binary = stream.getvalue()rekognition.detect_faces(Image={'Bytes':image_binary}, Attributes=['ALL']) You can either send the image to Rekogntion as in-memory binary file object directly from your local machine or upload your image to S3 and give your bucket and key details as a parameter when calling rekognition.detect_faces(). In the above example, I am sending the binary object directly from my local machine. The response you will get from the above call will be quite long with all the information you can get from detect_faces function of Rekognition. {'FaceDetails': [{'AgeRange': {'High': 38, 'Low': 20}, 'Beard': {'Confidence': 99.98848724365234, 'Value': False}, 'BoundingBox': {'Height': 0.1584049016237259, 'Left': 0.4546355605125427, 'Top': 0.0878104418516159, 'Width': 0.09999311715364456}, 'Confidence': 100.0, 'Emotions': [{'Confidence': 37.66959762573242, 'Type': 'SURPRISED'}, {'Confidence': 29.646778106689453, 'Type': 'CALM'}, {'Confidence': 3.8459930419921875, 'Type': 'SAD'}, {'Confidence': 3.134934186935425, 'Type': 'DISGUSTED'}, {'Confidence': 2.061260938644409, 'Type': 'HAPPY'}, {'Confidence': 18.516468048095703, 'Type': 'CONFUSED'}, {'Confidence': 5.1249613761901855, 'Type': 'ANGRY'}], 'Eyeglasses': {'Confidence': 99.98339080810547, 'Value': False}, 'EyesOpen': {'Confidence': 99.9864730834961, 'Value': True}, 'Gender': {'Confidence': 99.84709167480469, 'Value': 'Female'}, 'Landmarks': [{'Type': 'eyeLeft', 'X': 0.47338899970054626, 'Y': 0.15436244010925293}, {'Type': 'eyeRight', 'X': 0.5152773261070251, 'Y': 0.1474122554063797}, {'Type': 'mouthLeft', 'X': 0.48312342166900635, 'Y': 0.211111381649971}, {'Type': 'mouthRight', 'X': 0.5174261927604675, 'Y': 0.20560002326965332}, {'Type': 'nose', 'X': 0.4872787892818451, 'Y': 0.1808750480413437}, {'Type': 'leftEyeBrowLeft', 'X': 0.45876359939575195, 'Y': 0.14424000680446625}, {'Type': 'leftEyeBrowRight', 'X': 0.4760720133781433, 'Y': 0.13612663745880127}, {'Type': 'leftEyeBrowUp', 'X': 0.4654795229434967, 'Y': 0.13559915125370026}, {'Type': 'rightEyeBrowLeft', 'X': 0.5008187890052795, 'Y': 0.1317606270313263}, {'Type': 'rightEyeBrowRight', 'X': 0.5342025756835938, 'Y': 0.1317359358072281}, {'Type': 'rightEyeBrowUp', 'X': 0.5151524543762207, 'Y': 0.12679456174373627}, {'Type': 'leftEyeLeft', 'X': 0.4674917757511139, 'Y': 0.15510375797748566}, {'Type': 'leftEyeRight', 'X': 0.4817998707294464, 'Y': 0.15343616902828217}, {'Type': 'leftEyeUp', 'X': 0.47253310680389404, 'Y': 0.1514900177717209}, {'Type': 'leftEyeDown', 'X': 0.47370508313179016, 'Y': 0.15651680529117584}, {'Type': 'rightEyeLeft', 'X': 0.5069678425788879, 'Y': 0.14930757880210876}, {'Type': 'rightEyeRight', 'X': 0.5239912867546082, 'Y': 0.1460886150598526}, {'Type': 'rightEyeUp', 'X': 0.5144344568252563, 'Y': 0.1447771191596985}, {'Type': 'rightEyeDown', 'X': 0.5150220394134521, 'Y': 0.14997448027133942}, {'Type': 'noseLeft', 'X': 0.4858757555484772, 'Y': 0.18927086889743805}, {'Type': 'noseRight', 'X': 0.5023624897003174, 'Y': 0.1855706423521042}, {'Type': 'mouthUp', 'X': 0.4945952594280243, 'Y': 0.2002507448196411}, {'Type': 'mouthDown', 'X': 0.4980264902114868, 'Y': 0.21687346696853638}, {'Type': 'leftPupil', 'X': 0.47338899970054626, 'Y': 0.15436244010925293}, {'Type': 'rightPupil', 'X': 0.5152773261070251, 'Y': 0.1474122554063797}, {'Type': 'upperJawlineLeft', 'X': 0.46607205271720886, 'Y': 0.15965013206005096}, {'Type': 'midJawlineLeft', 'X': 0.47901660203933716, 'Y': 0.21797965466976166}, {'Type': 'chinBottom', 'X': 0.5062429904937744, 'Y': 0.24532964825630188}, {'Type': 'midJawlineRight', 'X': 0.5554487109184265, 'Y': 0.20579127967357635}, {'Type': 'upperJawlineRight', 'X': 0.561174750328064, 'Y': 0.14439250528812408}], 'MouthOpen': {'Confidence': 99.0997543334961, 'Value': True}, 'Mustache': {'Confidence': 99.99714660644531, 'Value': False}, 'Pose': {'Pitch': 1.8594770431518555, 'Roll': -11.335309982299805, 'Yaw': -33.68760681152344}, 'Quality': {'Brightness': 89.57070922851562, 'Sharpness': 86.86019134521484}, 'Smile': {'Confidence': 99.23001861572266, 'Value': False}, 'Sunglasses': {'Confidence': 99.99723815917969, 'Value': False}}], 'ResponseMetadata': {'HTTPHeaders': {'connection': 'keep-alive', 'content-length': '3297', 'content-type': 'application/x-amz-json-1.1', 'date': 'Sun, 19 May 2019 08:45:56 GMT', 'x-amzn-requestid': '824f5dc3-7a12-11e9-a384-dfb84e388b7e'}, 'HTTPStatusCode': 200, 'RequestId': '824f5dc3-7a12-11e9-a384-dfb84e388b7e', 'RetryAttempts': 0}} As you can see from the above example response of the detect_faces call, it has not only bounding box information of the location of the face in the picture but also more advanced features such as emotions, gender, age range, etc. With Amazon Rekognition, you can compare faces in two pictures. For example, if I set a picture of Tzuyu as my source picture, then send a group photo of Twice as my target picture, Rekognition will find the face in the target picture which is the most similar to the source picture. The group photo of Twice I’ll be using is below. It might be difficult even for humans, especially if you’re not Asian (or not a Twice fan). You can take your guess who is Tzuyu in the picture. As a Korean, and at the same time a Twice fan, I know the answer, but let’s see how well Rekognition can find Tzuyu from this picture. sourceFile='Tzuyu.jpeg'targetFile='twice_group.jpg' imageSource=open(sourceFile,'rb')imageTarget=open(targetFile,'rb')response = rekognition.compare_faces(SimilarityThreshold=80, SourceImage={'Bytes': imageSource.read()}, TargetImage={'Bytes': imageTarget.read()})response['FaceMatches'] The response of the above compare_faces will also output information of all the unmatched faces in the group picture, and this can get quite long, so I’m just outputting the match that Rekognition found by specifying response[‘FaceMatches’]. It seems like a matching face has been found from the group photo with the similarity of around 97%. With the bounding box information, let’s check which face that Rekognition is referring to as Tzuyu’s face. By the way, the values in the BoundingBox section are ratios of the overall image size. So, in order to draw box with the values in BoundingBox, you need to calculate the location of the box’s each point by multiplying ratios to the actual image height or width. You can find how it can be done in the below code snippet. from PIL import ImageDrawimage = Image.open("twice_group.jpg")imgWidth,imgHeight = image.size draw = ImageDraw.Draw(image)box = response['FaceMatches'][0]['Face']['BoundingBox']left = imgWidth * box['Left']top = imgHeight * box['Top']width = imgWidth * box['Width']height = imgHeight * box['Height']points = ( (left,top), (left + width, top), (left + width, top + height), (left , top + height), (left, top))draw.line(points, fill='#00d400', width=2)display(image) Yes! Well done, Rekognition! That is Tzuyu indeed! Now we can detect face from a picture, and find the most similar face to the source picture from the target picture. But, these are all one-off call, and we need something more to store the information of each member’s face and their name, so that when we send a new picture of Twice, it can retrieve data and detect each member’s face and display their names. In order to implement this, we need to use what Amazon calls “Storage-Based API Operations”. There are two Amazon-specific terms for this type of operations. The “collection” is a virtual space where Rekognition stores information about detected faces. With a collection, we can “index” faces, which means to detect faces in an image, then store the information in the specified collection. What’s important is that the information Rekognition stores in the collection is not actual images, but feature vectors extracted by Rekognition’s algorithm. Let’s see how we can create a collection and add indexes. collectionId='test-collection'rekognition.create_collection(CollectionId=collectionId) Yes. It is as simple as that. Since this is a new collection we just created, we don’t have any information stored in the collection. But, let’s double check. rekognition.describe_collection(CollectionId=collectionId) In the above response, you can see ‘FaceCount’ is 0. This will change if we index any face and store that information in the collection. Indexing faces is again as simple as one line of code with Rekognition. sourceFile='Tzuyu.jpeg' imageSource=open(sourceFile,'rb')rekognition.index_faces(Image={'Bytes':imageSource.read()},ExternalImageId='Tzuyu',CollectionId=collectionId) From the above code, you can see that I am passing ExternalImageId parameter and give it the value of string “Tzuyu”. Later when we try to recognise Tzuyu from a new picture, Rekognition will search for faces that are matching any of the indexed faces. As you will see later, when indexing a face, Rekognition will give it a unique face ID. But I want to display the name “Tzuyu” when a matching face is found from a new picture. For this purpose, I am using ExternalImageId. Now we if we check our collection, we can see 1 face has been added to the collection. rekognition.describe_collection(CollectionId=collectionId) Now with Tzuyu’s face indexed in our collection, we can send a new unseen picture to Rekognition and find the matching face. But a problem with search_faces_by_image function is that it can only detect one face (the largest in the image). So if we want to send a group picture of Twice and find Tzuyu from there, we will need to do an additional step. Below we will first detect all the faces in the picture by using detect_faces, then with the bounding box information of each face, we will call search_faces_by_image one by one. First let’s detect each face. imageSource=open('twice_group.jpg','rb')resp = rekognition.detect_faces(Image={'Bytes':imageSource.read()})all_faces = resp['FaceDetails']len(all_faces) Rekognition detected 9 faces from the group picture. Good. Now let’s crop each face and call serach_faces_by_image one by one. image = Image.open("twice_group.jpg")image_width,image_height = image.sizefor face in all_faces: box=face['BoundingBox'] x1 = box['Left'] * image_width y1 = box['Top'] * image_height x2 = x1 + box['Width'] * image_width y2 = y1 + box['Height'] * image_height image_crop = image.crop((x1,y1,x2,y2)) stream = io.BytesIO() image_crop.save(stream,format="JPEG") image_crop_binary = stream.getvalue()response = rekognition.search_faces_by_image( CollectionId=collectionId, Image={'Bytes':image_crop_binary} ) print(response) print('-'*100) Among the 9 search_faces_by_image calls we have made, Rekognition has found one face that matches the indexed face in our collection. We only indexed one face of Tzuyu, so what it has found is Tzuyu’s face from the group picture. Let’s display this on the image with the bounding box and the name. For the name part, we will use the ExternalImageId we set when we indexed the face. By the way, from the search_faces_by_image response, ‘FaceMatches’ part is an array, and if there are more than one matches found from the collection, then it will show all the matches. According to Amazon this array is ordered by similarity score with the highest similarity first. We will get the match with the highest score by specifying the first item of the array. from PIL import ImageFontimport ioimage = Image.open("twice_group.jpg")image_width,image_height = image.size for face in all_faces: box=face['BoundingBox'] x1 = box['Left'] * image_width y1 = box['Top'] * image_height x2 = x1 + box['Width'] * image_width y2 = y1 + box['Height'] * image_height image_crop = image.crop((x1,y1,x2,y2)) stream = io.BytesIO() image_crop.save(stream,format="JPEG") image_crop_binary = stream.getvalue()response = rekognition.search_faces_by_image( CollectionId=collectionId, Image={'Bytes':image_crop_binary} ) if len(response['FaceMatches']) > 0: draw = ImageDraw.Draw(image) points = ( (x1,y1), (x2, y1), (x2, y2), (x1 , y2), (x1, y1)) draw.line(points, fill='#00d400', width=2) fnt = ImageFont.truetype('/Library/Fonts/Arial.ttf', 15) draw.text((x1,y2),response['FaceMatches'][0]['Face']['ExternalImageId'], font=fnt, fill=(255, 255, 0)) display(image) Hooray! Again the correct answer! Now let’s expand the project to identify all members from the group picture. In order to do that, we first need to index faces of all members (there are 9 members). I have prepared 4 pictures of each member. I have added multiple pictures of the same person following the logic of Amazon tutorial written by Christian Petters. According to Petters, “adding multiple reference images per person greatly enhances the potential match rate for a person”, which makes intuitive sense. From the Github link I’ll share at the end, you will find all the pictures that are used in this project. collectionId='twice'rekognition.create_collection(CollectionId=collectionId) import ospath = 'Twice'for r, d, f in os.walk(path): for file in f: if file != '.DS_Store': sourceFile = os.path.join(r,file) imageSource=open(sourceFile,'rb') rekognition.index_faces(Image={'Bytes':imageSource.read()},ExternalImageId=file.split('_')[0],CollectionId=collectionId)rekognition.describe_collection(CollectionId=collectionId) OK. It seems like all 36 pictures are indexed in our “twice” collection. Now it’s time to check the final result. Can Rekognition be enhanced to identify each member of Twice? from PIL import ImageFontimage = Image.open("twice_group.jpg")image_width,image_height = image.size for face in all_faces: box=face['BoundingBox'] x1 = box['Left'] * image_width y1 = box['Top'] * image_height x2 = x1 + box['Width'] * image_width y2 = y1 + box['Height'] * image_height image_crop = image.crop((x1,y1,x2,y2)) stream = io.BytesIO() image_crop.save(stream,format="JPEG") image_crop_binary = stream.getvalue()response = rekognition.search_faces_by_image( CollectionId=collectionId, Image={'Bytes':image_crop_binary} ) if len(response['FaceMatches']) > 0: draw = ImageDraw.Draw(image) points = ( (x1,y1), (x2, y1), (x2, y2), (x1 , y2), (x1, y1)) draw.line(points, fill='#00d400', width=2) fnt = ImageFont.truetype('/Library/Fonts/Arial.ttf', 15) draw.text((x1,y2),response['FaceMatches'][0]['Face']['ExternalImageId'], font=fnt, fill=(255, 255, 0))display(image) YES! It can! It identified all the members correctly! Thank you for reading. You can find the Jupyter Notebook and the pictures used for the project from the below link.
[ { "code": null, "e": 631, "s": 172, "text": "Building a data science model from scratch is quite a big job. There are many elements that make up a single model, many steps involved, and many iterations needed to create a decent model. Even though going through these steps will definitely help you to have a deeper understanding of the algorithm being used in the model, sometimes you just don’t have enough time to go through all the trials and errors especially when you have a tight deadline to meet." }, { "code": null, "e": 1093, "s": 631, "text": "Image recognition is a field in machine learning that has been intensively explored by many tech giants such as Google, Amazon, Microsoft. Among all the features of image processing, probably what’s most being discussed is facial recognition. There are lots of debates on ethical aspects of the technology, but that is beyond the scope of this post. I will simply share what I have tried with Amazon Rekognition, and hope you can get something out of this post." }, { "code": null, "e": 1724, "s": 1093, "text": "The urge to write this post started when I played around with Amazon Rekognition demo on their web interface. It provides many useful services like “object and scene detection”, “facial recognition”, “facial analysis”, and “celebrity recognition”. I tried with a few pictures, and everything ran smoothly until I got to “celebrity recognition”. Celebrity recognition first seemed to work fine until I tried with K-pop celebrities’ pictures. The performance of the recognition significantly dropped with K-pop celebrities. Sometimes it gives me the right answer, sometimes it cannot recognise, sometimes it gives me the wrong name." }, { "code": null, "e": 1944, "s": 1724, "text": "By the way, the above picture is Tzuyu from a group called Twice, which is my favourite K-pop girl group, and I cannot accept that Amazon recognises this picture as Seolhyun (who’s a member of another group called AOA)." }, { "code": null, "e": 2064, "s": 1944, "text": "So I decided to write a simple Python script using Amazon Rekognition which can accurately detect the members of Twice." }, { "code": null, "e": 2202, "s": 2064, "text": "In addition to short code blocks you can find in the post, I will attach the link for the whole Jupyter Notebook at the end of this post." }, { "code": null, "e": 2385, "s": 2202, "text": "This post is based on the tutorial “Build Your Own Face Recognition Service Using Amazon Rekognition”, but modified from the original code to fit the specific purpose of the project." }, { "code": null, "e": 2477, "s": 2385, "text": "There are a few prerequisites in order for you to run below steps in your Jupyter Notebook." }, { "code": null, "e": 2562, "s": 2477, "text": "Amazon AWS accountAWS credentials configured with AWS CLIThe latest version of Boto3" }, { "code": null, "e": 2581, "s": 2562, "text": "Amazon AWS account" }, { "code": null, "e": 2621, "s": 2581, "text": "AWS credentials configured with AWS CLI" }, { "code": null, "e": 2649, "s": 2621, "text": "The latest version of Boto3" }, { "code": null, "e": 2740, "s": 2649, "text": "Let’s first start by importing some packages that will be directly used for the next step." }, { "code": null, "e": 2792, "s": 2740, "text": "import boto3from PIL import Image%matplotlib inline" }, { "code": null, "e": 3138, "s": 2792, "text": "Now we need to have an image that we want to process. I chose the same image that I tried with the above web interface demo, and we will send this image to Rekognition API to get the result of its image recognition. (The image can also be found in the Github link that I will share at the end of this post.) Let’s take a quick look at the image." }, { "code": null, "e": 3172, "s": 3138, "text": "display(Image.open('Tzuyu.jpeg'))" }, { "code": null, "e": 3312, "s": 3172, "text": "The most basic task we can ask Rekognition is facial recognition with the given image, and this can be done with just a few lines of codes." }, { "code": null, "e": 3557, "s": 3312, "text": "import iorekognition = boto3.client('rekognition')image = Image.open(\"Tzuyu.jpeg\")stream = io.BytesIO()image.save(stream,format=\"JPEG\")image_binary = stream.getvalue()rekognition.detect_faces(Image={'Bytes':image_binary}, Attributes=['ALL'])" }, { "code": null, "e": 4016, "s": 3557, "text": "You can either send the image to Rekogntion as in-memory binary file object directly from your local machine or upload your image to S3 and give your bucket and key details as a parameter when calling rekognition.detect_faces(). In the above example, I am sending the binary object directly from my local machine. The response you will get from the above call will be quite long with all the information you can get from detect_faces function of Rekognition." }, { "code": null, "e": 8218, "s": 4016, "text": "{'FaceDetails': [{'AgeRange': {'High': 38, 'Low': 20}, 'Beard': {'Confidence': 99.98848724365234, 'Value': False}, 'BoundingBox': {'Height': 0.1584049016237259, 'Left': 0.4546355605125427, 'Top': 0.0878104418516159, 'Width': 0.09999311715364456}, 'Confidence': 100.0, 'Emotions': [{'Confidence': 37.66959762573242, 'Type': 'SURPRISED'}, {'Confidence': 29.646778106689453, 'Type': 'CALM'}, {'Confidence': 3.8459930419921875, 'Type': 'SAD'}, {'Confidence': 3.134934186935425, 'Type': 'DISGUSTED'}, {'Confidence': 2.061260938644409, 'Type': 'HAPPY'}, {'Confidence': 18.516468048095703, 'Type': 'CONFUSED'}, {'Confidence': 5.1249613761901855, 'Type': 'ANGRY'}], 'Eyeglasses': {'Confidence': 99.98339080810547, 'Value': False}, 'EyesOpen': {'Confidence': 99.9864730834961, 'Value': True}, 'Gender': {'Confidence': 99.84709167480469, 'Value': 'Female'}, 'Landmarks': [{'Type': 'eyeLeft', 'X': 0.47338899970054626, 'Y': 0.15436244010925293}, {'Type': 'eyeRight', 'X': 0.5152773261070251, 'Y': 0.1474122554063797}, {'Type': 'mouthLeft', 'X': 0.48312342166900635, 'Y': 0.211111381649971}, {'Type': 'mouthRight', 'X': 0.5174261927604675, 'Y': 0.20560002326965332}, {'Type': 'nose', 'X': 0.4872787892818451, 'Y': 0.1808750480413437}, {'Type': 'leftEyeBrowLeft', 'X': 0.45876359939575195, 'Y': 0.14424000680446625}, {'Type': 'leftEyeBrowRight', 'X': 0.4760720133781433, 'Y': 0.13612663745880127}, {'Type': 'leftEyeBrowUp', 'X': 0.4654795229434967, 'Y': 0.13559915125370026}, {'Type': 'rightEyeBrowLeft', 'X': 0.5008187890052795, 'Y': 0.1317606270313263}, {'Type': 'rightEyeBrowRight', 'X': 0.5342025756835938, 'Y': 0.1317359358072281}, {'Type': 'rightEyeBrowUp', 'X': 0.5151524543762207, 'Y': 0.12679456174373627}, {'Type': 'leftEyeLeft', 'X': 0.4674917757511139, 'Y': 0.15510375797748566}, {'Type': 'leftEyeRight', 'X': 0.4817998707294464, 'Y': 0.15343616902828217}, {'Type': 'leftEyeUp', 'X': 0.47253310680389404, 'Y': 0.1514900177717209}, {'Type': 'leftEyeDown', 'X': 0.47370508313179016, 'Y': 0.15651680529117584}, {'Type': 'rightEyeLeft', 'X': 0.5069678425788879, 'Y': 0.14930757880210876}, {'Type': 'rightEyeRight', 'X': 0.5239912867546082, 'Y': 0.1460886150598526}, {'Type': 'rightEyeUp', 'X': 0.5144344568252563, 'Y': 0.1447771191596985}, {'Type': 'rightEyeDown', 'X': 0.5150220394134521, 'Y': 0.14997448027133942}, {'Type': 'noseLeft', 'X': 0.4858757555484772, 'Y': 0.18927086889743805}, {'Type': 'noseRight', 'X': 0.5023624897003174, 'Y': 0.1855706423521042}, {'Type': 'mouthUp', 'X': 0.4945952594280243, 'Y': 0.2002507448196411}, {'Type': 'mouthDown', 'X': 0.4980264902114868, 'Y': 0.21687346696853638}, {'Type': 'leftPupil', 'X': 0.47338899970054626, 'Y': 0.15436244010925293}, {'Type': 'rightPupil', 'X': 0.5152773261070251, 'Y': 0.1474122554063797}, {'Type': 'upperJawlineLeft', 'X': 0.46607205271720886, 'Y': 0.15965013206005096}, {'Type': 'midJawlineLeft', 'X': 0.47901660203933716, 'Y': 0.21797965466976166}, {'Type': 'chinBottom', 'X': 0.5062429904937744, 'Y': 0.24532964825630188}, {'Type': 'midJawlineRight', 'X': 0.5554487109184265, 'Y': 0.20579127967357635}, {'Type': 'upperJawlineRight', 'X': 0.561174750328064, 'Y': 0.14439250528812408}], 'MouthOpen': {'Confidence': 99.0997543334961, 'Value': True}, 'Mustache': {'Confidence': 99.99714660644531, 'Value': False}, 'Pose': {'Pitch': 1.8594770431518555, 'Roll': -11.335309982299805, 'Yaw': -33.68760681152344}, 'Quality': {'Brightness': 89.57070922851562, 'Sharpness': 86.86019134521484}, 'Smile': {'Confidence': 99.23001861572266, 'Value': False}, 'Sunglasses': {'Confidence': 99.99723815917969, 'Value': False}}], 'ResponseMetadata': {'HTTPHeaders': {'connection': 'keep-alive', 'content-length': '3297', 'content-type': 'application/x-amz-json-1.1', 'date': 'Sun, 19 May 2019 08:45:56 GMT', 'x-amzn-requestid': '824f5dc3-7a12-11e9-a384-dfb84e388b7e'}, 'HTTPStatusCode': 200, 'RequestId': '824f5dc3-7a12-11e9-a384-dfb84e388b7e', 'RetryAttempts': 0}}" }, { "code": null, "e": 8449, "s": 8218, "text": "As you can see from the above example response of the detect_faces call, it has not only bounding box information of the location of the face in the picture but also more advanced features such as emotions, gender, age range, etc." }, { "code": null, "e": 8782, "s": 8449, "text": "With Amazon Rekognition, you can compare faces in two pictures. For example, if I set a picture of Tzuyu as my source picture, then send a group photo of Twice as my target picture, Rekognition will find the face in the target picture which is the most similar to the source picture. The group photo of Twice I’ll be using is below." }, { "code": null, "e": 9062, "s": 8782, "text": "It might be difficult even for humans, especially if you’re not Asian (or not a Twice fan). You can take your guess who is Tzuyu in the picture. As a Korean, and at the same time a Twice fan, I know the answer, but let’s see how well Rekognition can find Tzuyu from this picture." }, { "code": null, "e": 9410, "s": 9062, "text": "sourceFile='Tzuyu.jpeg'targetFile='twice_group.jpg' imageSource=open(sourceFile,'rb')imageTarget=open(targetFile,'rb')response = rekognition.compare_faces(SimilarityThreshold=80, SourceImage={'Bytes': imageSource.read()}, TargetImage={'Bytes': imageTarget.read()})response['FaceMatches']" }, { "code": null, "e": 9861, "s": 9410, "text": "The response of the above compare_faces will also output information of all the unmatched faces in the group picture, and this can get quite long, so I’m just outputting the match that Rekognition found by specifying response[‘FaceMatches’]. It seems like a matching face has been found from the group photo with the similarity of around 97%. With the bounding box information, let’s check which face that Rekognition is referring to as Tzuyu’s face." }, { "code": null, "e": 10183, "s": 9861, "text": "By the way, the values in the BoundingBox section are ratios of the overall image size. So, in order to draw box with the values in BoundingBox, you need to calculate the location of the box’s each point by multiplying ratios to the actual image height or width. You can find how it can be done in the below code snippet." }, { "code": null, "e": 10705, "s": 10183, "text": "from PIL import ImageDrawimage = Image.open(\"twice_group.jpg\")imgWidth,imgHeight = image.size draw = ImageDraw.Draw(image)box = response['FaceMatches'][0]['Face']['BoundingBox']left = imgWidth * box['Left']top = imgHeight * box['Top']width = imgWidth * box['Width']height = imgHeight * box['Height']points = ( (left,top), (left + width, top), (left + width, top + height), (left , top + height), (left, top))draw.line(points, fill='#00d400', width=2)display(image)" }, { "code": null, "e": 10756, "s": 10705, "text": "Yes! Well done, Rekognition! That is Tzuyu indeed!" }, { "code": null, "e": 11724, "s": 10756, "text": "Now we can detect face from a picture, and find the most similar face to the source picture from the target picture. But, these are all one-off call, and we need something more to store the information of each member’s face and their name, so that when we send a new picture of Twice, it can retrieve data and detect each member’s face and display their names. In order to implement this, we need to use what Amazon calls “Storage-Based API Operations”. There are two Amazon-specific terms for this type of operations. The “collection” is a virtual space where Rekognition stores information about detected faces. With a collection, we can “index” faces, which means to detect faces in an image, then store the information in the specified collection. What’s important is that the information Rekognition stores in the collection is not actual images, but feature vectors extracted by Rekognition’s algorithm. Let’s see how we can create a collection and add indexes." }, { "code": null, "e": 11811, "s": 11724, "text": "collectionId='test-collection'rekognition.create_collection(CollectionId=collectionId)" }, { "code": null, "e": 11970, "s": 11811, "text": "Yes. It is as simple as that. Since this is a new collection we just created, we don’t have any information stored in the collection. But, let’s double check." }, { "code": null, "e": 12029, "s": 11970, "text": "rekognition.describe_collection(CollectionId=collectionId)" }, { "code": null, "e": 12166, "s": 12029, "text": "In the above response, you can see ‘FaceCount’ is 0. This will change if we index any face and store that information in the collection." }, { "code": null, "e": 12238, "s": 12166, "text": "Indexing faces is again as simple as one line of code with Rekognition." }, { "code": null, "e": 12407, "s": 12238, "text": "sourceFile='Tzuyu.jpeg' imageSource=open(sourceFile,'rb')rekognition.index_faces(Image={'Bytes':imageSource.read()},ExternalImageId='Tzuyu',CollectionId=collectionId)" }, { "code": null, "e": 12970, "s": 12407, "text": "From the above code, you can see that I am passing ExternalImageId parameter and give it the value of string “Tzuyu”. Later when we try to recognise Tzuyu from a new picture, Rekognition will search for faces that are matching any of the indexed faces. As you will see later, when indexing a face, Rekognition will give it a unique face ID. But I want to display the name “Tzuyu” when a matching face is found from a new picture. For this purpose, I am using ExternalImageId. Now we if we check our collection, we can see 1 face has been added to the collection." }, { "code": null, "e": 13029, "s": 12970, "text": "rekognition.describe_collection(CollectionId=collectionId)" }, { "code": null, "e": 13590, "s": 13029, "text": "Now with Tzuyu’s face indexed in our collection, we can send a new unseen picture to Rekognition and find the matching face. But a problem with search_faces_by_image function is that it can only detect one face (the largest in the image). So if we want to send a group picture of Twice and find Tzuyu from there, we will need to do an additional step. Below we will first detect all the faces in the picture by using detect_faces, then with the bounding box information of each face, we will call search_faces_by_image one by one. First let’s detect each face." }, { "code": null, "e": 13743, "s": 13590, "text": "imageSource=open('twice_group.jpg','rb')resp = rekognition.detect_faces(Image={'Bytes':imageSource.read()})all_faces = resp['FaceDetails']len(all_faces)" }, { "code": null, "e": 13870, "s": 13743, "text": "Rekognition detected 9 faces from the group picture. Good. Now let’s crop each face and call serach_faces_by_image one by one." }, { "code": null, "e": 14516, "s": 13870, "text": "image = Image.open(\"twice_group.jpg\")image_width,image_height = image.sizefor face in all_faces: box=face['BoundingBox'] x1 = box['Left'] * image_width y1 = box['Top'] * image_height x2 = x1 + box['Width'] * image_width y2 = y1 + box['Height'] * image_height image_crop = image.crop((x1,y1,x2,y2)) stream = io.BytesIO() image_crop.save(stream,format=\"JPEG\") image_crop_binary = stream.getvalue()response = rekognition.search_faces_by_image( CollectionId=collectionId, Image={'Bytes':image_crop_binary} ) print(response) print('-'*100)" }, { "code": null, "e": 15269, "s": 14516, "text": "Among the 9 search_faces_by_image calls we have made, Rekognition has found one face that matches the indexed face in our collection. We only indexed one face of Tzuyu, so what it has found is Tzuyu’s face from the group picture. Let’s display this on the image with the bounding box and the name. For the name part, we will use the ExternalImageId we set when we indexed the face. By the way, from the search_faces_by_image response, ‘FaceMatches’ part is an array, and if there are more than one matches found from the collection, then it will show all the matches. According to Amazon this array is ordered by similarity score with the highest similarity first. We will get the match with the highest score by specifying the first item of the array." }, { "code": null, "e": 16405, "s": 15269, "text": "from PIL import ImageFontimport ioimage = Image.open(\"twice_group.jpg\")image_width,image_height = image.size for face in all_faces: box=face['BoundingBox'] x1 = box['Left'] * image_width y1 = box['Top'] * image_height x2 = x1 + box['Width'] * image_width y2 = y1 + box['Height'] * image_height image_crop = image.crop((x1,y1,x2,y2)) stream = io.BytesIO() image_crop.save(stream,format=\"JPEG\") image_crop_binary = stream.getvalue()response = rekognition.search_faces_by_image( CollectionId=collectionId, Image={'Bytes':image_crop_binary} ) if len(response['FaceMatches']) > 0: draw = ImageDraw.Draw(image) points = ( (x1,y1), (x2, y1), (x2, y2), (x1 , y2), (x1, y1)) draw.line(points, fill='#00d400', width=2) fnt = ImageFont.truetype('/Library/Fonts/Arial.ttf', 15) draw.text((x1,y2),response['FaceMatches'][0]['Face']['ExternalImageId'], font=fnt, fill=(255, 255, 0)) display(image)" }, { "code": null, "e": 16439, "s": 16405, "text": "Hooray! Again the correct answer!" }, { "code": null, "e": 17025, "s": 16439, "text": "Now let’s expand the project to identify all members from the group picture. In order to do that, we first need to index faces of all members (there are 9 members). I have prepared 4 pictures of each member. I have added multiple pictures of the same person following the logic of Amazon tutorial written by Christian Petters. According to Petters, “adding multiple reference images per person greatly enhances the potential match rate for a person”, which makes intuitive sense. From the Github link I’ll share at the end, you will find all the pictures that are used in this project." }, { "code": null, "e": 17102, "s": 17025, "text": "collectionId='twice'rekognition.create_collection(CollectionId=collectionId)" }, { "code": null, "e": 17484, "s": 17102, "text": "import ospath = 'Twice'for r, d, f in os.walk(path): for file in f: if file != '.DS_Store': sourceFile = os.path.join(r,file) imageSource=open(sourceFile,'rb') rekognition.index_faces(Image={'Bytes':imageSource.read()},ExternalImageId=file.split('_')[0],CollectionId=collectionId)rekognition.describe_collection(CollectionId=collectionId)" }, { "code": null, "e": 17660, "s": 17484, "text": "OK. It seems like all 36 pictures are indexed in our “twice” collection. Now it’s time to check the final result. Can Rekognition be enhanced to identify each member of Twice?" }, { "code": null, "e": 18779, "s": 17660, "text": "from PIL import ImageFontimage = Image.open(\"twice_group.jpg\")image_width,image_height = image.size for face in all_faces: box=face['BoundingBox'] x1 = box['Left'] * image_width y1 = box['Top'] * image_height x2 = x1 + box['Width'] * image_width y2 = y1 + box['Height'] * image_height image_crop = image.crop((x1,y1,x2,y2)) stream = io.BytesIO() image_crop.save(stream,format=\"JPEG\") image_crop_binary = stream.getvalue()response = rekognition.search_faces_by_image( CollectionId=collectionId, Image={'Bytes':image_crop_binary} ) if len(response['FaceMatches']) > 0: draw = ImageDraw.Draw(image) points = ( (x1,y1), (x2, y1), (x2, y2), (x1 , y2), (x1, y1)) draw.line(points, fill='#00d400', width=2) fnt = ImageFont.truetype('/Library/Fonts/Arial.ttf', 15) draw.text((x1,y2),response['FaceMatches'][0]['Face']['ExternalImageId'], font=fnt, fill=(255, 255, 0))display(image)" }, { "code": null, "e": 18833, "s": 18779, "text": "YES! It can! It identified all the members correctly!" } ]
How to display a specific field in array using $project in MongoDB and ignore other fields?
To display a specific field, use $project along with $unwind. To ignore a field, set to 0. Let us create a collection with documents − > db.demo731.insertOne({ "ProductInformation": [ { ProductId:"Product-1", ProductPrice:80 }, { ProductId:"Product-2", ProductPrice:45 }, { ProductId:"Product-3", ProductPrice:50 } ] } ); { "acknowledged" : true, "insertedId" : ObjectId("5eac5efd56e85a39df5f6341") } Display all documents from a collection with the help of find() method − > db.demo731.find(); This will produce the following output − { "_id" : ObjectId("5eac5efd56e85a39df5f6341"), "ProductInformation" : [ { "ProductId" : "Product-1", "ProductPrice" : 80 }, { "ProductId" : "Product-2", "ProductPrice" : 45 }, { "ProductId" : "Product-3", "ProductPrice" : 50 } ] } Following is the query to display a specific field in array using $project in MongoDB − > db.demo731.aggregate([ ... { $unwind: "$ProductInformation" }, ... { $match: { "ProductInformation.ProductPrice": 80} }, ... { $project: {_id: 0,"ProductInformation.ProductPrice":0}} ... ]) This will produce the following output − { "ProductInformation" : { "ProductId" : "Product-1" } }
[ { "code": null, "e": 1197, "s": 1062, "text": "To display a specific field, use $project along with $unwind. To ignore a field, set to 0. Let us create a collection with documents −" }, { "code": null, "e": 1469, "s": 1197, "text": "> db.demo731.insertOne({ \"ProductInformation\": [ { ProductId:\"Product-1\", ProductPrice:80 }, { ProductId:\"Product-2\", ProductPrice:45 }, { ProductId:\"Product-3\", ProductPrice:50 } ] } );\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5eac5efd56e85a39df5f6341\")\n}" }, { "code": null, "e": 1542, "s": 1469, "text": "Display all documents from a collection with the help of find() method −" }, { "code": null, "e": 1563, "s": 1542, "text": "> db.demo731.find();" }, { "code": null, "e": 1604, "s": 1563, "text": "This will produce the following output −" }, { "code": null, "e": 1836, "s": 1604, "text": "{ \"_id\" : ObjectId(\"5eac5efd56e85a39df5f6341\"), \"ProductInformation\" : [ { \"ProductId\" : \"Product-1\", \"ProductPrice\" : 80 }, { \"ProductId\" : \"Product-2\", \"ProductPrice\" : 45 }, { \"ProductId\" : \"Product-3\", \"ProductPrice\" : 50 } ] }" }, { "code": null, "e": 1924, "s": 1836, "text": "Following is the query to display a specific field in array using $project in MongoDB −" }, { "code": null, "e": 2125, "s": 1924, "text": "> db.demo731.aggregate([\n... { $unwind: \"$ProductInformation\" },\n... { $match: { \"ProductInformation.ProductPrice\": 80} },\n... { $project: {_id: 0,\"ProductInformation.ProductPrice\":0}}\n... ])" }, { "code": null, "e": 2166, "s": 2125, "text": "This will produce the following output −" }, { "code": null, "e": 2223, "s": 2166, "text": "{ \"ProductInformation\" : { \"ProductId\" : \"Product-1\" } }" } ]
Fine Tuning a T5 transformer for any Summarization Task | by Priya Dwivedi | Towards Data Science
I am amazed with the power of the T5 transformer model! T5 which stands for text to text transfer transformer makes it easy to fine tune a transformer model on any text to text task. Any NLP task event if it is a classification task, can be framed as an input text to output text problem. In this blog, I show how you can tune this model on any data set you have. In particular, I demo how this can be done on Summarization data sets. I have personally tested this on CNN-Daily Mail and the WikiHow data sets. The code is publicly available on my Github here. T5-small trained on Wikihow writes amazing summaries. See snippet below of actual text, actual summary and predicted summary. This model is also available on HuggingFace Transformers model hub here. The link provides a convenient way to test the model on input texts as well as a JSON endpoint. WikiHow Text: Make sure you've got all the cables disconnected from the back of your console,especially the power cord., You'll need the straight end to be about 2-3 inches long.You will need alarge size paper clip for this method because it will need to go in about 1 and a half inches topush the disc out., It's located on the left side of the console, right behind the vents.The ejecthole on an Xbox One S is located at the second hole on the left from the right corner and the thirdhole up from the bottom. It can be more difficult to spot, so it's best to have a good amount oflight available. Doing so will cause the disc to pop out a little bit., Carefully pull the disc therest of the way out with your fingers. It might be a good idea to use a cloth or soft fabric toprotect the disc from fingerprints and scratching.Actual Summary: Unplug all cables from your Xbox One.Bend a paper clip into a straight line.Locate the orange circle.Insert the paper clip into the eject hole.Use your fingers to pull the disc out.Predicted Summary: Gather the cables.Place the disc on your console.Section the eject hole on the left side of the console.Pull out the disc.Remove from the back of the console. I run a machine learning consulting, Deep Learning Analytics. At Deep Learning Analytics, we are very passionate about using data science and machine learning to solve real world problems. Please reach out to us if you are looking for NLP expertise for your business projects. Original full story published on our website here. T5 model which was released by google research adds the following to existing research: It creates a clean version of the massive common crawl data set called Colossal Cleaned Common crawl(C4). This data set is s two orders of magnitude larger than Wikipedia.It pretrains T5 on common crawlIt proposes reframing of all NLP tasks as an input text to output text formulationIt shows that fine tuning on different tasks — summarization, QnA, reading comprehension using the pretrained T5 and the text-text formulation results in state of the art resultsThe T5 team also did a systematic study to understand best practices for pre training and fine tuning. Their paper details what parameters matter most for getting good results. It creates a clean version of the massive common crawl data set called Colossal Cleaned Common crawl(C4). This data set is s two orders of magnitude larger than Wikipedia. It pretrains T5 on common crawl It proposes reframing of all NLP tasks as an input text to output text formulation It shows that fine tuning on different tasks — summarization, QnA, reading comprehension using the pretrained T5 and the text-text formulation results in state of the art results The T5 team also did a systematic study to understand best practices for pre training and fine tuning. Their paper details what parameters matter most for getting good results. The figure below from T5 paper explains this input text to output text problem formulation. This blog from Google also explains the paper well. Lets deep dive into the code now! We will use the HuggingFace Transformers implementation of the T5 model for this task. A big thanks to this awesome work from Suraj that I used as a starting point for my code. To make it simple to extend this pipeline to any NLP task, I have used the HuggingFace NLP library to get the data set. This makes it easy to load many supporting data sets. The HuggingFace NLP library also has support for many metrics. I have used it rouge score implementation for my model. The full code is available on my Github. For this demo, I will show how to process the WikiHow data set. The code though is flexible to be extended to any summarization task. The Main Steps involved are: Load the Wikihow data. Please note for this dataset, two files need to be download to a local data folderThe dataset object created by NLP library can be used to see sample examplesWe want to look at the average length of the text to decide if input can be tokenized to a max length of 512 Load the Wikihow data. Please note for this dataset, two files need to be download to a local data folder The dataset object created by NLP library can be used to see sample examples We want to look at the average length of the text to decide if input can be tokenized to a max length of 512 For Wikihow dataset, the average length of text is 660 words and average length of summary is 49. The graph below shows distribution of text length WikiHow text are usually 1–2 paragraphs instructional text on a subject. An example is shared below WikiHow Text: Each airline has a different seat design, but you should find a lever on the side ofyour seat in many cases. Pull it up to bring the seat back up. If you can't find the lever, ask aflight attendant for help., Most airlines still use seat belts that only go across your lap. Locatethe buckle on one side and the latching device on the other. Straighten out each side, if necessary.Insert the buckle into the latching device. Make sure you hear a click. Pull the belt until it'ssnug across the tops of your thighs., Do this even if the captain turns off the “Fasten Seat Belts”sign. If you decide to recline, make sure the belt stays snug across your lap. If you're using ablanket, place it between the belt and your body. Next, we define a Pytorch Dataset class which can be used for any NLP data set type. For the text to text T5, we have to define the fields for input text and target text. Here the ‘text’ of the article is an input text and the ‘headline’ is its summary. I have used an input target length of 512 tokens and an output summary length of 150. The output of the wikihow dataset class are : source_ids: Tokenized input text length truncated/padded to a max length of 512 source_mask: Attention mask corresponding to the input token IDs target_ids: Tokenized Target(summary) text length truncated/padded to a max length of 150 target_mask: Attention mask corresponding to the target token IDs My notebook on Github has sample code that you can use to play with the dataset class to check if the input is being encoded and decoded correctly. The T5 tuner is a pytorch lightning class that defines the data loaders, forward pass through the model, training one step, validation on one step as well as validation at epoch end. I have added a few features here to make it easier to use this for summarization: I have used the NLP library to import the rouge_metricI have extended the code to generate predictions at the validation step and used those to calculate the rouge metricAdded WANDB as the logger I have used the NLP library to import the rouge_metric I have extended the code to generate predictions at the validation step and used those to calculate the rouge metric Added WANDB as the logger I decided to train a T5 small model. I used a batch size of 4 for both train and val and could train this model on GTX 1080Ti in about 4 hours. The model was trained for 2 epochs and WANDB logger showed good improvement in Rouge1 score and Val loss as the model trained. The full report for the model is shared here. I have uploaded this model to Huggingface Transformers model hub and its available here for testing. To test the model on local, you can load it using the HuggingFace AutoModelWithLMHeadand AutoTokenizer feature. Sample script for doing that is shared below. The main drawback of the current model is that the input text length is set to max 512 tokens. This may be insufficient for many summarization problems. To overcome this limitation, I am working on a Longformer based summarization model. Will share a blog on that too soon! T5 is an awesome model. It has made it easy to fine tune a Transformer for any NLP problem with sufficient data. In this blog I have created a code shell that can be adapted for any summarization problem. I hope you give the code a try and train your own models. Please share your experience in the comments below. At Deep Learning Analytics, we are extremely passionate about using Machine Learning to solve real-world problems. We have helped many businesses deploy innovative AI-based solutions. Contact us through our website here if you see an opportunity to collaborate.
[ { "code": null, "e": 460, "s": 171, "text": "I am amazed with the power of the T5 transformer model! T5 which stands for text to text transfer transformer makes it easy to fine tune a transformer model on any text to text task. Any NLP task event if it is a classification task, can be framed as an input text to output text problem." }, { "code": null, "e": 731, "s": 460, "text": "In this blog, I show how you can tune this model on any data set you have. In particular, I demo how this can be done on Summarization data sets. I have personally tested this on CNN-Daily Mail and the WikiHow data sets. The code is publicly available on my Github here." }, { "code": null, "e": 1026, "s": 731, "text": "T5-small trained on Wikihow writes amazing summaries. See snippet below of actual text, actual summary and predicted summary. This model is also available on HuggingFace Transformers model hub here. The link provides a convenient way to test the model on input texts as well as a JSON endpoint." }, { "code": null, "e": 2227, "s": 1026, "text": "WikiHow Text: Make sure you've got all the cables disconnected from the back of your console,especially the power cord., You'll need the straight end to be about 2-3 inches long.You will need alarge size paper clip for this method because it will need to go in about 1 and a half inches topush the disc out., It's located on the left side of the console, right behind the vents.The ejecthole on an Xbox One S is located at the second hole on the left from the right corner and the thirdhole up from the bottom. It can be more difficult to spot, so it's best to have a good amount oflight available. Doing so will cause the disc to pop out a little bit., Carefully pull the disc therest of the way out with your fingers. It might be a good idea to use a cloth or soft fabric toprotect the disc from fingerprints and scratching.Actual Summary: Unplug all cables from your Xbox One.Bend a paper clip into a straight line.Locate the orange circle.Insert the paper clip into the eject hole.Use your fingers to pull the disc out.Predicted Summary: Gather the cables.Place the disc on your console.Section the eject hole on the left side of the console.Pull out the disc.Remove from the back of the console." }, { "code": null, "e": 2555, "s": 2227, "text": "I run a machine learning consulting, Deep Learning Analytics. At Deep Learning Analytics, we are very passionate about using data science and machine learning to solve real world problems. Please reach out to us if you are looking for NLP expertise for your business projects. Original full story published on our website here." }, { "code": null, "e": 2643, "s": 2555, "text": "T5 model which was released by google research adds the following to existing research:" }, { "code": null, "e": 3282, "s": 2643, "text": "It creates a clean version of the massive common crawl data set called Colossal Cleaned Common crawl(C4). This data set is s two orders of magnitude larger than Wikipedia.It pretrains T5 on common crawlIt proposes reframing of all NLP tasks as an input text to output text formulationIt shows that fine tuning on different tasks — summarization, QnA, reading comprehension using the pretrained T5 and the text-text formulation results in state of the art resultsThe T5 team also did a systematic study to understand best practices for pre training and fine tuning. Their paper details what parameters matter most for getting good results." }, { "code": null, "e": 3454, "s": 3282, "text": "It creates a clean version of the massive common crawl data set called Colossal Cleaned Common crawl(C4). This data set is s two orders of magnitude larger than Wikipedia." }, { "code": null, "e": 3486, "s": 3454, "text": "It pretrains T5 on common crawl" }, { "code": null, "e": 3569, "s": 3486, "text": "It proposes reframing of all NLP tasks as an input text to output text formulation" }, { "code": null, "e": 3748, "s": 3569, "text": "It shows that fine tuning on different tasks — summarization, QnA, reading comprehension using the pretrained T5 and the text-text formulation results in state of the art results" }, { "code": null, "e": 3925, "s": 3748, "text": "The T5 team also did a systematic study to understand best practices for pre training and fine tuning. Their paper details what parameters matter most for getting good results." }, { "code": null, "e": 4017, "s": 3925, "text": "The figure below from T5 paper explains this input text to output text problem formulation." }, { "code": null, "e": 4103, "s": 4017, "text": "This blog from Google also explains the paper well. Lets deep dive into the code now!" }, { "code": null, "e": 4280, "s": 4103, "text": "We will use the HuggingFace Transformers implementation of the T5 model for this task. A big thanks to this awesome work from Suraj that I used as a starting point for my code." }, { "code": null, "e": 4573, "s": 4280, "text": "To make it simple to extend this pipeline to any NLP task, I have used the HuggingFace NLP library to get the data set. This makes it easy to load many supporting data sets. The HuggingFace NLP library also has support for many metrics. I have used it rouge score implementation for my model." }, { "code": null, "e": 4748, "s": 4573, "text": "The full code is available on my Github. For this demo, I will show how to process the WikiHow data set. The code though is flexible to be extended to any summarization task." }, { "code": null, "e": 4777, "s": 4748, "text": "The Main Steps involved are:" }, { "code": null, "e": 5067, "s": 4777, "text": "Load the Wikihow data. Please note for this dataset, two files need to be download to a local data folderThe dataset object created by NLP library can be used to see sample examplesWe want to look at the average length of the text to decide if input can be tokenized to a max length of 512" }, { "code": null, "e": 5173, "s": 5067, "text": "Load the Wikihow data. Please note for this dataset, two files need to be download to a local data folder" }, { "code": null, "e": 5250, "s": 5173, "text": "The dataset object created by NLP library can be used to see sample examples" }, { "code": null, "e": 5359, "s": 5250, "text": "We want to look at the average length of the text to decide if input can be tokenized to a max length of 512" }, { "code": null, "e": 5507, "s": 5359, "text": "For Wikihow dataset, the average length of text is 660 words and average length of summary is 49. The graph below shows distribution of text length" }, { "code": null, "e": 5607, "s": 5507, "text": "WikiHow text are usually 1–2 paragraphs instructional text on a subject. An example is shared below" }, { "code": null, "e": 6342, "s": 5607, "text": "WikiHow Text: Each airline has a different seat design, but you should find a lever on the side ofyour seat in many cases. Pull it up to bring the seat back up. If you can't find the lever, ask aflight attendant for help., Most airlines still use seat belts that only go across your lap. Locatethe buckle on one side and the latching device on the other. Straighten out each side, if necessary.Insert the buckle into the latching device. Make sure you hear a click. Pull the belt until it'ssnug across the tops of your thighs., Do this even if the captain turns off the “Fasten Seat Belts”sign. If you decide to recline, make sure the belt stays snug across your lap. If you're using ablanket, place it between the belt and your body." }, { "code": null, "e": 6596, "s": 6342, "text": "Next, we define a Pytorch Dataset class which can be used for any NLP data set type. For the text to text T5, we have to define the fields for input text and target text. Here the ‘text’ of the article is an input text and the ‘headline’ is its summary." }, { "code": null, "e": 6728, "s": 6596, "text": "I have used an input target length of 512 tokens and an output summary length of 150. The output of the wikihow dataset class are :" }, { "code": null, "e": 6808, "s": 6728, "text": "source_ids: Tokenized input text length truncated/padded to a max length of 512" }, { "code": null, "e": 6873, "s": 6808, "text": "source_mask: Attention mask corresponding to the input token IDs" }, { "code": null, "e": 6963, "s": 6873, "text": "target_ids: Tokenized Target(summary) text length truncated/padded to a max length of 150" }, { "code": null, "e": 7029, "s": 6963, "text": "target_mask: Attention mask corresponding to the target token IDs" }, { "code": null, "e": 7177, "s": 7029, "text": "My notebook on Github has sample code that you can use to play with the dataset class to check if the input is being encoded and decoded correctly." }, { "code": null, "e": 7360, "s": 7177, "text": "The T5 tuner is a pytorch lightning class that defines the data loaders, forward pass through the model, training one step, validation on one step as well as validation at epoch end." }, { "code": null, "e": 7442, "s": 7360, "text": "I have added a few features here to make it easier to use this for summarization:" }, { "code": null, "e": 7638, "s": 7442, "text": "I have used the NLP library to import the rouge_metricI have extended the code to generate predictions at the validation step and used those to calculate the rouge metricAdded WANDB as the logger" }, { "code": null, "e": 7693, "s": 7638, "text": "I have used the NLP library to import the rouge_metric" }, { "code": null, "e": 7810, "s": 7693, "text": "I have extended the code to generate predictions at the validation step and used those to calculate the rouge metric" }, { "code": null, "e": 7836, "s": 7810, "text": "Added WANDB as the logger" }, { "code": null, "e": 8107, "s": 7836, "text": "I decided to train a T5 small model. I used a batch size of 4 for both train and val and could train this model on GTX 1080Ti in about 4 hours. The model was trained for 2 epochs and WANDB logger showed good improvement in Rouge1 score and Val loss as the model trained." }, { "code": null, "e": 8153, "s": 8107, "text": "The full report for the model is shared here." }, { "code": null, "e": 8412, "s": 8153, "text": "I have uploaded this model to Huggingface Transformers model hub and its available here for testing. To test the model on local, you can load it using the HuggingFace AutoModelWithLMHeadand AutoTokenizer feature. Sample script for doing that is shared below." }, { "code": null, "e": 8686, "s": 8412, "text": "The main drawback of the current model is that the input text length is set to max 512 tokens. This may be insufficient for many summarization problems. To overcome this limitation, I am working on a Longformer based summarization model. Will share a blog on that too soon!" }, { "code": null, "e": 8891, "s": 8686, "text": "T5 is an awesome model. It has made it easy to fine tune a Transformer for any NLP problem with sufficient data. In this blog I have created a code shell that can be adapted for any summarization problem." }, { "code": null, "e": 9001, "s": 8891, "text": "I hope you give the code a try and train your own models. Please share your experience in the comments below." } ]
How to use an HTML tag inside HTML table?
With HTML, you can easily add HTML tag inside a table. The tag should open and close inside the <td> tag. For example, adding a paragraph <p>...</> tag or even a list tag i.e. <ul>...<ul>. You can try to run the following code to use an HTML tag <ul>...</ul> inside HTML table Live Demo <!DOCTYPE html> <html> <head> <style> table, th, td { border: 1px solid black; width: 400px; } </style> </head> <body> <h1> Total Points</h1> <table> <tr> <th>Technologies</th> <th>Points</th> </tr> <tr> <td>Programming Languages <ul> <li>C++</li> <li>Java</li> <li>C</li> </ul> </td> <td>100</td> </tr> <tr> <td>Database <ul> <li>MySQL</li> <li>Oracle</li> <li>CouchDB</li> </ul> </td> <td>50</td> </tr> </table> </body> </html>
[ { "code": null, "e": 1251, "s": 1062, "text": "With HTML, you can easily add HTML tag inside a table. The tag should open and close inside the <td> tag. For example, adding a paragraph <p>...</> tag or even a list tag i.e. <ul>...<ul>." }, { "code": null, "e": 1339, "s": 1251, "text": "You can try to run the following code to use an HTML tag <ul>...</ul> inside HTML table" }, { "code": null, "e": 1349, "s": 1339, "text": "Live Demo" }, { "code": null, "e": 2141, "s": 1349, "text": "<!DOCTYPE html>\n<html>\n <head>\n <style>\n table, th, td { border: 1px solid black; width: 400px; }\n </style>\n </head>\n <body>\n <h1> Total Points</h1>\n <table>\n <tr>\n <th>Technologies</th>\n <th>Points</th>\n </tr>\n <tr>\n <td>Programming Languages\n <ul>\n <li>C++</li>\n <li>Java</li>\n <li>C</li>\n </ul>\n </td>\n <td>100</td>\n </tr>\n <tr>\n <td>Database\n <ul>\n <li>MySQL</li>\n <li>Oracle</li>\n <li>CouchDB</li>\n </ul>\n </td>\n <td>50</td>\n </tr>\n </table>\n </body>\n</html>" } ]
How to add comments in MySQL Code?
We can add comments in MySQL with the help of # symbol. Whenever we write # symbol before any sentence, the whole line will be ignored by MySQL. MySQL supports three type of comments − 1. With the help of # symbol mysql> create table CommentDemo -> ( -> id int #Id is an integer type -> ); Query OK, 0 rows affected (0.65 sec Above, we have set the comment as #Id is an integer type 2. With the help of -- symbol mysql> create table CommentDemo2 -> ( -> id int -- id is an integer type -> ); Query OK, 0 rows affected (0.49 sec) Above, we have set the comment as − - id is an integer type 3. With the help of /* */ symbol This is for multiple line comments, same as C or C++ language. mysql> create table CommentDemo3 -> ( -> /*id is an integer type */ -> id int -> ); Query OK, 0 rows affected (0.52 sec) Above, we have set multi-line comment as /*id is an integer type */
[ { "code": null, "e": 1207, "s": 1062, "text": "We can add comments in MySQL with the help of # symbol. Whenever we write # symbol before any sentence, the whole line will be ignored by MySQL." }, { "code": null, "e": 1247, "s": 1207, "text": "MySQL supports three type of comments −" }, { "code": null, "e": 1276, "s": 1247, "text": "1. With the help of # symbol" }, { "code": null, "e": 1399, "s": 1276, "text": "mysql> create table CommentDemo\n -> (\n -> id int #Id is an integer type\n -> );\nQuery OK, 0 rows affected (0.65 sec" }, { "code": null, "e": 1433, "s": 1399, "text": "Above, we have set the comment as" }, { "code": null, "e": 1457, "s": 1433, "text": "#Id is an integer type\n" }, { "code": null, "e": 1487, "s": 1457, "text": "2. With the help of -- symbol" }, { "code": null, "e": 1612, "s": 1487, "text": "mysql> create table CommentDemo2\n -> (\n -> id int -- id is an integer type\n -> );\nQuery OK, 0 rows affected (0.49 sec)" }, { "code": null, "e": 1648, "s": 1612, "text": "Above, we have set the comment as −" }, { "code": null, "e": 1673, "s": 1648, "text": "- id is an integer type\n" }, { "code": null, "e": 1707, "s": 1673, "text": "3. With the help of /* */ symbol" }, { "code": null, "e": 1770, "s": 1707, "text": "This is for multiple line comments, same as C or C++ language." }, { "code": null, "e": 1903, "s": 1770, "text": "mysql> create table CommentDemo3\n -> (\n -> /*id is an integer type */\n -> id int\n -> );\nQuery OK, 0 rows affected (0.52 sec)" }, { "code": null, "e": 1944, "s": 1903, "text": "Above, we have set multi-line comment as" }, { "code": null, "e": 1972, "s": 1944, "text": "/*id is an integer type */\n" } ]
How to change the orientation and font size of x-axis labels using ggplot2 in R?
This can be done by using theme argument in ggplot2 > df <- data.frame(x=gl(10, 1, 10, labels=paste("long text label ", letters[1:10])), y=rnorm(10,0.5)) > df x y 1 long text label a -0.8080940 2 long text label b 0.2164785 3 long text label c 0.4694148 4 long text label d 0.7878956 5 long text label e -0.1836776 6 long text label f 0.7916155 7 long text label g 1.3170755 8 long text label h 0.4002917 9 long text label i 0.6890988 10 long text label j 0.6077572 Plot is created as follows − > library(ggplot2) > ggplot(df, aes(x=x, y=y)) + geom_point() + theme(text = element_text(size=20), axis.text.x = element_text(angle=90, hjust=1))
[ { "code": null, "e": 1239, "s": 1187, "text": "This can be done by using theme argument in ggplot2" }, { "code": null, "e": 1672, "s": 1239, "text": "> df <- data.frame(x=gl(10, 1, 10, labels=paste(\"long text label \", letters[1:10])),\ny=rnorm(10,0.5))\n> df\n x y\n1 long text label a -0.8080940\n2 long text label b 0.2164785\n3 long text label c 0.4694148\n4 long text label d 0.7878956\n5 long text label e -0.1836776\n6 long text label f 0.7916155\n7 long text label g 1.3170755\n8 long text label h 0.4002917\n9 long text label i 0.6890988\n10 long text label j 0.6077572" }, { "code": null, "e": 1701, "s": 1672, "text": "Plot is created as follows −" }, { "code": null, "e": 1857, "s": 1701, "text": "> library(ggplot2)\n> ggplot(df, aes(x=x, y=y)) + geom_point() +\n theme(text = element_text(size=20),\n axis.text.x = element_text(angle=90, hjust=1))" } ]
Views In Django | Python
16 Sep, 2021 Django Views are one of the vital participants of MVT Structure of Django. As per Django Documentation, A view function is a Python function that takes a Web request and returns a Web response. This response can be the HTML contents of a Web page, or a redirect, or a 404 error, or an XML document, or an image, anything that a web browser can display. Django views are part of the user interface — they usually render the HTML/CSS/Javascript in your Template files into what you see in your browser when you render a web page. (Note that if you’ve used other frameworks based on the MVC (Model-View-Controller), do not get confused between Django views and views in the MVC paradigm. Django views roughly correspond to controllers in MVC, and Django templates to views in MVC.) Illustration of How to create and use a Django view using an Example. Consider a project named geeksforgeeks having an app named geeks. Refer to the following articles to check how to create a project and an app in Django. How to Create a Basic Project using MVT in Django? How to Create an App in Django ? After you have a project ready, we can create a view in geeks/views.py, Python3 # import Http Response from djangofrom django.http import HttpResponse# get datetimeimport datetime # create a functiondef geeks_view(request): # fetch date and time now = datetime.datetime.now() # convert to string html = "Time is {}".format(now) # return response return HttpResponse(html) Let’s step through this code one line at a time: First, we import the class HttpResponse from the django.http module, along with Python’s datetime library. Next, we define a function called geeks_view. This is the view function. Each view function takes an HttpRequest object as its first parameter, which is typically named request. The view returns an HttpResponse object that contains the generated response. Each view function is responsible for returning an HttpResponse object. For more info on HttpRequest and HttpResponse visit – Django Request and Response cycle – HttpRequest and HttpResponse ObjectsLet’s get this view to working, in geeks/urls.py, Python3 from django.urls import path # importing views from views..pyfrom .views import geeks_view urlpatterns = [ path('', geeks_view),] Now, visit http://127.0.0.1:8000/, To check how to make a basic project using MVT (Model, View, Template) structure of Django, visit Creating a Project Django. Django views are divided into two major categories:- Function-Based Views Class-Based Views Function based views are writer using a function in python which receives as an argument HttpRequest object and returns an HttpResponse Object. Function based views are generally divided into 4 basic strategies, i.e., CRUD (Create, Retrieve, Update, Delete). CRUD is the base of any framework one is using for development. Let’s Create a function-based view list view to display instances of a model. Let’s create a model of which we will be creating instances through our view. In geeks/models.py, Python3 # import the standard Django Model# from built-in libraryfrom django.db import models # declare a new model with a name "GeeksModel"class GeeksModel(models.Model): # fields of the model title = models.CharField(max_length = 200) description = models.TextField() # renames the instances of the model # with their title name def __str__(self): return self.title After creating this model, we need to run two commands in order to create Database for the same. Python manage.py makemigrations Python manage.py migrate Now let’s create some instances of this model using shell, run form bash, Python manage.py shell Enter following commands >>> from geeks.models import GeeksModel >>> GeeksModel.objects.create( title="title1", description="description1").save() >>> GeeksModel.objects.create( title="title2", description="description2").save() >>> GeeksModel.objects.create( title="title2", description="description2").save() Now if you want to see your model and its data in the admin panel, then you need to register your model.Let’s register this model. In geeks/admin.py, Python3 from django.contrib import adminfrom .models import GeeksModel# Register your models here.admin.site.register(GeeksModel) Now we have everything ready for the back end. Verify that instances have been created from http://localhost:8000/admin/geeks/geeksmodel/ Let’s create a view and template for the same. In geeks/views.py, Python3 from django.shortcuts import render # relative import of formsfrom .models import GeeksModel def list_view(request): # dictionary for initial data with # field names as keys context ={} # add the dictionary during initialization context["dataset"] = GeeksModel.objects.all() return render(request, "list_view.html", context) Create a template in templates/list_view.html, html <div class="main"> {% for data in dataset %}. {{ data.title }}<br/> {{ data.description }}<br/> <hr/> {% endfor %} </div> Let’s check what is there on http://localhost:8000/ Similarly, function based views can be implemented with logics for create, update, retrieve and delete views.Django CRUD (Create, Retrieve, Update, Delete) Function Based Views :- Class-based views provide an alternative way to implement views as Python objects instead of functions. They do not replace function-based views, but have certain differences and advantages when compared to function-based views: Organization of code related to specific HTTP methods (GET, POST, etc.) can be addressed by separate methods instead of conditional branching. Object oriented techniques such as mixins (multiple inheritance) can be used to factor code into reusable components. Class-based views are simpler and efficient to manage than function-based views. A function-based view with tons of lines of code can be converted into class-based views with few lines only. This is where Object-Oriented Programming comes into impact. In geeks/views.py, Python3 from django.views.generic.list import ListViewfrom .models import GeeksModel class GeeksList(ListView): # specify the model for list view model = GeeksModel Now create a URL path to map the view. In geeks/urls.py, Python3 from django.urls import path # importing views from views..pyfrom .views import GeeksListurlpatterns = [ path('', GeeksList.as_view()),] Create a template in templates/geeks/geeksmodel_list.html, html <ul> <!-- Iterate over object_list --> {% for object in object_list %} <!-- Display Objects --> <li>{{ object.title }}</li> <li>{{ object.description }}</li> <hr/> <!-- If objet_list is empty --> {% empty %} <li>No objects yet.</li> {% endfor %}</ul> Let’s check what is there on http://localhost:8000/ Django CRUD (Create, Retrieve, Update, Delete) Class Based Generic Views :- CreateView – Class based Views Django DetailView – Class based Views Django UpdateView – Class based Views Django DeleteView – Class based Views Django FormView – Class Based Views Django Akanksha_Rai NaveenArora harshitaggarwal3 svrrrsvr daveboltman saurabh1990aror Picked Python Django Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n16 Sep, 2021" }, { "code": null, "e": 406, "s": 52, "text": "Django Views are one of the vital participants of MVT Structure of Django. As per Django Documentation, A view function is a Python function that takes a Web request and returns a Web response. This response can be the HTML contents of a Web page, or a redirect, or a 404 error, or an XML document, or an image, anything that a web browser can display. " }, { "code": null, "e": 832, "s": 406, "text": "Django views are part of the user interface — they usually render the HTML/CSS/Javascript in your Template files into what you see in your browser when you render a web page. (Note that if you’ve used other frameworks based on the MVC (Model-View-Controller), do not get confused between Django views and views in the MVC paradigm. Django views roughly correspond to controllers in MVC, and Django templates to views in MVC.)" }, { "code": null, "e": 971, "s": 834, "text": "Illustration of How to create and use a Django view using an Example. Consider a project named geeksforgeeks having an app named geeks. " }, { "code": null, "e": 1059, "s": 971, "text": "Refer to the following articles to check how to create a project and an app in Django. " }, { "code": null, "e": 1110, "s": 1059, "text": "How to Create a Basic Project using MVT in Django?" }, { "code": null, "e": 1143, "s": 1110, "text": "How to Create an App in Django ?" }, { "code": null, "e": 1215, "s": 1143, "text": "After you have a project ready, we can create a view in geeks/views.py," }, { "code": null, "e": 1223, "s": 1215, "text": "Python3" }, { "code": "# import Http Response from djangofrom django.http import HttpResponse# get datetimeimport datetime # create a functiondef geeks_view(request): # fetch date and time now = datetime.datetime.now() # convert to string html = \"Time is {}\".format(now) # return response return HttpResponse(html)", "e": 1533, "s": 1223, "text": null }, { "code": null, "e": 1583, "s": 1533, "text": "Let’s step through this code one line at a time: " }, { "code": null, "e": 1690, "s": 1583, "text": "First, we import the class HttpResponse from the django.http module, along with Python’s datetime library." }, { "code": null, "e": 1868, "s": 1690, "text": "Next, we define a function called geeks_view. This is the view function. Each view function takes an HttpRequest object as its first parameter, which is typically named request." }, { "code": null, "e": 2018, "s": 1868, "text": "The view returns an HttpResponse object that contains the generated response. Each view function is responsible for returning an HttpResponse object." }, { "code": null, "e": 2194, "s": 2018, "text": "For more info on HttpRequest and HttpResponse visit – Django Request and Response cycle – HttpRequest and HttpResponse ObjectsLet’s get this view to working, in geeks/urls.py," }, { "code": null, "e": 2202, "s": 2194, "text": "Python3" }, { "code": "from django.urls import path # importing views from views..pyfrom .views import geeks_view urlpatterns = [ path('', geeks_view),]", "e": 2335, "s": 2202, "text": null }, { "code": null, "e": 2370, "s": 2335, "text": "Now, visit http://127.0.0.1:8000/," }, { "code": null, "e": 2495, "s": 2370, "text": "To check how to make a basic project using MVT (Model, View, Template) structure of Django, visit Creating a Project Django." }, { "code": null, "e": 2548, "s": 2495, "text": "Django views are divided into two major categories:-" }, { "code": null, "e": 2569, "s": 2548, "text": "Function-Based Views" }, { "code": null, "e": 2587, "s": 2569, "text": "Class-Based Views" }, { "code": null, "e": 2914, "s": 2589, "text": "Function based views are writer using a function in python which receives as an argument HttpRequest object and returns an HttpResponse Object. Function based views are generally divided into 4 basic strategies, i.e., CRUD (Create, Retrieve, Update, Delete). CRUD is the base of any framework one is using for development. " }, { "code": null, "e": 3090, "s": 2914, "text": "Let’s Create a function-based view list view to display instances of a model. Let’s create a model of which we will be creating instances through our view. In geeks/models.py," }, { "code": null, "e": 3098, "s": 3090, "text": "Python3" }, { "code": "# import the standard Django Model# from built-in libraryfrom django.db import models # declare a new model with a name \"GeeksModel\"class GeeksModel(models.Model): # fields of the model title = models.CharField(max_length = 200) description = models.TextField() # renames the instances of the model # with their title name def __str__(self): return self.title", "e": 3486, "s": 3098, "text": null }, { "code": null, "e": 3583, "s": 3486, "text": "After creating this model, we need to run two commands in order to create Database for the same." }, { "code": null, "e": 3640, "s": 3583, "text": "Python manage.py makemigrations\nPython manage.py migrate" }, { "code": null, "e": 3714, "s": 3640, "text": "Now let’s create some instances of this model using shell, run form bash," }, { "code": null, "e": 3737, "s": 3714, "text": "Python manage.py shell" }, { "code": null, "e": 3762, "s": 3737, "text": "Enter following commands" }, { "code": null, "e": 4186, "s": 3762, "text": ">>> from geeks.models import GeeksModel\n>>> GeeksModel.objects.create(\n title=\"title1\",\n description=\"description1\").save()\n>>> GeeksModel.objects.create(\n title=\"title2\",\n description=\"description2\").save()\n>>> GeeksModel.objects.create(\n title=\"title2\",\n description=\"description2\").save()" }, { "code": null, "e": 4336, "s": 4186, "text": "Now if you want to see your model and its data in the admin panel, then you need to register your model.Let’s register this model. In geeks/admin.py," }, { "code": null, "e": 4344, "s": 4336, "text": "Python3" }, { "code": "from django.contrib import adminfrom .models import GeeksModel# Register your models here.admin.site.register(GeeksModel)", "e": 4466, "s": 4344, "text": null }, { "code": null, "e": 4605, "s": 4466, "text": "Now we have everything ready for the back end. Verify that instances have been created from http://localhost:8000/admin/geeks/geeksmodel/ " }, { "code": null, "e": 4671, "s": 4605, "text": "Let’s create a view and template for the same. In geeks/views.py," }, { "code": null, "e": 4679, "s": 4671, "text": "Python3" }, { "code": "from django.shortcuts import render # relative import of formsfrom .models import GeeksModel def list_view(request): # dictionary for initial data with # field names as keys context ={} # add the dictionary during initialization context[\"dataset\"] = GeeksModel.objects.all() return render(request, \"list_view.html\", context)", "e": 5033, "s": 4679, "text": null }, { "code": null, "e": 5080, "s": 5033, "text": "Create a template in templates/list_view.html," }, { "code": null, "e": 5085, "s": 5080, "text": "html" }, { "code": "<div class=\"main\"> {% for data in dataset %}. {{ data.title }}<br/> {{ data.description }}<br/> <hr/> {% endfor %} </div>", "e": 5225, "s": 5085, "text": null }, { "code": null, "e": 5277, "s": 5225, "text": "Let’s check what is there on http://localhost:8000/" }, { "code": null, "e": 5458, "s": 5277, "text": "Similarly, function based views can be implemented with logics for create, update, retrieve and delete views.Django CRUD (Create, Retrieve, Update, Delete) Function Based Views :- " }, { "code": null, "e": 5688, "s": 5458, "text": "Class-based views provide an alternative way to implement views as Python objects instead of functions. They do not replace function-based views, but have certain differences and advantages when compared to function-based views: " }, { "code": null, "e": 5831, "s": 5688, "text": "Organization of code related to specific HTTP methods (GET, POST, etc.) can be addressed by separate methods instead of conditional branching." }, { "code": null, "e": 5949, "s": 5831, "text": "Object oriented techniques such as mixins (multiple inheritance) can be used to factor code into reusable components." }, { "code": null, "e": 6203, "s": 5949, "text": "Class-based views are simpler and efficient to manage than function-based views. A function-based view with tons of lines of code can be converted into class-based views with few lines only. This is where Object-Oriented Programming comes into impact. " }, { "code": null, "e": 6222, "s": 6203, "text": "In geeks/views.py," }, { "code": null, "e": 6230, "s": 6222, "text": "Python3" }, { "code": "from django.views.generic.list import ListViewfrom .models import GeeksModel class GeeksList(ListView): # specify the model for list view model = GeeksModel", "e": 6394, "s": 6230, "text": null }, { "code": null, "e": 6451, "s": 6394, "text": "Now create a URL path to map the view. In geeks/urls.py," }, { "code": null, "e": 6459, "s": 6451, "text": "Python3" }, { "code": "from django.urls import path # importing views from views..pyfrom .views import GeeksListurlpatterns = [ path('', GeeksList.as_view()),]", "e": 6599, "s": 6459, "text": null }, { "code": null, "e": 6658, "s": 6599, "text": "Create a template in templates/geeks/geeksmodel_list.html," }, { "code": null, "e": 6663, "s": 6658, "text": "html" }, { "code": "<ul> <!-- Iterate over object_list --> {% for object in object_list %} <!-- Display Objects --> <li>{{ object.title }}</li> <li>{{ object.description }}</li> <hr/> <!-- If objet_list is empty --> {% empty %} <li>No objects yet.</li> {% endfor %}</ul>", "e": 6946, "s": 6663, "text": null }, { "code": null, "e": 6999, "s": 6946, "text": "Let’s check what is there on http://localhost:8000/ " }, { "code": null, "e": 7075, "s": 6999, "text": "Django CRUD (Create, Retrieve, Update, Delete) Class Based Generic Views :-" }, { "code": null, "e": 7113, "s": 7075, "text": "CreateView – Class based Views Django" }, { "code": null, "e": 7151, "s": 7113, "text": "DetailView – Class based Views Django" }, { "code": null, "e": 7189, "s": 7151, "text": "UpdateView – Class based Views Django" }, { "code": null, "e": 7227, "s": 7189, "text": "DeleteView – Class based Views Django" }, { "code": null, "e": 7263, "s": 7227, "text": "FormView – Class Based Views Django" }, { "code": null, "e": 7276, "s": 7263, "text": "Akanksha_Rai" }, { "code": null, "e": 7288, "s": 7276, "text": "NaveenArora" }, { "code": null, "e": 7305, "s": 7288, "text": "harshitaggarwal3" }, { "code": null, "e": 7314, "s": 7305, "text": "svrrrsvr" }, { "code": null, "e": 7326, "s": 7314, "text": "daveboltman" }, { "code": null, "e": 7342, "s": 7326, "text": "saurabh1990aror" }, { "code": null, "e": 7349, "s": 7342, "text": "Picked" }, { "code": null, "e": 7363, "s": 7349, "text": "Python Django" }, { "code": null, "e": 7370, "s": 7363, "text": "Python" } ]
How to Save Output of Command in a File in Linux?
17 Mar, 2021 When we run a command on a terminal on Linux it generates some output of that command. Sometimes we need the output result of the commands. Today we are going to see how to save the output of the command. We can use the redirections operators to save the output of commands into files. Redirection operators redirect the output of a command to the file instead of the output terminal. There are two main redirection operators in Linux: > >> Example 1: The first operator is “>” which is used to redirect the output of a command to the file, but this operator erases all existing data in that file and overwrites the command output, Let’s see one example of > redirection operator: In the above image, we can see that the previous content of the output.txt file gets erased and the output of the ls command is written into the file. Example 2: Now let’s see about the second redirection operator is >>. Using this operator we can append the output of the command to the file. It does not erase any previous content of the file. Let’s see the example of >> operator In the above image, we can see that the output of the command is appended to the output.txt file without erasing the content stored in that file. If the file mentioned after the Redirection operator in not exist then it will create automatically. When we use the redirection operator the output is going to the file only the redirection operator does not print it on the terminal. To see the output on the terminal and also save it into the file we can use the tee command. It sends the output of the file as well as to the terminal. First, let’s see how to use the tee operator using the pipeline. Following is the syntax of using the tee operator: command | tee outfile.txt Now let’s see one example of the tee command: We can see in the above image the output is redirected to the terminal as well as the output.txt file. To append the output of the command to the file use the –a option with the tee command. Here is the syntax of the command: command | tee outfile.txt Now Let’s see one example of this command In this image, we can see that the output of cowsay command is stored in the output.txt file without erasing the existing data of the file. linux-command How To Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n17 Mar, 2021" }, { "code": null, "e": 233, "s": 28, "text": "When we run a command on a terminal on Linux it generates some output of that command. Sometimes we need the output result of the commands. Today we are going to see how to save the output of the command." }, { "code": null, "e": 414, "s": 233, "text": "We can use the redirections operators to save the output of commands into files. Redirection operators redirect the output of a command to the file instead of the output terminal. " }, { "code": null, "e": 465, "s": 414, "text": "There are two main redirection operators in Linux:" }, { "code": null, "e": 467, "s": 465, "text": ">" }, { "code": null, "e": 470, "s": 467, "text": ">>" }, { "code": null, "e": 481, "s": 470, "text": "Example 1:" }, { "code": null, "e": 662, "s": 481, "text": "The first operator is “>” which is used to redirect the output of a command to the file, but this operator erases all existing data in that file and overwrites the command output, " }, { "code": null, "e": 711, "s": 662, "text": "Let’s see one example of > redirection operator:" }, { "code": null, "e": 862, "s": 711, "text": "In the above image, we can see that the previous content of the output.txt file gets erased and the output of the ls command is written into the file." }, { "code": null, "e": 873, "s": 862, "text": "Example 2:" }, { "code": null, "e": 1058, "s": 873, "text": "Now let’s see about the second redirection operator is >>. Using this operator we can append the output of the command to the file. It does not erase any previous content of the file. " }, { "code": null, "e": 1095, "s": 1058, "text": "Let’s see the example of >> operator" }, { "code": null, "e": 1241, "s": 1095, "text": "In the above image, we can see that the output of the command is appended to the output.txt file without erasing the content stored in that file." }, { "code": null, "e": 1342, "s": 1241, "text": "If the file mentioned after the Redirection operator in not exist then it will create automatically." }, { "code": null, "e": 1629, "s": 1342, "text": "When we use the redirection operator the output is going to the file only the redirection operator does not print it on the terminal. To see the output on the terminal and also save it into the file we can use the tee command. It sends the output of the file as well as to the terminal." }, { "code": null, "e": 1745, "s": 1629, "text": "First, let’s see how to use the tee operator using the pipeline. Following is the syntax of using the tee operator:" }, { "code": null, "e": 1771, "s": 1745, "text": "command | tee outfile.txt" }, { "code": null, "e": 1817, "s": 1771, "text": "Now let’s see one example of the tee command:" }, { "code": null, "e": 1920, "s": 1817, "text": "We can see in the above image the output is redirected to the terminal as well as the output.txt file." }, { "code": null, "e": 2043, "s": 1920, "text": "To append the output of the command to the file use the –a option with the tee command. Here is the syntax of the command:" }, { "code": null, "e": 2069, "s": 2043, "text": "command | tee outfile.txt" }, { "code": null, "e": 2111, "s": 2069, "text": "Now Let’s see one example of this command" }, { "code": null, "e": 2251, "s": 2111, "text": "In this image, we can see that the output of cowsay command is stored in the output.txt file without erasing the existing data of the file." }, { "code": null, "e": 2265, "s": 2251, "text": "linux-command" }, { "code": null, "e": 2272, "s": 2265, "text": "How To" }, { "code": null, "e": 2283, "s": 2272, "text": "Linux-Unix" } ]
Ruby | Enumerator each_with_object function
06 Jan, 2020 The each_with_object function in Ruby is used to Iterate the given object’s each element. Syntax: A.each_with_object({})Here, A is the initialised object. Parameters: This function does not accept any parameters. Returns: the new set of values. Example 1: # Calling the .each_with_object function on an array object[:gfg, :geeks, :geek].each_with_object({}) do |item, hash| # Converting the array elements into its uppercase hash[item] = item.to_s.upcaseend Output: {:gfg=>"GFG", :geeks=>"GEEKS", :geek=>"GEEK"} Example 2: # Calling the .each_with_object function on a hash{ foo: 2, bar: 4, jazz: 6 }.each_with_object({}) do |(key, value), hash| # Getting the square of the hash's value hash[key] = value**2end Output: {:foo=>4, :bar=>16, :jazz=>36} Ruby Enumerable-class Ruby-Methods Ruby Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Ruby | Array sample() function Instance Variables in Ruby Ruby | String empty? Method Ruby | String concat Method Ruby | unless Statement and unless Modifier Ruby | Hash key() function Ruby Integer times function with example Ruby | Operators Lambda Function - Ruby Ruby | String reverse Method
[ { "code": null, "e": 28, "s": 0, "text": "\n06 Jan, 2020" }, { "code": null, "e": 118, "s": 28, "text": "The each_with_object function in Ruby is used to Iterate the given object’s each element." }, { "code": null, "e": 183, "s": 118, "text": "Syntax: A.each_with_object({})Here, A is the initialised object." }, { "code": null, "e": 241, "s": 183, "text": "Parameters: This function does not accept any parameters." }, { "code": null, "e": 273, "s": 241, "text": "Returns: the new set of values." }, { "code": null, "e": 284, "s": 273, "text": "Example 1:" }, { "code": "# Calling the .each_with_object function on an array object[:gfg, :geeks, :geek].each_with_object({}) do |item, hash| # Converting the array elements into its uppercase hash[item] = item.to_s.upcaseend", "e": 488, "s": 284, "text": null }, { "code": null, "e": 496, "s": 488, "text": "Output:" }, { "code": null, "e": 542, "s": 496, "text": "{:gfg=>\"GFG\", :geeks=>\"GEEKS\", :geek=>\"GEEK\"}" }, { "code": null, "e": 553, "s": 542, "text": "Example 2:" }, { "code": "# Calling the .each_with_object function on a hash{ foo: 2, bar: 4, jazz: 6 }.each_with_object({}) do |(key, value), hash| # Getting the square of the hash's value hash[key] = value**2end", "e": 743, "s": 553, "text": null }, { "code": null, "e": 751, "s": 743, "text": "Output:" }, { "code": null, "e": 783, "s": 751, "text": "{:foo=>4, :bar=>16, :jazz=>36}\n" }, { "code": null, "e": 805, "s": 783, "text": "Ruby Enumerable-class" }, { "code": null, "e": 818, "s": 805, "text": "Ruby-Methods" }, { "code": null, "e": 823, "s": 818, "text": "Ruby" }, { "code": null, "e": 921, "s": 823, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 952, "s": 921, "text": "Ruby | Array sample() function" }, { "code": null, "e": 979, "s": 952, "text": "Instance Variables in Ruby" }, { "code": null, "e": 1007, "s": 979, "text": "Ruby | String empty? Method" }, { "code": null, "e": 1035, "s": 1007, "text": "Ruby | String concat Method" }, { "code": null, "e": 1079, "s": 1035, "text": "Ruby | unless Statement and unless Modifier" }, { "code": null, "e": 1106, "s": 1079, "text": "Ruby | Hash key() function" }, { "code": null, "e": 1147, "s": 1106, "text": "Ruby Integer times function with example" }, { "code": null, "e": 1164, "s": 1147, "text": "Ruby | Operators" }, { "code": null, "e": 1187, "s": 1164, "text": "Lambda Function - Ruby" } ]
SELECT increment counter in MySQL?
To select increment counter in MySQL, first you need to declare and initialize a variable. The syntax is as follows − set @anyVariableName=0; select yourColumnName, @anyVariableName:=@anyVariableName+1 as anyVariableName from yourTableName; To understand the above syntax and set an increment counter, let us first create a table. The query to create a table is as follows. mysql> create table incrementCounterDemo -> ( -> Name varchar(100) -> ); Query OK, 0 rows affected (1.01 sec) Insert some records in the table using insert command. The query is as follows. mysql> insert into incrementCounterDemo values('John'); Query OK, 1 row affected (0.18 sec) mysql> insert into incrementCounterDemo values('Carol'); Query OK, 1 row affected (0.20 sec) mysql> insert into incrementCounterDemo values('David'); Query OK, 1 row affected (0.14 sec) mysql> insert into incrementCounterDemo values('Mike'); Query OK, 1 row affected (0.21 sec) mysql> insert into incrementCounterDemo values('Bob'); Query OK, 1 row affected (0.12 sec) mysql> insert into incrementCounterDemo values('Sam'); Query OK, 1 row affected (0.16 sec) Display all records from the table using select statement. The query is as follows − mysql> select *from incrementCounterDemo; The following is the output. +-------+ | Name | +-------+ | John | | Carol | | David | | Mike | | Bob | | Sam | +-------+ 6 rows in set (0.00 sec) mysql> set @counter=0; Query OK, 0 rows affected (0.00 sec) Now select the increment counter. mysql> select Name, -> @counter:=@counter+1 as IncrementingValuebyOne -> from incrementCounterDemo; The following is the output. +-------+------------------------+ | Name | IncrementingValuebyOne | +-------+------------------------+ | John | 1 | | Carol | 2 | | David | 3 | | Mike | 4 | | Bob | 5 | | Sam | 6 | +-------+------------------------+ 6 rows in set (0.00 sec)
[ { "code": null, "e": 1305, "s": 1187, "text": "To select increment counter in MySQL, first you need to declare and initialize a variable. The syntax is as follows −" }, { "code": null, "e": 1428, "s": 1305, "text": "set @anyVariableName=0;\nselect yourColumnName,\n@anyVariableName:=@anyVariableName+1 as anyVariableName\nfrom yourTableName;" }, { "code": null, "e": 1561, "s": 1428, "text": "To understand the above syntax and set an increment counter, let us first create a table. The query to create a table is as follows." }, { "code": null, "e": 1671, "s": 1561, "text": "mysql> create table incrementCounterDemo\n-> (\n-> Name varchar(100)\n-> );\nQuery OK, 0 rows affected (1.01 sec)" }, { "code": null, "e": 1751, "s": 1671, "text": "Insert some records in the table using insert command. The query is as follows." }, { "code": null, "e": 2308, "s": 1751, "text": "mysql> insert into incrementCounterDemo values('John');\nQuery OK, 1 row affected (0.18 sec)\n\nmysql> insert into incrementCounterDemo values('Carol');\nQuery OK, 1 row affected (0.20 sec)\n\nmysql> insert into incrementCounterDemo values('David');\nQuery OK, 1 row affected (0.14 sec)\n\nmysql> insert into incrementCounterDemo values('Mike');\nQuery OK, 1 row affected (0.21 sec)\n\nmysql> insert into incrementCounterDemo values('Bob');\nQuery OK, 1 row affected (0.12 sec)\n\nmysql> insert into incrementCounterDemo values('Sam');\nQuery OK, 1 row affected (0.16 sec)" }, { "code": null, "e": 2393, "s": 2308, "text": "Display all records from the table using select statement. The query is as follows −" }, { "code": null, "e": 2435, "s": 2393, "text": "mysql> select *from incrementCounterDemo;" }, { "code": null, "e": 2464, "s": 2435, "text": "The following is the output." }, { "code": null, "e": 2589, "s": 2464, "text": "+-------+\n| Name |\n+-------+\n| John |\n| Carol |\n| David |\n| Mike |\n| Bob |\n| Sam |\n+-------+\n6 rows in set (0.00 sec)" }, { "code": null, "e": 2649, "s": 2589, "text": "mysql> set @counter=0;\nQuery OK, 0 rows affected (0.00 sec)" }, { "code": null, "e": 2683, "s": 2649, "text": "Now select the increment counter." }, { "code": null, "e": 2783, "s": 2683, "text": "mysql> select Name,\n-> @counter:=@counter+1 as IncrementingValuebyOne\n-> from incrementCounterDemo;" }, { "code": null, "e": 2812, "s": 2783, "text": "The following is the output." }, { "code": null, "e": 3187, "s": 2812, "text": "+-------+------------------------+\n| Name | IncrementingValuebyOne |\n+-------+------------------------+\n| John | 1 |\n| Carol | 2 |\n| David | 3 |\n| Mike | 4 |\n| Bob | 5 |\n| Sam | 6 |\n+-------+------------------------+\n6 rows in set (0.00 sec)" } ]
Java tricks for competitive programming (for Java 8)
10 May, 2022 Although the practice is the only way that ensures increased performance in programming contests but having some tricks up your sleeve ensures an upper edge and fast debugging.1) Checking if the number is even or odd without using the % operator: Although this trick is not much better than using a % operator but is sometimes efficient (with large numbers). Use & operator: System.out.println((a & 1) == 0 ? "EVEN" : "ODD" ); Example: num = 5 Binary: "101 & 1" will be 001, so false num = 4 Binary: "100 & 1" will be 000, so true. 2) Fast Multiplication or Division by 2 Multiplying by 2 means shifting all the bits to left and dividing by 2 means shifting to the right. Example: 2 (Binary 10): shifting left 4 (Binary 100) and right 1 (Binary 1) n = n << 1; // Multiply n with 2 n = n >> 1; // Divide n by 2 3) Swapping of 2 numbers using XOR: This method is fast and doesn’t require the use of the 3rd variable. // A quick way to swap a and b a ^= b; b ^= a; a ^= b; 4) Faster I/O: Refer here for Fast I/O in java 5) For String manipulations: Use StringBuffer for string manipulations, as String in java is immutable. Refer here. 6) Calculating the most significant digit: To calculate the most significant digit of any number log can be directly used to calculate it. Suppose the number is N then Let double K = Math.log10(N); now K = K - Math.floor(K); int X = (int)Math.pow(10, K); X will be the most significant digit. 7) Calculating the number of digits directly: To calculate the number of digits in a number, instead of looping we can efficiently use log : No. of digits in N = Math.floor(Math.log10(N)) + 1; 8) Inbuilt GCD Method: Java has inbuilt GCD method in BigInteger class. It returns a BigInteger whose value is the greatest common divisor of abs(this) and abs(val). Returns 0 if this==0 && val==0. Syntax : public BigInteger gcd(BigInteger val) Parameters : val - value with which the GCD is to be computed. Returns : GCD(abs(this), abs(val)) Below is the implementation of GCD: Java // Java program to demonstrate how// to use gcd method of BigInteger class import java.math.BigInteger; class Test { public static int gcd(int a, int b) { BigInteger b1 = BigInteger.valueOf(a); BigInteger b2 = BigInteger.valueOf(b); BigInteger gcd = b1.gcd(b2); return gcd.intValue(); } public static long gcd(long a, long b) { BigInteger b1 = BigInteger.valueOf(a); BigInteger b2 = BigInteger.valueOf(b); BigInteger gcd = b1.gcd(b2); return gcd.longValue(); } // Driver method public static void main(String[] args) { System.out.println(gcd(3, 5)); System.out.println(gcd(10000000000L, 600000000L)); }} 1 200000000 9) checking for a prime number: Java has an inbuilt isProbablePrime() method in BigInteger class. It returns true if this BigInteger is probably prime(with some certainty), false if it’s definitely composite. BigInteger.valueOf(1235).isProbablePrime(1) 10) Efficient trick to know if a number is a power of 2: The normal technique of division the complexity comes out to be O(logN), but it can be solved using O(v) where v is the number of digits of the number in binary form. Java /* Method to check if x is power of 2*/static boolean isPowerOfTwo (int x){ /* First x in the below expression is for the case when x is 0 */ return x!=0 && ((x&(x-1)) == 0); } 11) Sorting Algorithm: Arrays.sort() used to sort elements of an array. Collections.sort() used to sort elements of a collection. Arrays.sort() used to sort elements of an array. Collections.sort() used to sort elements of a collection. For primitives, Arrays.sort() uses dual pivot quicksort algorithms. 12) Searching Algorithm: Arrays.binarySearch()(SET 1 | SET2) used to apply binary search on a sorted array. Collections.binarySearch() used to apply binary search on a collection based on comparators. Arrays.binarySearch()(SET 1 | SET2) used to apply binary search on a sorted array. Collections.binarySearch() used to apply binary search on a collection based on comparators. 13) Copy Algorithm: Arrays.copyOf() and copyOfRange() copy the specified array. Collections.copy() copies specified collection. Arrays.copyOf() and copyOfRange() copy the specified array. Collections.copy() copies specified collection. 14) Rotation and Frequency We can use Collections.rotate() to rotate a collection or an array by a specified distance. You can also use Collections.frequency() method to get the frequency of a specified element in a collection or an array. 15) Most data structures are already implemented in the Collections Framework. For example Stack, LinkedList, HashSet, HashMaps, Heaps etc. 16) Use Wrapper class functions for getting radix conversions of a number Sometimes you require radix conversion of a number. For this, you can use wrapper classes. Java // Java program to demonstrate use of wrapper// classes for radix conversion class Test { // Driver method public static void main(String[] args) { int a = 525; long b = 12456545645L; String binaryA = Integer.toString(a, 2); System.out.println("Binary representation" + " of A : " + binaryA); String binaryB = Long.toString(b, 2); System.out.println("Binary representation" + " of B : " + binaryB); String octalA = Integer.toString(a, 8); System.out.println("Octal representation" + " of A : " + octalA); String octalB = Long.toString(b, 8); System.out.println("Octal representation" + " of B : " + octalB); }} Binary representation of A : 1000001101 Binary representation of B : 1011100110011101111100110101101101 Octal representation of A : 1015 Octal representation of B : 134635746555 17) NullPointerException(Why ?) Refer here and here to avoid it. This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. debojitbanerjee546 Java-Competitive-Programming Competitive Programming Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Modulo 10^9+7 (1000000007) Prefix Sum Array - Implementation and Applications in Competitive Programming Bits manipulation (Important tactics) What is Competitive Programming and How to Prepare for It? Algorithm Library | C++ Magicians STL Algorithm Arrays.sort() in Java with examples Object Oriented Programming (OOPs) Concept in Java Reverse a string in Java For-each loop in Java How to iterate any Map in Java
[ { "code": null, "e": 52, "s": 24, "text": "\n10 May, 2022" }, { "code": null, "e": 412, "s": 52, "text": "Although the practice is the only way that ensures increased performance in programming contests but having some tricks up your sleeve ensures an upper edge and fast debugging.1) Checking if the number is even or odd without using the % operator: Although this trick is not much better than using a % operator but is sometimes efficient (with large numbers). " }, { "code": null, "e": 428, "s": 412, "text": "Use & operator:" }, { "code": null, "e": 481, "s": 428, "text": "System.out.println((a & 1) == 0 ? \"EVEN\" : \"ODD\" );" }, { "code": null, "e": 491, "s": 481, "text": "Example: " }, { "code": null, "e": 591, "s": 491, "text": "num = 5 \nBinary: \"101 & 1\" will be 001, so false \n\nnum = 4 \nBinary: \"100 & 1\" will be 000, so true." }, { "code": null, "e": 632, "s": 591, "text": "2) Fast Multiplication or Division by 2 " }, { "code": null, "e": 732, "s": 632, "text": "Multiplying by 2 means shifting all the bits to left and dividing by 2 means shifting to the right." }, { "code": null, "e": 808, "s": 732, "text": "Example: 2 (Binary 10): shifting left 4 (Binary 100) and right 1 (Binary 1)" }, { "code": null, "e": 874, "s": 808, "text": "n = n << 1; // Multiply n with 2\nn = n >> 1; // Divide n by 2" }, { "code": null, "e": 911, "s": 874, "text": "3) Swapping of 2 numbers using XOR: " }, { "code": null, "e": 980, "s": 911, "text": "This method is fast and doesn’t require the use of the 3rd variable." }, { "code": null, "e": 1044, "s": 980, "text": " // A quick way to swap a and b\n a ^= b;\n b ^= a;\n a ^= b; " }, { "code": null, "e": 1060, "s": 1044, "text": "4) Faster I/O: " }, { "code": null, "e": 1092, "s": 1060, "text": "Refer here for Fast I/O in java" }, { "code": null, "e": 1122, "s": 1092, "text": "5) For String manipulations: " }, { "code": null, "e": 1209, "s": 1122, "text": "Use StringBuffer for string manipulations, as String in java is immutable. Refer here." }, { "code": null, "e": 1253, "s": 1209, "text": "6) Calculating the most significant digit: " }, { "code": null, "e": 1350, "s": 1253, "text": "To calculate the most significant digit of any number log can be directly used to calculate it. " }, { "code": null, "e": 1506, "s": 1350, "text": "Suppose the number is N then \nLet double K = Math.log10(N);\nnow K = K - Math.floor(K);\nint X = (int)Math.pow(10, K);\nX will be the most significant digit. " }, { "code": null, "e": 1552, "s": 1506, "text": "7) Calculating the number of digits directly:" }, { "code": null, "e": 1648, "s": 1552, "text": "To calculate the number of digits in a number, instead of looping we can efficiently use log : " }, { "code": null, "e": 1700, "s": 1648, "text": "No. of digits in N = Math.floor(Math.log10(N)) + 1;" }, { "code": null, "e": 1724, "s": 1700, "text": "8) Inbuilt GCD Method: " }, { "code": null, "e": 1900, "s": 1724, "text": "Java has inbuilt GCD method in BigInteger class. It returns a BigInteger whose value is the greatest common divisor of abs(this) and abs(val). Returns 0 if this==0 && val==0. " }, { "code": null, "e": 1910, "s": 1900, "text": "Syntax : " }, { "code": null, "e": 2046, "s": 1910, "text": "public BigInteger gcd(BigInteger val)\nParameters :\nval - value with which the GCD is to be computed.\nReturns :\nGCD(abs(this), abs(val))" }, { "code": null, "e": 2084, "s": 2046, "text": " Below is the implementation of GCD: " }, { "code": null, "e": 2089, "s": 2084, "text": "Java" }, { "code": "// Java program to demonstrate how// to use gcd method of BigInteger class import java.math.BigInteger; class Test { public static int gcd(int a, int b) { BigInteger b1 = BigInteger.valueOf(a); BigInteger b2 = BigInteger.valueOf(b); BigInteger gcd = b1.gcd(b2); return gcd.intValue(); } public static long gcd(long a, long b) { BigInteger b1 = BigInteger.valueOf(a); BigInteger b2 = BigInteger.valueOf(b); BigInteger gcd = b1.gcd(b2); return gcd.longValue(); } // Driver method public static void main(String[] args) { System.out.println(gcd(3, 5)); System.out.println(gcd(10000000000L, 600000000L)); }}", "e": 2799, "s": 2089, "text": null }, { "code": null, "e": 2812, "s": 2799, "text": "1\n200000000\n" }, { "code": null, "e": 2845, "s": 2812, "text": "9) checking for a prime number: " }, { "code": null, "e": 3023, "s": 2845, "text": "Java has an inbuilt isProbablePrime() method in BigInteger class. It returns true if this BigInteger is probably prime(with some certainty), false if it’s definitely composite. " }, { "code": null, "e": 3068, "s": 3023, "text": "BigInteger.valueOf(1235).isProbablePrime(1) " }, { "code": null, "e": 3125, "s": 3068, "text": "10) Efficient trick to know if a number is a power of 2:" }, { "code": null, "e": 3294, "s": 3125, "text": "The normal technique of division the complexity comes out to be O(logN), but it can be solved using O(v) where v is the number of digits of the number in binary form. " }, { "code": null, "e": 3299, "s": 3294, "text": "Java" }, { "code": "/* Method to check if x is power of 2*/static boolean isPowerOfTwo (int x){ /* First x in the below expression is for the case when x is 0 */ return x!=0 && ((x&(x-1)) == 0); }", "e": 3493, "s": 3299, "text": null }, { "code": null, "e": 3519, "s": 3495, "text": "11) Sorting Algorithm: " }, { "code": null, "e": 3626, "s": 3519, "text": "Arrays.sort() used to sort elements of an array. Collections.sort() used to sort elements of a collection." }, { "code": null, "e": 3676, "s": 3626, "text": "Arrays.sort() used to sort elements of an array. " }, { "code": null, "e": 3734, "s": 3676, "text": "Collections.sort() used to sort elements of a collection." }, { "code": null, "e": 3802, "s": 3734, "text": "For primitives, Arrays.sort() uses dual pivot quicksort algorithms." }, { "code": null, "e": 3828, "s": 3802, "text": "12) Searching Algorithm: " }, { "code": null, "e": 4004, "s": 3828, "text": "Arrays.binarySearch()(SET 1 | SET2) used to apply binary search on a sorted array. Collections.binarySearch() used to apply binary search on a collection based on comparators." }, { "code": null, "e": 4088, "s": 4004, "text": "Arrays.binarySearch()(SET 1 | SET2) used to apply binary search on a sorted array. " }, { "code": null, "e": 4181, "s": 4088, "text": "Collections.binarySearch() used to apply binary search on a collection based on comparators." }, { "code": null, "e": 4202, "s": 4181, "text": "13) Copy Algorithm: " }, { "code": null, "e": 4310, "s": 4202, "text": "Arrays.copyOf() and copyOfRange() copy the specified array. Collections.copy() copies specified collection." }, { "code": null, "e": 4371, "s": 4310, "text": "Arrays.copyOf() and copyOfRange() copy the specified array. " }, { "code": null, "e": 4419, "s": 4371, "text": "Collections.copy() copies specified collection." }, { "code": null, "e": 4447, "s": 4419, "text": "14) Rotation and Frequency " }, { "code": null, "e": 4660, "s": 4447, "text": "We can use Collections.rotate() to rotate a collection or an array by a specified distance. You can also use Collections.frequency() method to get the frequency of a specified element in a collection or an array." }, { "code": null, "e": 4739, "s": 4660, "text": "15) Most data structures are already implemented in the Collections Framework." }, { "code": null, "e": 4800, "s": 4739, "text": "For example Stack, LinkedList, HashSet, HashMaps, Heaps etc." }, { "code": null, "e": 4966, "s": 4800, "text": "16) Use Wrapper class functions for getting radix conversions of a number Sometimes you require radix conversion of a number. For this, you can use wrapper classes. " }, { "code": null, "e": 4971, "s": 4966, "text": "Java" }, { "code": "// Java program to demonstrate use of wrapper// classes for radix conversion class Test { // Driver method public static void main(String[] args) { int a = 525; long b = 12456545645L; String binaryA = Integer.toString(a, 2); System.out.println(\"Binary representation\" + \" of A : \" + binaryA); String binaryB = Long.toString(b, 2); System.out.println(\"Binary representation\" + \" of B : \" + binaryB); String octalA = Integer.toString(a, 8); System.out.println(\"Octal representation\" + \" of A : \" + octalA); String octalB = Long.toString(b, 8); System.out.println(\"Octal representation\" + \" of B : \" + octalB); }}", "e": 5771, "s": 4971, "text": null }, { "code": null, "e": 5950, "s": 5771, "text": "Binary representation of A : 1000001101\nBinary representation of B : 1011100110011101111100110101101101\nOctal representation of A : 1015\nOctal representation of B : 134635746555\n" }, { "code": null, "e": 6015, "s": 5950, "text": "17) NullPointerException(Why ?) Refer here and here to avoid it." }, { "code": null, "e": 6438, "s": 6015, "text": "This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 6457, "s": 6438, "text": "debojitbanerjee546" }, { "code": null, "e": 6486, "s": 6457, "text": "Java-Competitive-Programming" }, { "code": null, "e": 6510, "s": 6486, "text": "Competitive Programming" }, { "code": null, "e": 6515, "s": 6510, "text": "Java" }, { "code": null, "e": 6520, "s": 6515, "text": "Java" }, { "code": null, "e": 6618, "s": 6520, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6645, "s": 6618, "text": "Modulo 10^9+7 (1000000007)" }, { "code": null, "e": 6723, "s": 6645, "text": "Prefix Sum Array - Implementation and Applications in Competitive Programming" }, { "code": null, "e": 6761, "s": 6723, "text": "Bits manipulation (Important tactics)" }, { "code": null, "e": 6820, "s": 6761, "text": "What is Competitive Programming and How to Prepare for It?" }, { "code": null, "e": 6868, "s": 6820, "text": "Algorithm Library | C++ Magicians STL Algorithm" }, { "code": null, "e": 6904, "s": 6868, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 6955, "s": 6904, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 6980, "s": 6955, "text": "Reverse a string in Java" }, { "code": null, "e": 7002, "s": 6980, "text": "For-each loop in Java" } ]
What is the primary difference between the XPath and CSS selector in Selenium?
There are some differences between the xpath and css selector. The format of xpath is //tagname[@attribute='value'] while the format of css selector is tagname[attribute='value']. We can traverse both forward and backward in DOM, i.e we can move from parent to child element and also from child to the parent element with xpath. However for css, we can only traverse from parent to child and not vice-versa. In terms of performance, css is better and faster, while xpath is on a slower side. An xpath can be of two types – absolute which starts from the root node and relative does not require to be started from the root. To traverse to the nth element, we have to mention [n] in the xpath, where n is the index number. For css, we have to mention nth-of-type(n). For example, to get hold of the second li child of the parent ul, the css expression shall be ul li:nth-of-type(2). While xpath shall be ul/li[2]. We can create an xpath with the help of the visible text on the element by using the text() function, for example, //*[text()='Home'], which will identify the element having the text Home displayed on the page. This feature is not available in css. We have the starts-with() function in xpath which is used to identify an element whose attribute value begins with a specific text. To deal with a similar scenario in css, we have to use the ^= symbol. For example in css, input[title^='qa'] For example in xpath, //input[starts-with(@title, 'qa')]. [here input is the tagname and the value of the title attribute starts with qa]. We have the contains() function in xpath which is used to identify an element whose attribute value contains a partial text. To deal with a similar scenario in css, we use the *= symbol For example in css, input[title*='nam'] For example in xpath, //input[contains(@title, 'nam')]. [here input is the tagname and the value of the title attribute contains nam]. With attribute id, css expression should be tagname#id. For example, input#loc [here input is the tagname and the loc is the value of the id attribute]. This rule does not apply to xpath. With attribute class, css expression should be tagname.class attribute value. For example, input.xt [here input is the tagname and the xt is the value of the class attribute]. This rule does not apply to xpath. WebElement m = driver.findElement(By.xpath("//div[@class = 'loc']")); WebElement n = driver.findElement(By.cssSelector("div[class = 'loc']")); import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import java.util.concurrent.TimeUnit; public class LocatorXpathvsCss{ public static void main(String[] args) { System.setProperty("webdriver.gecko.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\geckodriver.exe"); WebDriver driver = new FirefoxDriver(); //implicit wait driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); //URL launch driver.get("https://www.tutorialspoint.com/online_dev_tools.htm"); // identify element with xpath WebElement m=driver.findElement(By.xpath("//span[@class = 'cat-title']")); String str = m.getText(); // identify element with css WebElement n=driver. findElement(By.cssSelector("div.cat-punch-line span")); String s = n.getText(); System.out.println("Text obtained from xpath : " + str); System.out.println("Text obtained from css : " + s); driver.quit(); } }
[ { "code": null, "e": 1367, "s": 1187, "text": "There are some differences between the xpath and css selector. The format of xpath is //tagname[@attribute='value'] while the format of css selector is tagname[attribute='value']." }, { "code": null, "e": 1595, "s": 1367, "text": "We can traverse both forward and backward in DOM, i.e we can move from parent to child element and also from child to the parent element with xpath. However for css, we can only traverse from parent to child and not vice-versa." }, { "code": null, "e": 1810, "s": 1595, "text": "In terms of performance, css is better and faster, while xpath is on a slower side. An xpath can be of two types – absolute which starts from the root node and relative does not require to be started from the root." }, { "code": null, "e": 2099, "s": 1810, "text": "To traverse to the nth element, we have to mention [n] in the xpath, where n is the index number. For css, we have to mention nth-of-type(n). For example, to get hold of the second li child of the parent ul, the css expression shall be ul li:nth-of-type(2). While xpath shall be ul/li[2]." }, { "code": null, "e": 2348, "s": 2099, "text": "We can create an xpath with the help of the visible text on the element by using the text() function, for example, //*[text()='Home'], which will identify the element having the text Home displayed on the page. This feature is not available in css." }, { "code": null, "e": 2550, "s": 2348, "text": "We have the starts-with() function in xpath which is used to identify an element whose attribute value begins with a specific text. To deal with a similar scenario in css, we have to use the ^= symbol." }, { "code": null, "e": 2570, "s": 2550, "text": "For example in css," }, { "code": null, "e": 2589, "s": 2570, "text": "input[title^='qa']" }, { "code": null, "e": 2611, "s": 2589, "text": "For example in xpath," }, { "code": null, "e": 2647, "s": 2611, "text": "//input[starts-with(@title, 'qa')]." }, { "code": null, "e": 2728, "s": 2647, "text": "[here input is the tagname and the value of the title attribute starts with qa]." }, { "code": null, "e": 2914, "s": 2728, "text": "We have the contains() function in xpath which is used to identify an element whose attribute value contains a partial text. To deal with a similar scenario in css, we use the *= symbol" }, { "code": null, "e": 2934, "s": 2914, "text": "For example in css," }, { "code": null, "e": 2954, "s": 2934, "text": "input[title*='nam']" }, { "code": null, "e": 2976, "s": 2954, "text": "For example in xpath," }, { "code": null, "e": 3010, "s": 2976, "text": "//input[contains(@title, 'nam')]." }, { "code": null, "e": 3089, "s": 3010, "text": "[here input is the tagname and the value of the title attribute contains nam]." }, { "code": null, "e": 3277, "s": 3089, "text": "With attribute id, css expression should be tagname#id. For example, input#loc [here input is the tagname and the loc is the value of the id attribute]. This rule does not apply to xpath." }, { "code": null, "e": 3488, "s": 3277, "text": "With attribute class, css expression should be tagname.class attribute value. For example, input.xt [here input is the tagname and the xt is the value of the class attribute]. This rule does not apply to xpath." }, { "code": null, "e": 3631, "s": 3488, "text": "WebElement m = driver.findElement(By.xpath(\"//div[@class = 'loc']\"));\nWebElement n = driver.findElement(By.cssSelector(\"div[class = 'loc']\"));" }, { "code": null, "e": 4702, "s": 3631, "text": "import org.openqa.selenium.By;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.firefox.FirefoxDriver;\nimport java.util.concurrent.TimeUnit;\npublic class LocatorXpathvsCss{\n public static void main(String[] args) {\n System.setProperty(\"webdriver.gecko.driver\",\n \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\geckodriver.exe\");\n WebDriver driver = new FirefoxDriver();\n //implicit wait\n driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);\n //URL launch\n driver.get(\"https://www.tutorialspoint.com/online_dev_tools.htm\");\n // identify element with xpath\n WebElement m=driver.findElement(By.xpath(\"//span[@class = 'cat-title']\"));\n String str = m.getText();\n // identify element with css\n WebElement n=driver.\n findElement(By.cssSelector(\"div.cat-punch-line span\"));\n String s = n.getText();\n System.out.println(\"Text obtained from xpath : \" + str);\n System.out.println(\"Text obtained from css : \" + s);\n driver.quit();\n }\n}" } ]
Vue.js v-once Directive
14 Jul, 2020 The v-once directive is a Vue.js directive that is used to avoid unwanted re-renders of an element. It treats the element as a static content after rendering it once for the first time. This improves performance as it does not have to be rendered again. First, we will create a div element with the id of choice. The v-once directive is then applied to this element to make it render only once. Syntax: v-once Parameters: This function does not accept any parameter. Example: This example uses Vue.js to show the working of the data with v-once. <!DOCTYPE html><html> <head> <title> VueJS v-once Directive </title> <!-- Load Vuejs --> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"> </script></head> <body> <div style="text-align: center; width: 600px;"> <h1 style="color: green;"> GeeksforGeeks </h1> <b> VueJS | v-once directive </b> </div> <div id="canvas" style= "border: 1px solid #000000; width: 600px; height: 200px;"> <div id="app" style="text-align: center; padding-top: 40px;"> <h1 v-once>{{ data }}</h1> </div> </div> <script> var app = new Vue({ el: '#app', data: { data: 'GeeksforGeeks' } }) </script></body> </html> Output: Vue.JS JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Remove elements from a JavaScript Array Difference Between PUT and PATCH Request Roadmap to Learn JavaScript For Beginners JavaScript | Promises Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n14 Jul, 2020" }, { "code": null, "e": 423, "s": 28, "text": "The v-once directive is a Vue.js directive that is used to avoid unwanted re-renders of an element. It treats the element as a static content after rendering it once for the first time. This improves performance as it does not have to be rendered again. First, we will create a div element with the id of choice. The v-once directive is then applied to this element to make it render only once." }, { "code": null, "e": 431, "s": 423, "text": "Syntax:" }, { "code": null, "e": 438, "s": 431, "text": "v-once" }, { "code": null, "e": 495, "s": 438, "text": "Parameters: This function does not accept any parameter." }, { "code": null, "e": 574, "s": 495, "text": "Example: This example uses Vue.js to show the working of the data with v-once." }, { "code": "<!DOCTYPE html><html> <head> <title> VueJS v-once Directive </title> <!-- Load Vuejs --> <script src=\"https://cdn.jsdelivr.net/npm/vue/dist/vue.js\"> </script></head> <body> <div style=\"text-align: center; width: 600px;\"> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <b> VueJS | v-once directive </b> </div> <div id=\"canvas\" style= \"border: 1px solid #000000; width: 600px; height: 200px;\"> <div id=\"app\" style=\"text-align: center; padding-top: 40px;\"> <h1 v-once>{{ data }}</h1> </div> </div> <script> var app = new Vue({ el: '#app', data: { data: 'GeeksforGeeks' } }) </script></body> </html>", "e": 1398, "s": 574, "text": null }, { "code": null, "e": 1406, "s": 1398, "text": "Output:" }, { "code": null, "e": 1413, "s": 1406, "text": "Vue.JS" }, { "code": null, "e": 1424, "s": 1413, "text": "JavaScript" }, { "code": null, "e": 1441, "s": 1424, "text": "Web Technologies" }, { "code": null, "e": 1539, "s": 1441, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1600, "s": 1539, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 1640, "s": 1600, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 1681, "s": 1640, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 1723, "s": 1681, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 1745, "s": 1723, "text": "JavaScript | Promises" }, { "code": null, "e": 1778, "s": 1745, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 1840, "s": 1778, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 1901, "s": 1840, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 1951, "s": 1901, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Label-based indexing to the Pandas DataFrame
25 Oct, 2020 Indexing plays an important role in data frames. Sometimes we need to give a label-based “fancy indexing” to the Pandas Data frame. For this, we have a function in pandas known as pandas.DataFrame.lookup(). The concept of Fancy Indexing is simple which means, we have to pass an array of indices to access multiple array elements at once. pandas.DataFrame.lookup() function takes equal-length arrays of row and column labels as its attributes and returns an array of the values corresponding to each (row, col) pair. Syntax: DataFrame.lookup(row_labels, col_labels) Parameters:row_labels – The row labels to use for lookup.col_labels – The column labels to use for lookup. Returns:numpy.ndarray Example 1: Python3 # importing pandas libraryimport pandas as pd # Creating a Data framedf = pd.DataFrame([['1993', 'x', 5, 4, 7, 2], ['1994', 'v', 10, 1, 2, 0], ['1995', 'z', 2, 1, 4, 12], ['1996', 'y', 2, 1, 10, 1], ['1998', 'x', 2, 10, 40, 12], ['1999', 'x', 5, 8, 11, 6]], columns=('Year', 'Alpha', 'x', 'y', 'z', 'v')) # Display Data framedf Output: Python3 # Use concept of fancy indexing to make new # column 'Value' in data frame # with help of dataframe.lookup() functiondf['Value'] = df.lookup(df.index, df['Alpha']) # Modified Data framedf Output: In the above example, we use the concept of label based Fancy Indexing to access multiple elements of data frame at once and hence create a new column ‘Value‘ using function dataframe.lookup() Example 2: Python3 # importing pandas libraryimport pandas as pd # Creating a Data framedf = pd.DataFrame([['1993', 'Avi', 5, 41, 70, 'Bob'], ['1994', 'Cathy', 10, 1, 22, 'Cathy'], ['1995', 'Cathy', 24, 11, 44, 'Bob'], ['1996', 'Bob', 2, 11, 10, 'Avi'], ['1998', 'Avi', 20, 10, 40, 'Avi'], ['1999', 'Avi', 50, 8, 11, 'Cathy']], columns=('Patients', 'Name', 'Avi', 'Bob', 'Cathy', 'Aname')) # Display Data framedf Output: Python3 # Use concept of fancy indexing to make two# new columns in data frame with help of# dataframe.lookup() functiondf['Age'] = df.lookup(df.index, df['Name'])df['Marks'] = df.lookup(df.index, df['Aname']) # Modified Data framedf Output: In the above example, we use the concept of label based Fancy Indexing to access multiple elements of data frame at once and hence create two new columns ‘Age‘ and ‘Marks‘ using function dataframe.lookup() Example 3: Python3 # importing pandas libraryimport pandas as pd # Creating a Data framedf = pd.DataFrame([['Date1', 1850, 1992,'Avi', 5, 41, 70, 'Avi'], ['Date2', 1896, 1950, 'Cathy', 10, 1, 22, 'Avi'], ['Date2', 1900, 1920, 'Cathy', 24, 11, 44, 'Cathy'], ['Date1', 1889, 1960, 'Bob', 2, 11, 10, 'Bob'], ['Date2', 1910, 1952, 'Avi', 20, 10, 40, 'Bob'], ['Date1', 1999, 1929, 'Avi', 50, 8, 11, 'Cathy']], columns=('Year', 'Date1', 'Date2', 'Name', 'Avi', 'Bob', 'Cathy', 'Alpha')) # Display Data framedf Output: Python3 # Use concept of fancy indexing to make two # three columns in data frame with help of# dataframe.lookup() functiondf['Age'] = df.lookup(df.index, df['Name'])df['Height'] = df.lookup(df.index, df['Alpha'])df['Date_of_Birth'] = df.lookup(df.index, df['Year']) # Modified Data framedf Output: In the above example, we use the concept of label based Fancy Indexing to access multiple elements of the data frame at once and hence create two new columns ‘Age‘, ‘Height‘ and ‘Date_of_Birth‘ using function dataframe.lookup() All three examples show how fancy indexing works and how we can create new columns using fancy indexing along with the dataframe.lookup() function. Python pandas-dataFrame Python pandas-indexing Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Convert integer to string in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n25 Oct, 2020" }, { "code": null, "e": 368, "s": 28, "text": "Indexing plays an important role in data frames. Sometimes we need to give a label-based “fancy indexing” to the Pandas Data frame. For this, we have a function in pandas known as pandas.DataFrame.lookup(). The concept of Fancy Indexing is simple which means, we have to pass an array of indices to access multiple array elements at once. " }, { "code": null, "e": 546, "s": 368, "text": "pandas.DataFrame.lookup() function takes equal-length arrays of row and column labels as its attributes and returns an array of the values corresponding to each (row, col) pair." }, { "code": null, "e": 595, "s": 546, "text": "Syntax: DataFrame.lookup(row_labels, col_labels)" }, { "code": null, "e": 702, "s": 595, "text": "Parameters:row_labels – The row labels to use for lookup.col_labels – The column labels to use for lookup." }, { "code": null, "e": 724, "s": 702, "text": "Returns:numpy.ndarray" }, { "code": null, "e": 735, "s": 724, "text": "Example 1:" }, { "code": null, "e": 743, "s": 735, "text": "Python3" }, { "code": "# importing pandas libraryimport pandas as pd # Creating a Data framedf = pd.DataFrame([['1993', 'x', 5, 4, 7, 2], ['1994', 'v', 10, 1, 2, 0], ['1995', 'z', 2, 1, 4, 12], ['1996', 'y', 2, 1, 10, 1], ['1998', 'x', 2, 10, 40, 12], ['1999', 'x', 5, 8, 11, 6]], columns=('Year', 'Alpha', 'x', 'y', 'z', 'v')) # Display Data framedf", "e": 1183, "s": 743, "text": null }, { "code": null, "e": 1191, "s": 1183, "text": "Output:" }, { "code": null, "e": 1199, "s": 1191, "text": "Python3" }, { "code": "# Use concept of fancy indexing to make new # column 'Value' in data frame # with help of dataframe.lookup() functiondf['Value'] = df.lookup(df.index, df['Alpha']) # Modified Data framedf", "e": 1388, "s": 1199, "text": null }, { "code": null, "e": 1396, "s": 1388, "text": "Output:" }, { "code": null, "e": 1589, "s": 1396, "text": "In the above example, we use the concept of label based Fancy Indexing to access multiple elements of data frame at once and hence create a new column ‘Value‘ using function dataframe.lookup()" }, { "code": null, "e": 1600, "s": 1589, "text": "Example 2:" }, { "code": null, "e": 1608, "s": 1600, "text": "Python3" }, { "code": "# importing pandas libraryimport pandas as pd # Creating a Data framedf = pd.DataFrame([['1993', 'Avi', 5, 41, 70, 'Bob'], ['1994', 'Cathy', 10, 1, 22, 'Cathy'], ['1995', 'Cathy', 24, 11, 44, 'Bob'], ['1996', 'Bob', 2, 11, 10, 'Avi'], ['1998', 'Avi', 20, 10, 40, 'Avi'], ['1999', 'Avi', 50, 8, 11, 'Cathy']], columns=('Patients', 'Name', 'Avi', 'Bob', 'Cathy', 'Aname')) # Display Data framedf", "e": 2115, "s": 1608, "text": null }, { "code": null, "e": 2123, "s": 2115, "text": "Output:" }, { "code": null, "e": 2131, "s": 2123, "text": "Python3" }, { "code": "# Use concept of fancy indexing to make two# new columns in data frame with help of# dataframe.lookup() functiondf['Age'] = df.lookup(df.index, df['Name'])df['Marks'] = df.lookup(df.index, df['Aname']) # Modified Data framedf", "e": 2358, "s": 2131, "text": null }, { "code": null, "e": 2366, "s": 2358, "text": "Output:" }, { "code": null, "e": 2572, "s": 2366, "text": "In the above example, we use the concept of label based Fancy Indexing to access multiple elements of data frame at once and hence create two new columns ‘Age‘ and ‘Marks‘ using function dataframe.lookup()" }, { "code": null, "e": 2583, "s": 2572, "text": "Example 3:" }, { "code": null, "e": 2591, "s": 2583, "text": "Python3" }, { "code": "# importing pandas libraryimport pandas as pd # Creating a Data framedf = pd.DataFrame([['Date1', 1850, 1992,'Avi', 5, 41, 70, 'Avi'], ['Date2', 1896, 1950, 'Cathy', 10, 1, 22, 'Avi'], ['Date2', 1900, 1920, 'Cathy', 24, 11, 44, 'Cathy'], ['Date1', 1889, 1960, 'Bob', 2, 11, 10, 'Bob'], ['Date2', 1910, 1952, 'Avi', 20, 10, 40, 'Bob'], ['Date1', 1999, 1929, 'Avi', 50, 8, 11, 'Cathy']], columns=('Year', 'Date1', 'Date2', 'Name', 'Avi', 'Bob', 'Cathy', 'Alpha')) # Display Data framedf", "e": 3216, "s": 2591, "text": null }, { "code": null, "e": 3224, "s": 3216, "text": "Output:" }, { "code": null, "e": 3232, "s": 3224, "text": "Python3" }, { "code": "# Use concept of fancy indexing to make two # three columns in data frame with help of# dataframe.lookup() functiondf['Age'] = df.lookup(df.index, df['Name'])df['Height'] = df.lookup(df.index, df['Alpha'])df['Date_of_Birth'] = df.lookup(df.index, df['Year']) # Modified Data framedf", "e": 3520, "s": 3232, "text": null }, { "code": null, "e": 3528, "s": 3520, "text": "Output:" }, { "code": null, "e": 3756, "s": 3528, "text": "In the above example, we use the concept of label based Fancy Indexing to access multiple elements of the data frame at once and hence create two new columns ‘Age‘, ‘Height‘ and ‘Date_of_Birth‘ using function dataframe.lookup()" }, { "code": null, "e": 3904, "s": 3756, "text": "All three examples show how fancy indexing works and how we can create new columns using fancy indexing along with the dataframe.lookup() function." }, { "code": null, "e": 3928, "s": 3904, "text": "Python pandas-dataFrame" }, { "code": null, "e": 3951, "s": 3928, "text": "Python pandas-indexing" }, { "code": null, "e": 3965, "s": 3951, "text": "Python-pandas" }, { "code": null, "e": 3972, "s": 3965, "text": "Python" }, { "code": null, "e": 4070, "s": 3972, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4088, "s": 4070, "text": "Python Dictionary" }, { "code": null, "e": 4130, "s": 4088, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 4152, "s": 4130, "text": "Enumerate() in Python" }, { "code": null, "e": 4187, "s": 4152, "text": "Read a file line by line in Python" }, { "code": null, "e": 4213, "s": 4187, "text": "Python String | replace()" }, { "code": null, "e": 4245, "s": 4213, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 4274, "s": 4245, "text": "*args and **kwargs in Python" }, { "code": null, "e": 4301, "s": 4274, "text": "Python Classes and Objects" }, { "code": null, "e": 4331, "s": 4301, "text": "Iterate over a list in Python" } ]
How to get the same value from another array and assign to object of arrays?
12 Mar, 2021 To get the same value from another array and insert it into an object of the array we need to. Compare each and every element of two arraysReturn the matched elementAdd the element or object into the object of array Compare each and every element of two arrays Return the matched element Add the element or object into the object of array Before jumping into the code, you can read the following articles. It will help you to understand it better, Array forEach() method Array push() method Array includes() method Array filter() method ES6 Arrow function Method 1: Using forEach() and push(), includes() method of array. Javascript <script> // Define first array let arr1 = [1, 2, 3, 4, 5, 77, 876, 453]; // Define second array let arr2 = [1, 2, 45, 4, 231, 453]; // Create a empty object of array let result = []; // Checked the matched element between two // array and add into result array arr1.forEach( val => arr2.includes(val) && result.push(val) ); // Print the result on console console.log( result );</script> Output: 1, 2, 4, 453 Method 2: filter(), push() and includes() of array. Javascript <script> // Define first array let arr1 = [1, 2, 3, 4, 5, 77, 876, 453]; // Define second array let arr2 = [1, 2, 45, 4, 231, 453]; / Checked the matched element between two array // and add into the result array let result = arr1.filter(val => arr2.includes(val) ); // Print the result on console console.log( result ); </script> Output: 1, 2, 4, 453 javascript-array JavaScript-Questions Picked Technical Scripter 2020 JavaScript Technical Scripter 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 Mar, 2021" }, { "code": null, "e": 123, "s": 28, "text": "To get the same value from another array and insert it into an object of the array we need to." }, { "code": null, "e": 244, "s": 123, "text": "Compare each and every element of two arraysReturn the matched elementAdd the element or object into the object of array" }, { "code": null, "e": 289, "s": 244, "text": "Compare each and every element of two arrays" }, { "code": null, "e": 316, "s": 289, "text": "Return the matched element" }, { "code": null, "e": 367, "s": 316, "text": "Add the element or object into the object of array" }, { "code": null, "e": 477, "s": 367, "text": "Before jumping into the code, you can read the following articles. It will help you to understand it better, " }, { "code": null, "e": 500, "s": 477, "text": "Array forEach() method" }, { "code": null, "e": 520, "s": 500, "text": "Array push() method" }, { "code": null, "e": 544, "s": 520, "text": "Array includes() method" }, { "code": null, "e": 566, "s": 544, "text": "Array filter() method" }, { "code": null, "e": 585, "s": 566, "text": "ES6 Arrow function" }, { "code": null, "e": 651, "s": 585, "text": "Method 1: Using forEach() and push(), includes() method of array." }, { "code": null, "e": 662, "s": 651, "text": "Javascript" }, { "code": "<script> // Define first array let arr1 = [1, 2, 3, 4, 5, 77, 876, 453]; // Define second array let arr2 = [1, 2, 45, 4, 231, 453]; // Create a empty object of array let result = []; // Checked the matched element between two // array and add into result array arr1.forEach( val => arr2.includes(val) && result.push(val) ); // Print the result on console console.log( result );</script>", "e": 1070, "s": 662, "text": null }, { "code": null, "e": 1078, "s": 1070, "text": "Output:" }, { "code": null, "e": 1092, "s": 1078, "text": " 1, 2, 4, 453" }, { "code": null, "e": 1144, "s": 1092, "text": "Method 2: filter(), push() and includes() of array." }, { "code": null, "e": 1155, "s": 1144, "text": "Javascript" }, { "code": "<script> // Define first array let arr1 = [1, 2, 3, 4, 5, 77, 876, 453]; // Define second array let arr2 = [1, 2, 45, 4, 231, 453]; / Checked the matched element between two array // and add into the result array let result = arr1.filter(val => arr2.includes(val) ); // Print the result on console console.log( result ); </script>", "e": 1506, "s": 1155, "text": null }, { "code": null, "e": 1514, "s": 1506, "text": "Output:" }, { "code": null, "e": 1528, "s": 1514, "text": " 1, 2, 4, 453" }, { "code": null, "e": 1545, "s": 1528, "text": "javascript-array" }, { "code": null, "e": 1566, "s": 1545, "text": "JavaScript-Questions" }, { "code": null, "e": 1573, "s": 1566, "text": "Picked" }, { "code": null, "e": 1597, "s": 1573, "text": "Technical Scripter 2020" }, { "code": null, "e": 1608, "s": 1597, "text": "JavaScript" }, { "code": null, "e": 1627, "s": 1608, "text": "Technical Scripter" }, { "code": null, "e": 1644, "s": 1627, "text": "Web Technologies" } ]
Number of ordered pairs such that (Ai & Aj) = 0
06 Jan, 2022 Given an array A[] of n integers, find out the number of ordered pairs such that Ai&Aj is zero, where 0<=(i,j)<n. Consider (i, j) and (j, i) to be different. Constraints: 1<=n<=104 1<=Ai<=104 Examples: Input : A[] = {3, 4, 2} Output : 4 Explanation : The pairs are (3, 4) and (4, 2) which are counted as 2 as (4, 3) and (2, 4) are considered different. Input : A[]={5, 4, 1, 6} Output : 4 Explanation : (4, 1), (1, 4), (6, 1) and (1, 6) are the pairs Simple approach: A simple approach is to check for all possible pairs and count the number of ordered pairs whose bitwise & returns 0. Below is the implementation of the above idea: C++ Java Python3 C# PHP JavaScript // CPP program to calculate the number// of ordered pairs such that their bitwise// and is zero#include <bits/stdc++.h>using namespace std; // Naive function to count the number// of ordered pairs such that their// bitwise and is 0int countPairs(int a[], int n){ int count = 0; // check for all possible pairs for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) if ((a[i] & a[j]) == 0) // add 2 as (i, j) and (j, i) are // considered different count += 2; } return count;} // Driver Codeint main(){ int a[] = { 3, 4, 2 }; int n = sizeof(a) / sizeof(a[0]); cout << countPairs(a, n); return 0;} // Java program to calculate the number// of ordered pairs such that their bitwise// and is zero class GFG { // Naive function to count the number // of ordered pairs such that their // bitwise and is 0 static int countPairs(int a[], int n) { int count = 0; // check for all possible pairs for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) if ((a[i] & a[j]) == 0) // add 2 as (i, j) and (j, i) are // considered different count += 2; } return count; } // Driver Code public static void main(String arg[]) { int a[] = { 3, 4, 2 }; int n = a.length; System.out.print(countPairs(a, n)); }} // This code is contributed by Anant Agarwal. # Python3 program to calculate the number# of ordered pairs such that their# bitwise and is zero # Naive function to count the number# of ordered pairs such that their# bitwise and is 0def countPairs(a, n): count = 0 # check for all possible pairs for i in range(0, n): for j in range(i + 1, n): if (a[i] & a[j]) == 0: # add 2 as (i, j) and (j, i) are # considered different count += 2 return count # Driver Codea = [ 3, 4, 2 ]n = len(a)print (countPairs(a, n)) # This code is contributed# by Shreyanshi Arun. // C# program to calculate the number// of ordered pairs such that their// bitwise and is zerousing System; class GFG { // Naive function to count the number // of ordered pairs such that their // bitwise and is 0 static int countPairs(int []a, int n) { int count = 0; // check for all possible pairs for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) if ((a[i] & a[j]) == 0) // add 2 as (i, j) and (j, i) // arev considered different count += 2; } return count; } // Driver Code public static void Main() { int []a = { 3, 4, 2 }; int n = a.Length; Console.Write(countPairs(a, n)); }} // This code is contributed by nitin mittal. <?php// PHP program to calculate the number// of ordered pairs such that their// bitwise and is zero // Naive function to count the number// of ordered pairs such that their// bitwise and is 0function countPairs($a, $n){ $count = 0; // check for all possible pairs for ($i = 0; $i < $n; $i++) { for ($j = $i + 1; $j < $n; $j++) if (($a[$i] & $a[$j]) == 0) // add 2 as (i, j) and (j, i) are // considered different $count += 2; } return $count;} // Driver Code{ $a = array(3, 4, 2); $n = sizeof($a) / sizeof($a[0]); echo countPairs($a, $n); return 0;} // This code is contributed by nitin mittal <script> // JavaScript program to calculate the number // of ordered pairs such that their bitwise // and is zero // Naive function to count the number // of ordered pairs such that their // bitwise and is 0 const countPairs = (a, n) => { let count = 0; // check for all possible pairs for (let i = 0; i < n; i++) { for (let j = i + 1; j < n; j++) if ((a[i] & a[j]) == 0) // add 2 as (i, j) and (j, i) are // considered different count += 2; } return count; } // Driver Code let a = [3, 4, 2]; let n = a.length; document.write(countPairs(a, n)); // This code is contributed by rakeshsahni </script> ?> Output: 4 Time Complexity: O(n2) Efficient approach: An efficient approach is to use Sum over Subsets Dynamic Programming method and count the number of ordered pairs. In the SOS DP we find out the pairs whose bitwise & returned 0. Here we need to count the number of pairs. Some key observations are the constraints, the maximum that an array element can be is 104. Calculating the mask up to (1<<15) will give us our answer. Use hashing to count the occurrence of every element. If the last bit is OFF, then relating to SOS dp, we will have a base case since there is only one possibility of OFF bit. dp[mask][0] = freq(mask) If the last bit is set ON, then we will have the base case as: dp[mask][0] = freq(mask) + freq(mask^1) We add freq(mask^1) to add the other possibility of OFF bit. Iterate over N=15 bits, which is the maximum possible.Let’s consider the i-th bit to be 0, then no subset can differ from the mask in the i-th bit as it would mean that the numbers will have a 1 at i-th bit where the mask has a 0 which would mean that it is not a subset of the mask. Thus we conclude that the numbers now differ in the first (i-1) bits only. Hence, DP(mask, i) = DP(mask, i-1) Now the second case, if the i-th bit is 1, it can be divided into two non-intersecting sets. One containing numbers with i-th bit as 1 and differing from mask in the next (i-1) bits. Second containing numbers with ith bit as 0 and differing from mask (2i) in next (i-1) bits. Hence, DP(mask, i) = DP(mask, i-1) + DP(mask 2i, i-1). DP[mask][i] stores the number of subsets of mask which differ from mask only in first i bits. Iterate for all array elements, and for every array element add the number of subsets (dp[ ( ( 1<<N ) – 1 ) ^ a[i] ][ N ]) to the number of pairs. N = maximum number of bits. Explanation of addition of dp[ ( ( 1<<N ) – 1 ) ^ a[i] ][N] to the number of pairs: Take an example of A[i] being 5, which is 101 in binary. For better understanding, assume N=3 in this case, therefore, the reverse of 101 will be 010 which on applying bitwise & gives 0. So (1<<3) gives 1000 which on subtraction from 1 gives 111. 111 101 gives 010 which is the reversed bit.So dp[((1<<N)-1)^a[i]][N] will have the number of subsets that returns 0 on applying bitwise & operator. Below is the implementation of the above idea: C++ Java Python3 C# // CPP program to calculate the number// of ordered pairs such that their bitwise// and is zero #include <bits/stdc++.h>using namespace std; const int N = 15; // efficient function to count pairslong long countPairs(int a[], int n){ // stores the frequency of each number unordered_map<int, int> hash; long long dp[1 << N][N + 1]; memset(dp, 0, sizeof(dp)); // initialize 0 to all // count the frequency of every element for (int i = 0; i < n; ++i) hash[a[i]] += 1; // iterate for all possible values that a[i] can be for (long long mask = 0; mask < (1 << N); ++mask) { // if the last bit is ON if (mask & 1) dp[mask][0] = hash[mask] + hash[mask ^ 1]; else // is the last bit is OFF dp[mask][0] = hash[mask]; // iterate till n for (int i = 1; i <= N; ++i) { // if mask's ith bit is set if (mask & (1 << i)) { dp[mask][i] = dp[mask][i - 1] + dp[mask ^ (1 << i)][i - 1]; } else // if mask's ith bit is not set dp[mask][i] = dp[mask][i - 1]; } } long long ans = 0; // iterate for all the array element // and count the number of pairs for (int i = 0; i < n; i++) ans += dp[((1 << N) - 1) ^ a[i]][N]; // return answer return ans;} // Driver Codeint main(){ int a[] = { 5, 4, 1, 6 }; int n = sizeof(a) / sizeof(a[0]); cout << countPairs(a, n); return 0;} // Java program to calculate// the number of ordered pairs// such that their bitwise// and is zeroimport java.util.*;class GFG{ static int N = 15; // Efficient function to count pairspublic static int countPairs(int a[], int n){ // Stores the frequency of // each number HashMap<Integer, Integer> hash = new HashMap<>(); int dp[][] = new int[1 << N][N + 1]; // Initialize 0 to all // Count the frequency // of every element for (int i = 0; i < n; ++i) { if(hash.containsKey(a[i])) { hash.replace(a[i], hash.get(a[i]) + 1); } else { hash.put(a[i], 1); } } // Iterate for all possible // values that a[i] can be for (int mask = 0; mask < (1 << N); ++mask) { // If the last bit is ON if ((mask & 1) != 0) { if(hash.containsKey(mask)) { dp[mask][0] = hash.get(mask); } if(hash.containsKey(mask ^ 1)) { dp[mask][0] += hash.get(mask ^ 1); } } else { // is the last bit is OFF if(hash.containsKey(mask)) { dp[mask][0] = hash.get(mask); } } // Iterate till n for (int i = 1; i <= N; ++i) { // If mask's ith bit is set if ((mask & (1 << i)) != 0) { dp[mask][i] = dp[mask][i - 1] + dp[mask ^ (1 << i)][i - 1]; } else { // If mask's ith bit is not set dp[mask][i] = dp[mask][i - 1]; } } } int ans = 0; // Iterate for all the // array element and // count the number of pairs for (int i = 0; i < n; i++) { ans += dp[((1 << N) - 1) ^ a[i]][N]; } // return answer return ans;} // Driver code public static void main(String[] args){ int a[] = {5, 4, 1, 6}; int n = a.length; System.out.print(countPairs(a, n));}} // This code is contributed by divyeshrabadiya07 # Python program to calculate the number# of ordered pairs such that their bitwise# and is zeroN = 15 # efficient function to count pairsdef countPairs(a, n): # stores the frequency of each number Hash = {} # initialize 0 to all dp = [[0 for i in range(N + 1)] for j in range(1 << N)] # count the frequency of every element for i in range(n): if a[i] not in Hash: Hash[a[i]] = 1 else: Hash[a[i]] += 1 # iterate for all possible values that a[i] can be mask = 0 while(mask < (1 << N)): if mask not in Hash: Hash[mask] = 0 # if the last bit is ON if(mask & 1): dp[mask][0] = Hash[mask] + Hash[mask ^ 1] else: # is the last bit is OFF dp[mask][0] = Hash[mask] # iterate till n for i in range(1, N + 1): # if mask's ith bit is set if(mask & (1 << i)): dp[mask][i] = dp[mask][i - 1] + dp[mask ^ (1 << i)][i - 1] else: # if mask's ith bit is not set dp[mask][i] = dp[mask][i - 1] mask += 1 ans = 0 # iterate for all the array element # and count the number of pairs for i in range(n): ans += dp[((1 << N) - 1) ^ a[i]][N] # return answer return ans # Driver Codea = [5, 4, 1, 6]n = len(a)print(countPairs(a, n)) # This code is contributed by avanitrachhadiya2155 // C# program to calculate// the number of ordered pairs// such that their bitwise// and is zerousing System;using System.Collections.Generic; class GFG { static int N = 15; // Efficient function to count pairs static int countPairs(int[] a, int n) { // Stores the frequency of // each number Dictionary<int, int> hash = new Dictionary<int, int>(); int[, ] dp = new int[1 << N, N + 1]; // Initialize 0 to all // Count the frequency // of every element for (int i = 0; i < n; ++i) { if(hash.ContainsKey(a[i])) { hash[a[i]] += 1; } else { hash.Add(a[i], 1); } } // Iterate for all possible // values that a[i] can be for (int mask = 0; mask < (1 << N); ++mask) { // If the last bit is ON if ((mask & 1) != 0) { if(hash.ContainsKey(mask)) { dp[mask, 0] = hash[mask]; } if(hash.ContainsKey(mask ^ 1)) { dp[mask, 0] += hash[mask ^ 1]; } } else { // is the last bit is OFF if(hash.ContainsKey(mask)) { dp[mask, 0] = hash[mask]; } } // Iterate till n for (int i = 1; i <= N; ++i) { // If mask's ith bit is set if ((mask & (1 << i)) != 0) { dp[mask, i] = dp[mask, i - 1] + dp[mask ^ (1 << i), i - 1]; } else { // If mask's ith bit is not set dp[mask, i] = dp[mask, i - 1]; } } } int ans = 0; // Iterate for all the // array element and // count the number of pairs for (int i = 0; i < n; i++) { ans += dp[((1 << N) - 1) ^ a[i], N]; } // return answer return ans; } // Driver code static void Main() { int[] a = {5, 4, 1, 6}; int n = a.Length; Console.WriteLine(countPairs(a, n)); }} // This code is contributed by divyesh072019 Output: 4 Time Complexity: O(N*2N) where N=15 which is a maximum number of bits possible, since Amax=104. nitin mittal ManasChhabra2 shubham_singh divyeshrabadiya07 divyesh072019 avanitrachhadiya2155 rakeshsahni surinderdawra388 Bit Algorithms Dynamic Programming Dynamic Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Longest Palindromic Substring | Set 1 Floyd Warshall Algorithm | DP-16 Find if there is a path between two vertices in an undirected graph Matrix Chain Multiplication | DP-8 Bellman–Ford Algorithm | DP-23 Sieve of Eratosthenes Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Find minimum number of coins that make a given value Minimum number of jumps to reach end Tabulation vs Memoization
[ { "code": null, "e": 52, "s": 24, "text": "\n06 Jan, 2022" }, { "code": null, "e": 211, "s": 52, "text": "Given an array A[] of n integers, find out the number of ordered pairs such that Ai&Aj is zero, where 0<=(i,j)<n. Consider (i, j) and (j, i) to be different. " }, { "code": null, "e": 245, "s": 211, "text": "Constraints: 1<=n<=104 1<=Ai<=104" }, { "code": null, "e": 256, "s": 245, "text": "Examples: " }, { "code": null, "e": 509, "s": 256, "text": "Input : A[] = {3, 4, 2}\nOutput : 4\nExplanation : The pairs are (3, 4) and (4, 2) which are \ncounted as 2 as (4, 3) and (2, 4) are considered different. \n\nInput : A[]={5, 4, 1, 6}\nOutput : 4 \nExplanation : (4, 1), (1, 4), (6, 1) and (1, 6) are the pairs" }, { "code": null, "e": 645, "s": 509, "text": "Simple approach: A simple approach is to check for all possible pairs and count the number of ordered pairs whose bitwise & returns 0. " }, { "code": null, "e": 694, "s": 645, "text": "Below is the implementation of the above idea: " }, { "code": null, "e": 698, "s": 694, "text": "C++" }, { "code": null, "e": 703, "s": 698, "text": "Java" }, { "code": null, "e": 711, "s": 703, "text": "Python3" }, { "code": null, "e": 714, "s": 711, "text": "C#" }, { "code": null, "e": 718, "s": 714, "text": "PHP" }, { "code": null, "e": 729, "s": 718, "text": "JavaScript" }, { "code": "// CPP program to calculate the number// of ordered pairs such that their bitwise// and is zero#include <bits/stdc++.h>using namespace std; // Naive function to count the number// of ordered pairs such that their// bitwise and is 0int countPairs(int a[], int n){ int count = 0; // check for all possible pairs for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) if ((a[i] & a[j]) == 0) // add 2 as (i, j) and (j, i) are // considered different count += 2; } return count;} // Driver Codeint main(){ int a[] = { 3, 4, 2 }; int n = sizeof(a) / sizeof(a[0]); cout << countPairs(a, n); return 0;}", "e": 1431, "s": 729, "text": null }, { "code": "// Java program to calculate the number// of ordered pairs such that their bitwise// and is zero class GFG { // Naive function to count the number // of ordered pairs such that their // bitwise and is 0 static int countPairs(int a[], int n) { int count = 0; // check for all possible pairs for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) if ((a[i] & a[j]) == 0) // add 2 as (i, j) and (j, i) are // considered different count += 2; } return count; } // Driver Code public static void main(String arg[]) { int a[] = { 3, 4, 2 }; int n = a.length; System.out.print(countPairs(a, n)); }} // This code is contributed by Anant Agarwal.", "e": 2254, "s": 1431, "text": null }, { "code": "# Python3 program to calculate the number# of ordered pairs such that their# bitwise and is zero # Naive function to count the number# of ordered pairs such that their# bitwise and is 0def countPairs(a, n): count = 0 # check for all possible pairs for i in range(0, n): for j in range(i + 1, n): if (a[i] & a[j]) == 0: # add 2 as (i, j) and (j, i) are # considered different count += 2 return count # Driver Codea = [ 3, 4, 2 ]n = len(a)print (countPairs(a, n)) # This code is contributed# by Shreyanshi Arun.", "e": 2841, "s": 2254, "text": null }, { "code": "// C# program to calculate the number// of ordered pairs such that their// bitwise and is zerousing System; class GFG { // Naive function to count the number // of ordered pairs such that their // bitwise and is 0 static int countPairs(int []a, int n) { int count = 0; // check for all possible pairs for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) if ((a[i] & a[j]) == 0) // add 2 as (i, j) and (j, i) // arev considered different count += 2; } return count; } // Driver Code public static void Main() { int []a = { 3, 4, 2 }; int n = a.Length; Console.Write(countPairs(a, n)); }} // This code is contributed by nitin mittal.", "e": 3667, "s": 2841, "text": null }, { "code": "<?php// PHP program to calculate the number// of ordered pairs such that their// bitwise and is zero // Naive function to count the number// of ordered pairs such that their// bitwise and is 0function countPairs($a, $n){ $count = 0; // check for all possible pairs for ($i = 0; $i < $n; $i++) { for ($j = $i + 1; $j < $n; $j++) if (($a[$i] & $a[$j]) == 0) // add 2 as (i, j) and (j, i) are // considered different $count += 2; } return $count;} // Driver Code{ $a = array(3, 4, 2); $n = sizeof($a) / sizeof($a[0]); echo countPairs($a, $n); return 0;} // This code is contributed by nitin mittal", "e": 4358, "s": 3667, "text": null }, { "code": "<script> // JavaScript program to calculate the number // of ordered pairs such that their bitwise // and is zero // Naive function to count the number // of ordered pairs such that their // bitwise and is 0 const countPairs = (a, n) => { let count = 0; // check for all possible pairs for (let i = 0; i < n; i++) { for (let j = i + 1; j < n; j++) if ((a[i] & a[j]) == 0) // add 2 as (i, j) and (j, i) are // considered different count += 2; } return count; } // Driver Code let a = [3, 4, 2]; let n = a.length; document.write(countPairs(a, n)); // This code is contributed by rakeshsahni </script> ?>", "e": 5125, "s": 4358, "text": null }, { "code": null, "e": 5134, "s": 5125, "text": "Output: " }, { "code": null, "e": 5136, "s": 5134, "text": "4" }, { "code": null, "e": 5159, "s": 5136, "text": "Time Complexity: O(n2)" }, { "code": null, "e": 5730, "s": 5159, "text": "Efficient approach: An efficient approach is to use Sum over Subsets Dynamic Programming method and count the number of ordered pairs. In the SOS DP we find out the pairs whose bitwise & returned 0. Here we need to count the number of pairs. Some key observations are the constraints, the maximum that an array element can be is 104. Calculating the mask up to (1<<15) will give us our answer. Use hashing to count the occurrence of every element. If the last bit is OFF, then relating to SOS dp, we will have a base case since there is only one possibility of OFF bit. " }, { "code": null, "e": 5755, "s": 5730, "text": "dp[mask][0] = freq(mask)" }, { "code": null, "e": 5820, "s": 5755, "text": "If the last bit is set ON, then we will have the base case as: " }, { "code": null, "e": 5860, "s": 5820, "text": "dp[mask][0] = freq(mask) + freq(mask^1)" }, { "code": null, "e": 6288, "s": 5860, "text": "We add freq(mask^1) to add the other possibility of OFF bit. Iterate over N=15 bits, which is the maximum possible.Let’s consider the i-th bit to be 0, then no subset can differ from the mask in the i-th bit as it would mean that the numbers will have a 1 at i-th bit where the mask has a 0 which would mean that it is not a subset of the mask. Thus we conclude that the numbers now differ in the first (i-1) bits only. Hence, " }, { "code": null, "e": 6316, "s": 6288, "text": "DP(mask, i) = DP(mask, i-1)" }, { "code": null, "e": 6567, "s": 6316, "text": "Now the second case, if the i-th bit is 1, it can be divided into two non-intersecting sets. One containing numbers with i-th bit as 1 and differing from mask in the next (i-1) bits. Second containing numbers with ith bit as 0 and differing from mask" }, { "code": null, "e": 6599, "s": 6567, "text": "(2i) in next (i-1) bits. Hence," }, { "code": null, "e": 6637, "s": 6599, "text": "DP(mask, i) = DP(mask, i-1) + DP(mask" }, { "code": null, "e": 6647, "s": 6637, "text": "2i, i-1)." }, { "code": null, "e": 6917, "s": 6647, "text": "DP[mask][i] stores the number of subsets of mask which differ from mask only in first i bits. Iterate for all array elements, and for every array element add the number of subsets (dp[ ( ( 1<<N ) – 1 ) ^ a[i] ][ N ]) to the number of pairs. N = maximum number of bits. " }, { "code": null, "e": 7397, "s": 6917, "text": "Explanation of addition of dp[ ( ( 1<<N ) – 1 ) ^ a[i] ][N] to the number of pairs: Take an example of A[i] being 5, which is 101 in binary. For better understanding, assume N=3 in this case, therefore, the reverse of 101 will be 010 which on applying bitwise & gives 0. So (1<<3) gives 1000 which on subtraction from 1 gives 111. 111 101 gives 010 which is the reversed bit.So dp[((1<<N)-1)^a[i]][N] will have the number of subsets that returns 0 on applying bitwise & operator." }, { "code": null, "e": 7446, "s": 7397, "text": "Below is the implementation of the above idea: " }, { "code": null, "e": 7450, "s": 7446, "text": "C++" }, { "code": null, "e": 7455, "s": 7450, "text": "Java" }, { "code": null, "e": 7463, "s": 7455, "text": "Python3" }, { "code": null, "e": 7466, "s": 7463, "text": "C#" }, { "code": "// CPP program to calculate the number// of ordered pairs such that their bitwise// and is zero #include <bits/stdc++.h>using namespace std; const int N = 15; // efficient function to count pairslong long countPairs(int a[], int n){ // stores the frequency of each number unordered_map<int, int> hash; long long dp[1 << N][N + 1]; memset(dp, 0, sizeof(dp)); // initialize 0 to all // count the frequency of every element for (int i = 0; i < n; ++i) hash[a[i]] += 1; // iterate for all possible values that a[i] can be for (long long mask = 0; mask < (1 << N); ++mask) { // if the last bit is ON if (mask & 1) dp[mask][0] = hash[mask] + hash[mask ^ 1]; else // is the last bit is OFF dp[mask][0] = hash[mask]; // iterate till n for (int i = 1; i <= N; ++i) { // if mask's ith bit is set if (mask & (1 << i)) { dp[mask][i] = dp[mask][i - 1] + dp[mask ^ (1 << i)][i - 1]; } else // if mask's ith bit is not set dp[mask][i] = dp[mask][i - 1]; } } long long ans = 0; // iterate for all the array element // and count the number of pairs for (int i = 0; i < n; i++) ans += dp[((1 << N) - 1) ^ a[i]][N]; // return answer return ans;} // Driver Codeint main(){ int a[] = { 5, 4, 1, 6 }; int n = sizeof(a) / sizeof(a[0]); cout << countPairs(a, n); return 0;}", "e": 8976, "s": 7466, "text": null }, { "code": "// Java program to calculate// the number of ordered pairs// such that their bitwise// and is zeroimport java.util.*;class GFG{ static int N = 15; // Efficient function to count pairspublic static int countPairs(int a[], int n){ // Stores the frequency of // each number HashMap<Integer, Integer> hash = new HashMap<>(); int dp[][] = new int[1 << N][N + 1]; // Initialize 0 to all // Count the frequency // of every element for (int i = 0; i < n; ++i) { if(hash.containsKey(a[i])) { hash.replace(a[i], hash.get(a[i]) + 1); } else { hash.put(a[i], 1); } } // Iterate for all possible // values that a[i] can be for (int mask = 0; mask < (1 << N); ++mask) { // If the last bit is ON if ((mask & 1) != 0) { if(hash.containsKey(mask)) { dp[mask][0] = hash.get(mask); } if(hash.containsKey(mask ^ 1)) { dp[mask][0] += hash.get(mask ^ 1); } } else { // is the last bit is OFF if(hash.containsKey(mask)) { dp[mask][0] = hash.get(mask); } } // Iterate till n for (int i = 1; i <= N; ++i) { // If mask's ith bit is set if ((mask & (1 << i)) != 0) { dp[mask][i] = dp[mask][i - 1] + dp[mask ^ (1 << i)][i - 1]; } else { // If mask's ith bit is not set dp[mask][i] = dp[mask][i - 1]; } } } int ans = 0; // Iterate for all the // array element and // count the number of pairs for (int i = 0; i < n; i++) { ans += dp[((1 << N) - 1) ^ a[i]][N]; } // return answer return ans;} // Driver code public static void main(String[] args){ int a[] = {5, 4, 1, 6}; int n = a.length; System.out.print(countPairs(a, n));}} // This code is contributed by divyeshrabadiya07", "e": 10837, "s": 8976, "text": null }, { "code": "# Python program to calculate the number# of ordered pairs such that their bitwise# and is zeroN = 15 # efficient function to count pairsdef countPairs(a, n): # stores the frequency of each number Hash = {} # initialize 0 to all dp = [[0 for i in range(N + 1)] for j in range(1 << N)] # count the frequency of every element for i in range(n): if a[i] not in Hash: Hash[a[i]] = 1 else: Hash[a[i]] += 1 # iterate for all possible values that a[i] can be mask = 0 while(mask < (1 << N)): if mask not in Hash: Hash[mask] = 0 # if the last bit is ON if(mask & 1): dp[mask][0] = Hash[mask] + Hash[mask ^ 1] else: # is the last bit is OFF dp[mask][0] = Hash[mask] # iterate till n for i in range(1, N + 1): # if mask's ith bit is set if(mask & (1 << i)): dp[mask][i] = dp[mask][i - 1] + dp[mask ^ (1 << i)][i - 1] else: # if mask's ith bit is not set dp[mask][i] = dp[mask][i - 1] mask += 1 ans = 0 # iterate for all the array element # and count the number of pairs for i in range(n): ans += dp[((1 << N) - 1) ^ a[i]][N] # return answer return ans # Driver Codea = [5, 4, 1, 6]n = len(a)print(countPairs(a, n)) # This code is contributed by avanitrachhadiya2155", "e": 12289, "s": 10837, "text": null }, { "code": "// C# program to calculate// the number of ordered pairs// such that their bitwise// and is zerousing System;using System.Collections.Generic; class GFG { static int N = 15; // Efficient function to count pairs static int countPairs(int[] a, int n) { // Stores the frequency of // each number Dictionary<int, int> hash = new Dictionary<int, int>(); int[, ] dp = new int[1 << N, N + 1]; // Initialize 0 to all // Count the frequency // of every element for (int i = 0; i < n; ++i) { if(hash.ContainsKey(a[i])) { hash[a[i]] += 1; } else { hash.Add(a[i], 1); } } // Iterate for all possible // values that a[i] can be for (int mask = 0; mask < (1 << N); ++mask) { // If the last bit is ON if ((mask & 1) != 0) { if(hash.ContainsKey(mask)) { dp[mask, 0] = hash[mask]; } if(hash.ContainsKey(mask ^ 1)) { dp[mask, 0] += hash[mask ^ 1]; } } else { // is the last bit is OFF if(hash.ContainsKey(mask)) { dp[mask, 0] = hash[mask]; } } // Iterate till n for (int i = 1; i <= N; ++i) { // If mask's ith bit is set if ((mask & (1 << i)) != 0) { dp[mask, i] = dp[mask, i - 1] + dp[mask ^ (1 << i), i - 1]; } else { // If mask's ith bit is not set dp[mask, i] = dp[mask, i - 1]; } } } int ans = 0; // Iterate for all the // array element and // count the number of pairs for (int i = 0; i < n; i++) { ans += dp[((1 << N) - 1) ^ a[i], N]; } // return answer return ans; } // Driver code static void Main() { int[] a = {5, 4, 1, 6}; int n = a.Length; Console.WriteLine(countPairs(a, n)); }} // This code is contributed by divyesh072019", "e": 14457, "s": 12289, "text": null }, { "code": null, "e": 14466, "s": 14457, "text": "Output: " }, { "code": null, "e": 14468, "s": 14466, "text": "4" }, { "code": null, "e": 14564, "s": 14468, "text": "Time Complexity: O(N*2N) where N=15 which is a maximum number of bits possible, since Amax=104." }, { "code": null, "e": 14577, "s": 14564, "text": "nitin mittal" }, { "code": null, "e": 14591, "s": 14577, "text": "ManasChhabra2" }, { "code": null, "e": 14605, "s": 14591, "text": "shubham_singh" }, { "code": null, "e": 14623, "s": 14605, "text": "divyeshrabadiya07" }, { "code": null, "e": 14637, "s": 14623, "text": "divyesh072019" }, { "code": null, "e": 14658, "s": 14637, "text": "avanitrachhadiya2155" }, { "code": null, "e": 14670, "s": 14658, "text": "rakeshsahni" }, { "code": null, "e": 14687, "s": 14670, "text": "surinderdawra388" }, { "code": null, "e": 14702, "s": 14687, "text": "Bit Algorithms" }, { "code": null, "e": 14722, "s": 14702, "text": "Dynamic Programming" }, { "code": null, "e": 14742, "s": 14722, "text": "Dynamic Programming" }, { "code": null, "e": 14840, "s": 14742, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 14878, "s": 14840, "text": "Longest Palindromic Substring | Set 1" }, { "code": null, "e": 14911, "s": 14878, "text": "Floyd Warshall Algorithm | DP-16" }, { "code": null, "e": 14979, "s": 14911, "text": "Find if there is a path between two vertices in an undirected graph" }, { "code": null, "e": 15014, "s": 14979, "text": "Matrix Chain Multiplication | DP-8" }, { "code": null, "e": 15045, "s": 15014, "text": "Bellman–Ford Algorithm | DP-23" }, { "code": null, "e": 15067, "s": 15045, "text": "Sieve of Eratosthenes" }, { "code": null, "e": 15135, "s": 15067, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" }, { "code": null, "e": 15188, "s": 15135, "text": "Find minimum number of coins that make a given value" }, { "code": null, "e": 15225, "s": 15188, "text": "Minimum number of jumps to reach end" } ]
Python | Cartesian product of string elements
22 Apr, 2020 Sometimes, while working with Python strings, we can have problem that we have data in string which is comma or any delim separated. We might want to perform cartesian product with other similar strings to get all possible pairs of data. Lets discuss certain ways in which this task can be performed. Method #1 : Using list comprehension + split()This task can be performed using list comprehension. In this, we perform the task of extracting individual elements using split(). The task of list comprehension is to form pairs. # Python3 code to demonstrate working of # Cartesian product of string elements# Using split() + list comprehension # initializing stringstest_str1 = "gfg, is, best"test_str2 = "for, all, geeks" # printing original stringsprint("The original string 1 is : " + test_str1)print("The original string 2 is : " + test_str2) # Cartesian product of string elements# Using split() + list comprehensionres = [sub1 + sub2 for sub1 in test_str1.split(", ") for sub2 in test_str2.split(", ")] # printing result print("Cartesian product list : " + str(res)) The original string 1 is : gfg, is, best The original string 2 is : for, all, geeks Cartesian product list : ['gfgfor', 'gfgall', 'gfggeeks', 'isfor', 'isall', 'isgeeks', 'bestfor', 'bestall', 'bestgeeks'] Method #2 : Using List comprehension + product()The combination of above functions can be used to perform this task. In this, we employ product() in place of nested comprehension to perform the task of pairing. # Python3 code to demonstrate working of # Cartesian product of string elements# Using product() + list comprehensionfrom itertools import product # initializing stringstest_str1 = "gfg, is, best"test_str2 = "for, all, geeks" # printing original stringsprint("The original string 1 is : " + test_str1)print("The original string 2 is : " + test_str2) # Cartesian product of string elements# Using product() + list comprehensionres = [sub1 + sub2 for sub1, sub2 in product(test_str1.split(", "), test_str2.split(", "))] # printing result print("Cartesian product list : " + str(res)) The original string 1 is : gfg, is, best The original string 2 is : for, all, geeks Cartesian product list : ['gfgfor', 'gfgall', 'gfggeeks', 'isfor', 'isall', 'isgeeks', 'bestfor', 'bestall', 'bestgeeks'] Python string-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Apr, 2020" }, { "code": null, "e": 329, "s": 28, "text": "Sometimes, while working with Python strings, we can have problem that we have data in string which is comma or any delim separated. We might want to perform cartesian product with other similar strings to get all possible pairs of data. Lets discuss certain ways in which this task can be performed." }, { "code": null, "e": 555, "s": 329, "text": "Method #1 : Using list comprehension + split()This task can be performed using list comprehension. In this, we perform the task of extracting individual elements using split(). The task of list comprehension is to form pairs." }, { "code": "# Python3 code to demonstrate working of # Cartesian product of string elements# Using split() + list comprehension # initializing stringstest_str1 = \"gfg, is, best\"test_str2 = \"for, all, geeks\" # printing original stringsprint(\"The original string 1 is : \" + test_str1)print(\"The original string 2 is : \" + test_str2) # Cartesian product of string elements# Using split() + list comprehensionres = [sub1 + sub2 for sub1 in test_str1.split(\", \") for sub2 in test_str2.split(\", \")] # printing result print(\"Cartesian product list : \" + str(res)) ", "e": 1125, "s": 555, "text": null }, { "code": null, "e": 1332, "s": 1125, "text": "The original string 1 is : gfg, is, best\nThe original string 2 is : for, all, geeks\nCartesian product list : ['gfgfor', 'gfgall', 'gfggeeks', 'isfor', 'isall', 'isgeeks', 'bestfor', 'bestall', 'bestgeeks']\n" }, { "code": null, "e": 1545, "s": 1334, "text": "Method #2 : Using List comprehension + product()The combination of above functions can be used to perform this task. In this, we employ product() in place of nested comprehension to perform the task of pairing." }, { "code": "# Python3 code to demonstrate working of # Cartesian product of string elements# Using product() + list comprehensionfrom itertools import product # initializing stringstest_str1 = \"gfg, is, best\"test_str2 = \"for, all, geeks\" # printing original stringsprint(\"The original string 1 is : \" + test_str1)print(\"The original string 2 is : \" + test_str2) # Cartesian product of string elements# Using product() + list comprehensionres = [sub1 + sub2 for sub1, sub2 in product(test_str1.split(\", \"), test_str2.split(\", \"))] # printing result print(\"Cartesian product list : \" + str(res)) ", "e": 2152, "s": 1545, "text": null }, { "code": null, "e": 2359, "s": 2152, "text": "The original string 1 is : gfg, is, best\nThe original string 2 is : for, all, geeks\nCartesian product list : ['gfgfor', 'gfgall', 'gfggeeks', 'isfor', 'isall', 'isgeeks', 'bestfor', 'bestall', 'bestgeeks']\n" }, { "code": null, "e": 2382, "s": 2359, "text": "Python string-programs" }, { "code": null, "e": 2389, "s": 2382, "text": "Python" }, { "code": null, "e": 2405, "s": 2389, "text": "Python Programs" } ]
Ruby | Class & Object
29 Jul, 2021 Ruby is an ideal object-oriented programming language. The features of an object-oriented programming language include data encapsulation, polymorphism, inheritance, data abstraction, operator overloading etc. In object-oriented programming classes and objects plays an important role. A class is a blueprint from which objects are created. The object is also called as an instance of a class. For Example, the animal is a class and mammals, birds, fish, reptiles, and amphibians are the instances of the class. Similarly, the sales department is the class and the objects of the class are sales data, sales manager, and secretary.Defining a class in Ruby: In Ruby, one can easily create classes and objects. Simply write class keyword followed by the name of the class. The first letter of the class name should be in capital letter.Syntax: class Class_name end A class is terminated by end keyword and all the data members are lies in between class definition and end keyword.Example: # class name is Animal class Animal # class variables @@type_of_animal = 4 @@no_of_animal = 3 end Creating Objects using the “new” method in Ruby: Classes and objects are the most important part of Ruby. Like class objects are also easy to create, we can create a number of objects from a single class. In Ruby, objects are created by the new method.Syntax: object_name = Class_name.new Example: # class name is box class Box # class variable @@No_of_color = 3 end # Two Objects of Box class sbox = Box.new nbox = Box.new Here Box is the name of the class and No_of_color is the variable of the class. sbox and nbox are the two objects of box class. You use (=) followed by the class name, dot operator, and new method.Defining Method in Ruby: In Ruby member functions are called as methods. Every method is defined by the def keyword followed by a method name. The name of the method is always in lowercase and the method ends with end keyword. In Ruby, each class and methods end with end keyword.Syntax: def method_name # statements or code to be executed end Example: Ruby # Ruby program to illustrate# the defining of methods #!/usr/bin/ruby # defining class Vehicleclass GFG # defining methoddef geeks # printing resultputs "Hello Geeks!" # end of methodend # end of class GFGend # creating objectobj = GFG.new # calling method using objectobj.geeks Output: Hello Geeks! Passing Parameters to new Method: User can pass any numbers of parameters to “new method” which are used to initialize the class variables. While passing parameters to “new method” it is must to declare an initialize method at the time of class creation. The initialize method is a specific method, which executes when the new method is called with parameters.Example: Ruby # Ruby program to illustrate the passing# parameters to new method #!/usr/bin/ruby # defining class Vehicleclass Vehicle # initialize methoddef initialize(id, color, name) # variables@veh_id = id@veh_color = color@veh_name = name # displaying valuesputs "ID is: #@veh_id"puts "Color is: #@veh_color"puts "Name is: #@veh_name"puts "\n"endend # Creating objects and passing parameters# to new methodxveh = Vehicle. new("1", "Red", "ABC")yveh = Vehicle. new("2", "Black", "XYZ") Output: ID is: 1 Color is: Red Name is: ABC ID is: 2 Color is: Black Name is: XYZ Explanation: Here Vehicle is the class name. def is a keyword which is used to define “initialize” method in Ruby. It is called whenever a new object is created. Whenever new class method called it always call initialize instance method. initialize method is like a constructor, whenever new objects are created initialize method called. Id, color, name, are the parameters in initialize method and @veh_id @veh_color, @veh_name are the local variables in initialize method with the help of these local variables we passed the value along the new method. The parameters in “new” method is always enclosed in double quotes. ghanshyam anand Ruby-Basics Ruby-OOP 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? Global Variable in Ruby Ruby | Enumerator each_with_index function Ruby | Case Statement Ruby | Array select() function Ruby | Hash delete() function Ruby | unless Statement and unless Modifier Ruby | Data Types Ruby | String capitalize() Method Ruby | String gsub! Method
[ { "code": null, "e": 53, "s": 25, "text": "\n29 Jul, 2021" }, { "code": null, "e": 896, "s": 53, "text": "Ruby is an ideal object-oriented programming language. The features of an object-oriented programming language include data encapsulation, polymorphism, inheritance, data abstraction, operator overloading etc. In object-oriented programming classes and objects plays an important role. A class is a blueprint from which objects are created. The object is also called as an instance of a class. For Example, the animal is a class and mammals, birds, fish, reptiles, and amphibians are the instances of the class. Similarly, the sales department is the class and the objects of the class are sales data, sales manager, and secretary.Defining a class in Ruby: In Ruby, one can easily create classes and objects. Simply write class keyword followed by the name of the class. The first letter of the class name should be in capital letter.Syntax: " }, { "code": null, "e": 918, "s": 896, "text": "class Class_name\n\nend" }, { "code": null, "e": 1044, "s": 918, "text": "A class is terminated by end keyword and all the data members are lies in between class definition and end keyword.Example: " }, { "code": null, "e": 1144, "s": 1044, "text": "# class name is Animal\nclass Animal\n\n# class variables\n@@type_of_animal = 4\n@@no_of_animal = 3\n\nend" }, { "code": null, "e": 1405, "s": 1144, "text": "Creating Objects using the “new” method in Ruby: Classes and objects are the most important part of Ruby. Like class objects are also easy to create, we can create a number of objects from a single class. In Ruby, objects are created by the new method.Syntax: " }, { "code": null, "e": 1434, "s": 1405, "text": "object_name = Class_name.new" }, { "code": null, "e": 1445, "s": 1434, "text": "Example: " }, { "code": null, "e": 1574, "s": 1445, "text": "# class name is box\nclass Box\n\n# class variable\n@@No_of_color = 3\n\nend\n\n# Two Objects of Box class\nsbox = Box.new\nnbox = Box.new" }, { "code": null, "e": 2061, "s": 1574, "text": "Here Box is the name of the class and No_of_color is the variable of the class. sbox and nbox are the two objects of box class. You use (=) followed by the class name, dot operator, and new method.Defining Method in Ruby: In Ruby member functions are called as methods. Every method is defined by the def keyword followed by a method name. The name of the method is always in lowercase and the method ends with end keyword. In Ruby, each class and methods end with end keyword.Syntax: " }, { "code": null, "e": 2119, "s": 2061, "text": "def method_name\n\n# statements or code to be executed\n\nend" }, { "code": null, "e": 2129, "s": 2119, "text": "Example: " }, { "code": null, "e": 2134, "s": 2129, "text": "Ruby" }, { "code": "# Ruby program to illustrate# the defining of methods #!/usr/bin/ruby # defining class Vehicleclass GFG # defining methoddef geeks # printing resultputs \"Hello Geeks!\" # end of methodend # end of class GFGend # creating objectobj = GFG.new # calling method using objectobj.geeks", "e": 2413, "s": 2134, "text": null }, { "code": null, "e": 2423, "s": 2413, "text": "Output: " }, { "code": null, "e": 2436, "s": 2423, "text": "Hello Geeks!" }, { "code": null, "e": 2806, "s": 2436, "text": "Passing Parameters to new Method: User can pass any numbers of parameters to “new method” which are used to initialize the class variables. While passing parameters to “new method” it is must to declare an initialize method at the time of class creation. The initialize method is a specific method, which executes when the new method is called with parameters.Example: " }, { "code": null, "e": 2811, "s": 2806, "text": "Ruby" }, { "code": "# Ruby program to illustrate the passing# parameters to new method #!/usr/bin/ruby # defining class Vehicleclass Vehicle # initialize methoddef initialize(id, color, name) # variables@veh_id = id@veh_color = color@veh_name = name # displaying valuesputs \"ID is: #@veh_id\"puts \"Color is: #@veh_color\"puts \"Name is: #@veh_name\"puts \"\\n\"endend # Creating objects and passing parameters# to new methodxveh = Vehicle. new(\"1\", \"Red\", \"ABC\")yveh = Vehicle. new(\"2\", \"Black\", \"XYZ\")", "e": 3287, "s": 2811, "text": null }, { "code": null, "e": 3297, "s": 3287, "text": "Output: " }, { "code": null, "e": 3372, "s": 3297, "text": "ID is: 1\nColor is: Red\nName is: ABC\n\nID is: 2\nColor is: Black\nName is: XYZ" }, { "code": null, "e": 3996, "s": 3372, "text": "Explanation: Here Vehicle is the class name. def is a keyword which is used to define “initialize” method in Ruby. It is called whenever a new object is created. Whenever new class method called it always call initialize instance method. initialize method is like a constructor, whenever new objects are created initialize method called. Id, color, name, are the parameters in initialize method and @veh_id @veh_color, @veh_name are the local variables in initialize method with the help of these local variables we passed the value along the new method. The parameters in “new” method is always enclosed in double quotes. " }, { "code": null, "e": 4012, "s": 3996, "text": "ghanshyam anand" }, { "code": null, "e": 4024, "s": 4012, "text": "Ruby-Basics" }, { "code": null, "e": 4033, "s": 4024, "text": "Ruby-OOP" }, { "code": null, "e": 4038, "s": 4033, "text": "Ruby" }, { "code": null, "e": 4136, "s": 4038, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4182, "s": 4136, "text": "How to Make a Custom Array of Hashes in Ruby?" }, { "code": null, "e": 4206, "s": 4182, "text": "Global Variable in Ruby" }, { "code": null, "e": 4249, "s": 4206, "text": "Ruby | Enumerator each_with_index function" }, { "code": null, "e": 4271, "s": 4249, "text": "Ruby | Case Statement" }, { "code": null, "e": 4302, "s": 4271, "text": "Ruby | Array select() function" }, { "code": null, "e": 4332, "s": 4302, "text": "Ruby | Hash delete() function" }, { "code": null, "e": 4376, "s": 4332, "text": "Ruby | unless Statement and unless Modifier" }, { "code": null, "e": 4394, "s": 4376, "text": "Ruby | Data Types" }, { "code": null, "e": 4428, "s": 4394, "text": "Ruby | String capitalize() Method" } ]
GATE | GATE-CS-2015 (Set 1) | Question 65
28 Jun, 2021 Consider a LAN with four nodes S1, S2, S3 and S4. Time is divided into fixed-size slots, and a node can begin its transmission only at the beginning of a slot. A collision is said to have occurred if more than one node transmit in the same slot. The probabilities of generation of a frame in a time slot by S1, S2, S3 and S4 are 0.1, 0.2, 0.3 and 0.4, respectively. The probability of sending a frame in the first slot without any collision by any of these four stations is _________.(A) 0.462(B) 0.711(C) 0.5(D) 0.652Answer: (A)Explanation: The probability of sending a frame in the first slot without any collision by any of these four stations is sum of following 4 probabilities Probability that S1 sends a frame and no one else does + Probability thatS2 sends a frame and no one else does + Probability thatS3 sends a frame and no one else does + Probability thatS4 sends a frame and no one else does = 0.1 * (1 - 0.2) * (1 - 0.3) *(1 - 0.4) + (1 -0.1) * 0.2 * (1 - 0.3) *(1 - 0.4) + (1 -0.1) * (1 - 0.2) * 0.3 *(1 - 0.4) + (1 -0.1) * (1 - 0.2) * (1 - 0.3) * 0.4 = 0.4404 Quiz of this Question GATE-CS-2015 (Set 1) GATE-GATE-CS-2015 (Set 1) GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Jun, 2021" }, { "code": null, "e": 570, "s": 28, "text": "Consider a LAN with four nodes S1, S2, S3 and S4. Time is divided into fixed-size slots, and a node can begin its transmission only at the beginning of a slot. A collision is said to have occurred if more than one node transmit in the same slot. The probabilities of generation of a frame in a time slot by S1, S2, S3 and S4 are 0.1, 0.2, 0.3 and 0.4, respectively. The probability of sending a frame in the first slot without any collision by any of these four stations is _________.(A) 0.462(B) 0.711(C) 0.5(D) 0.652Answer: (A)Explanation:" }, { "code": null, "e": 1120, "s": 570, "text": "The probability of sending a frame in the first slot \nwithout any collision by any of these four stations is\nsum of following 4 probabilities\n\nProbability that S1 sends a frame and no one else does + \nProbability thatS2 sends a frame and no one else does +\nProbability thatS3 sends a frame and no one else does +\nProbability thatS4 sends a frame and no one else does\n\n= 0.1 * (1 - 0.2) * (1 - 0.3) *(1 - 0.4) + \n (1 -0.1) * 0.2 * (1 - 0.3) *(1 - 0.4) + \n (1 -0.1) * (1 - 0.2) * 0.3 *(1 - 0.4) + \n (1 -0.1) * (1 - 0.2) * (1 - 0.3) * 0.4\n\n= 0.4404 " }, { "code": null, "e": 1142, "s": 1120, "text": "Quiz of this Question" }, { "code": null, "e": 1163, "s": 1142, "text": "GATE-CS-2015 (Set 1)" }, { "code": null, "e": 1189, "s": 1163, "text": "GATE-GATE-CS-2015 (Set 1)" }, { "code": null, "e": 1194, "s": 1189, "text": "GATE" } ]
Count of smaller or equal elements in sorted array
22 Jun, 2022 Given a sorted array of size n. Find a number of elements that are less than or equal to a given element.Examples: Input : arr[] = {1, 2, 4, 5, 8, 10} key = 9 Output : 5 Elements less than or equal to 9 are 1, 2, 4, 5, 8 therefore result will be 5. Input : arr[] = {1, 2, 2, 2, 5, 7, 9} key = 2 Output : 4 Elements less than or equal to 2 are 1, 2, 2, 2 therefore result will be 4. Naive approach: Search whole array linearly and count elements that are less than or equal to the key. Time Complexity: O(n).Auxiliary Space: O(1).Efficient approach: As the whole array is sorted we can use binary search to find result. Case 1: When key is present in array, the last position of key is the result.Case 2: When key is not present in array, we ignore left half if key is greater than mid. If key is smaller than mid, we ignore right half. We always end up with a case where key is present before middle element. C++ Java Python3 C# PHP Javascript // C++ program to count smaller or equal// elements in sorted array.#include <bits/stdc++.h>using namespace std; // A binary search function. It returns// number of elements less than of equal// to given keyint binarySearchCount(int arr[], int n, int key){ int left = 0, right = n; int mid; while (left < right) { mid = (right + left) >> 1; // Check if key is present in array if (arr[mid] == key) { // If duplicates are present it returns // the position of last element while (mid + 1 < n && arr[mid + 1] == key) mid++; break; } // If key is smaller, ignore right half else if (arr[mid] > key) right = mid; // If key is greater, ignore left half else left = mid + 1; } // If key is not found // in array then it will be // before mid while (mid > -1 && arr[mid] > key) mid--; // Return mid + 1 because of 0-based indexing // of array return mid + 1;} // Driver program to test binarySearchCount()int main(){ int arr[] = { 1, 2, 4, 5, 8, 10 }; int key = 11; int n = sizeof(arr) / sizeof(arr[0]); cout << binarySearchCount(arr, n, key); return 0;} // Java program to count smaller or equal// elements in sorted array. class GFG { // A binary search function. It returns // number of elements less than of equal // to given key static int binarySearchCount(int arr[], int n, int key) { int left = 0, right = n; int mid = 0; while (left < right) { mid = (right + left) >> 1; // Check if key is present in array if (arr[mid] == key) { // If duplicates are present it returns // the position of last element while (mid + 1 < n && arr[mid + 1] == key) mid++; break; } // If key is smaller, ignore right half else if (arr[mid] > key) right = mid; // If key is greater, ignore left half else left = mid + 1; } // If key is not found in array then it will be // before mid while (mid > -1 && arr[mid] > key) mid--; // Return mid + 1 because of 0-based indexing // of array return mid + 1; } // Driver code public static void main(String[] args) { int arr[] = { 1, 2, 4, 5, 8, 10 }; int key = 11; int n = arr.length; System.out.print(binarySearchCount(arr, n, key)); }} // This code is contributed by Anant Agarwal. # Python program to# count smaller or equal# elements in sorted array. # A binary search function.# It returns# number of elements# less than of equal# to given keydef binarySearchCount(arr, n, key): left = 0 right = n mid = 0 while (left < right): mid = (right + left)//2 # Check if key is present in array if (arr[mid] == key): # If duplicates are # present it returns # the position of last element while (mid + 1<n and arr[mid + 1] == key): mid+= 1 break # If key is smaller, # ignore right half elif (arr[mid] > key): right = mid # If key is greater, # ignore left half else: left = mid + 1 # If key is not found in # array then it will be # before mid while (mid > -1 and arr[mid] > key): mid-= 1 # Return mid + 1 because # of 0-based indexing # of array return mid + 1 # Driver code arr = [1, 2, 4, 5, 8, 10]key = 11n = len(arr) print(binarySearchCount(arr, n, key)) # This code is contributed# by Anant Agarwal. // C# program to count smaller or// equal elements in sorted array.using System; class GFG { // A binary search function. // It returns number of elements // less than of equal to given key static int binarySearchCount(int[] arr, int n, int key) { int left = 0; int right = n; int mid = 0; while (left < right) { mid = (right + left) / 2; // Check if key is // present in array if (arr[mid] == key) { // If duplicates are present // it returns the position // of last element while (mid + 1 < n && arr[mid + 1] == key) mid++; break; } // If key is smaller, // ignore right half else if (arr[mid] > key) right = mid; // If key is greater, // ignore left half else left = mid + 1; } // If key is not found in array // then it will be before mid while (mid > -1 && arr[mid] > key) mid--; // Return mid + 1 because of // 0-based indexing of array return mid + 1; } // Driver code static public void Main() { int[] arr = { 1, 2, 4, 5, 8, 10 }; int key = 11; int n = arr.Length; Console.Write(binarySearchCount(arr, n, key)); }} // This code is contributed by ajit. <?php// PHP program to count// smaller or equal// elements in sorted array. // A binary search function.// It returns number of// elements less than of// equal to given keyfunction binarySearchCount($arr, $n, $key){ $left = 0; $right = $n; $mid; while ($left < $right) { $mid = ($right + $left) / 2; // Check if key is // present in array if ($arr[$mid] == $key) { // If duplicates are // present it returns // the position of // last element while ($mid + 1 < $n && $arr[$mid + 1] == $key) $mid++; break; } // If key is smaller, // ignore right half else if ($mid > -1 && $arr[$mid] > $key) $right = $mid; // If key is greater, // ignore left half else $left = $mid + 1; } // If key is not found in // array then it will be // before mid while ($arr[$mid] > $key) $mid--; // Return mid + 1 because // of 0-based indexing // of array return $mid + 1;} // Driver Code$arr = array (1, 2, 4, 5, 8, 10);$key = 11;$n = sizeof($arr) ;echo binarySearchCount($arr, $n, $key); // This code is contributed by ajit?> <script> // Javascript program to // count smaller or equal // elements in sorted array. // A binary search function. It returns // number of elements less than of equal // to given key function binarySearchCount(arr, n, key) { let left = 0, right = n; let mid; while (left < right) { mid = (right + left) >> 1; // Check if key is present in array if (arr[mid] == key) { // If duplicates are // present it returns // the position of last element while ((mid + 1) < n && arr[mid + 1] == key) mid++; break; } // If key is smaller, ignore right half else if (arr[mid] > key) right = mid; // If key is greater, ignore left half else left = mid + 1; } // If key is not found // in array then it will be // before mid while (mid > -1 && arr[mid] > key) mid--; // Return mid + 1 because of 0-based indexing // of array return mid + 1; } let arr = [ 1, 2, 4, 5, 8, 10 ]; let key = 11; let n = arr.length; document.write(binarySearchCount(arr, n, key)); </script> 6 Time Complexity: O(n).Auxiliary Space: O(1). Although this solution performs better on average, the worst-case time complexity of this solution is still O(n).The above program can be implemented using a more simplified binary search. The idea is to check if the middle element is greater than the given element then update right index as mid – 1 but if the middle element is less than or equal to key update answer as mid + 1 and left index as mid + 1. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to count smaller or equal// elements in sorted array#include <bits/stdc++.h>using namespace std; // A binary search function to return// the number of elements less than// or equal to the given keyint binarySearchCount(int arr[], int n, int key){ int left = 0; int right = n - 1; int count = 0; while (left <= right) { int mid = (right + left) / 2; // Check if middle element is // less than or equal to key if (arr[mid] <= key) { // At least (mid + 1) elements are there // whose values are less than // or equal to key count = mid + 1; left = mid + 1; } // If key is smaller, ignore right half else right = mid - 1; } return count;} // Driver codeint main(){ int arr[] = { 1, 2, 4, 11, 11, 16 }; int key = 11; int n = sizeof(arr) / sizeof(arr[0]); cout << binarySearchCount(arr, n, key); return 0;} // Java program to count smaller or equalimport java.io.*; class GFG{ // A binary search function to return// the number of elements less than// or equal to the given keystatic int binarySearchCount(int arr[], int n, int key){ int left = 0; int right = n - 1; int count = 0; while (left <= right) { int mid = (right + left) / 2; // Check if middle element is // less than or equal to key if (arr[mid] <= key) { // At least (mid + 1) elements are there // whose values are less than // or equal to key count = mid + 1; left = mid + 1; } // If key is smaller, ignore right half else right = mid - 1; } return count;} // Driver codepublic static void main (String[] args){ int arr[] = { 1, 2, 4, 11, 11, 16 }; int key = 11; int n = arr.length; System.out.println (binarySearchCount(arr, n, key));}} // The code is contributed by Sachin. # Python3 program to count smaller or equal# elements in sorted array # A binary search function to return# the number of elements less than# or equal to the given keydef binarySearchCount(arr, n, key): left = 0 right = n - 1 count = 0 while (left <= right): mid = int((right + left) / 2) # Check if middle element is # less than or equal to key if (arr[mid] <= key): # At least (mid + 1) elements are there # whose values are less than # or equal to key count = mid + 1 left = mid + 1 # If key is smaller, ignore right half else: right = mid - 1 return count # Driver codearr = [ 1, 2, 4, 11, 11, 16 ]key = 11n = len(arr) print( binarySearchCount(arr, n, key)) # This code is contributed by Arnab Kundu // C# program to count smaller or equalusing System; class GFG{ // A binary search function to return// the number of elements less than// or equal to the given keystatic int binarySearchCount(int []arr, int n, int key){ int left = 0; int right = n - 1; int count = 0; while (left <= right) { int mid = (right + left) / 2; // Check if middle element is // less than or equal to key if (arr[mid] <= key) { // At least (mid + 1) elements are there // whose values are less than // or equal to key count = mid + 1; left = mid + 1; } // If key is smaller, // ignore right half else right = mid - 1; } return count;} // Driver codepublic static void Main (String[] args){ int []arr = { 1, 2, 4, 11, 11, 16 }; int key = 11; int n = arr.Length; Console.WriteLine(binarySearchCount(arr, n, key));}} // This code is contributed by PrinciRaj1992 <script> // Javascript program to count smaller or equal // elements in sorted array // A binary search function to return // the number of elements less than // or equal to the given key function binarySearchCount(arr, n, key) { let left = 0; let right = n - 1; let count = 0; while (left <= right) { let mid = parseInt((right + left) / 2, 10); // Check if middle element is // less than or equal to key if (arr[mid] <= key) { // At least (mid + 1) elements are there // whose values are less than // or equal to key count = mid + 1; left = mid + 1; } // If key is smaller, ignore right half else right = mid - 1; } return count; } let arr = [ 1, 2, 4, 11, 11, 16 ]; let key = 11; let n = arr.length; document.write(binarySearchCount(arr, n, key)); // This code is contributed by rameshtravel07.</script> 5 Time Complexity: O(log(n)).Auxiliary Space: O(1). This article is contributed by nuclode. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. jit_t Brij Raj Kishore Sakshi_Srivastava Sach_Code princiraj1992 andrew1234 princevishwakarma1 rameshtravel07 divyesh072019 amartyaghoshgfg anandkumarshivam2266 Binary Search Arrays Arrays Binary Search Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. 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 K'th Smallest/Largest Element in Unsorted Array | Set 1 Subset Sum Problem | DP-25 Introduction to Data Structures Python | Using 2D arrays/lists the right way Search an element in a sorted and rotated array Find Second largest element in an array
[ { "code": null, "e": 52, "s": 24, "text": "\n22 Jun, 2022" }, { "code": null, "e": 169, "s": 52, "text": "Given a sorted array of size n. Find a number of elements that are less than or equal to a given element.Examples: " }, { "code": null, "e": 456, "s": 169, "text": "Input : arr[] = {1, 2, 4, 5, 8, 10}\n key = 9\nOutput : 5\nElements less than or equal to 9 are 1, 2, \n4, 5, 8 therefore result will be 5.\n\nInput : arr[] = {1, 2, 2, 2, 5, 7, 9}\n key = 2\nOutput : 4\nElements less than or equal to 2 are 1, 2, \n2, 2 therefore result will be 4. " }, { "code": null, "e": 560, "s": 456, "text": "Naive approach: Search whole array linearly and count elements that are less than or equal to the key. " }, { "code": null, "e": 986, "s": 560, "text": "Time Complexity: O(n).Auxiliary Space: O(1).Efficient approach: As the whole array is sorted we can use binary search to find result. Case 1: When key is present in array, the last position of key is the result.Case 2: When key is not present in array, we ignore left half if key is greater than mid. If key is smaller than mid, we ignore right half. We always end up with a case where key is present before middle element. " }, { "code": null, "e": 990, "s": 986, "text": "C++" }, { "code": null, "e": 995, "s": 990, "text": "Java" }, { "code": null, "e": 1003, "s": 995, "text": "Python3" }, { "code": null, "e": 1006, "s": 1003, "text": "C#" }, { "code": null, "e": 1010, "s": 1006, "text": "PHP" }, { "code": null, "e": 1021, "s": 1010, "text": "Javascript" }, { "code": "// C++ program to count smaller or equal// elements in sorted array.#include <bits/stdc++.h>using namespace std; // A binary search function. It returns// number of elements less than of equal// to given keyint binarySearchCount(int arr[], int n, int key){ int left = 0, right = n; int mid; while (left < right) { mid = (right + left) >> 1; // Check if key is present in array if (arr[mid] == key) { // If duplicates are present it returns // the position of last element while (mid + 1 < n && arr[mid + 1] == key) mid++; break; } // If key is smaller, ignore right half else if (arr[mid] > key) right = mid; // If key is greater, ignore left half else left = mid + 1; } // If key is not found // in array then it will be // before mid while (mid > -1 && arr[mid] > key) mid--; // Return mid + 1 because of 0-based indexing // of array return mid + 1;} // Driver program to test binarySearchCount()int main(){ int arr[] = { 1, 2, 4, 5, 8, 10 }; int key = 11; int n = sizeof(arr) / sizeof(arr[0]); cout << binarySearchCount(arr, n, key); return 0;}", "e": 2278, "s": 1021, "text": null }, { "code": "// Java program to count smaller or equal// elements in sorted array. class GFG { // A binary search function. It returns // number of elements less than of equal // to given key static int binarySearchCount(int arr[], int n, int key) { int left = 0, right = n; int mid = 0; while (left < right) { mid = (right + left) >> 1; // Check if key is present in array if (arr[mid] == key) { // If duplicates are present it returns // the position of last element while (mid + 1 < n && arr[mid + 1] == key) mid++; break; } // If key is smaller, ignore right half else if (arr[mid] > key) right = mid; // If key is greater, ignore left half else left = mid + 1; } // If key is not found in array then it will be // before mid while (mid > -1 && arr[mid] > key) mid--; // Return mid + 1 because of 0-based indexing // of array return mid + 1; } // Driver code public static void main(String[] args) { int arr[] = { 1, 2, 4, 5, 8, 10 }; int key = 11; int n = arr.length; System.out.print(binarySearchCount(arr, n, key)); }} // This code is contributed by Anant Agarwal.", "e": 3494, "s": 2278, "text": null }, { "code": "# Python program to# count smaller or equal# elements in sorted array. # A binary search function.# It returns# number of elements# less than of equal# to given keydef binarySearchCount(arr, n, key): left = 0 right = n mid = 0 while (left < right): mid = (right + left)//2 # Check if key is present in array if (arr[mid] == key): # If duplicates are # present it returns # the position of last element while (mid + 1<n and arr[mid + 1] == key): mid+= 1 break # If key is smaller, # ignore right half elif (arr[mid] > key): right = mid # If key is greater, # ignore left half else: left = mid + 1 # If key is not found in # array then it will be # before mid while (mid > -1 and arr[mid] > key): mid-= 1 # Return mid + 1 because # of 0-based indexing # of array return mid + 1 # Driver code arr = [1, 2, 4, 5, 8, 10]key = 11n = len(arr) print(binarySearchCount(arr, n, key)) # This code is contributed# by Anant Agarwal.", "e": 4655, "s": 3494, "text": null }, { "code": "// C# program to count smaller or// equal elements in sorted array.using System; class GFG { // A binary search function. // It returns number of elements // less than of equal to given key static int binarySearchCount(int[] arr, int n, int key) { int left = 0; int right = n; int mid = 0; while (left < right) { mid = (right + left) / 2; // Check if key is // present in array if (arr[mid] == key) { // If duplicates are present // it returns the position // of last element while (mid + 1 < n && arr[mid + 1] == key) mid++; break; } // If key is smaller, // ignore right half else if (arr[mid] > key) right = mid; // If key is greater, // ignore left half else left = mid + 1; } // If key is not found in array // then it will be before mid while (mid > -1 && arr[mid] > key) mid--; // Return mid + 1 because of // 0-based indexing of array return mid + 1; } // Driver code static public void Main() { int[] arr = { 1, 2, 4, 5, 8, 10 }; int key = 11; int n = arr.Length; Console.Write(binarySearchCount(arr, n, key)); }} // This code is contributed by ajit.", "e": 6147, "s": 4655, "text": null }, { "code": "<?php// PHP program to count// smaller or equal// elements in sorted array. // A binary search function.// It returns number of// elements less than of// equal to given keyfunction binarySearchCount($arr, $n, $key){ $left = 0; $right = $n; $mid; while ($left < $right) { $mid = ($right + $left) / 2; // Check if key is // present in array if ($arr[$mid] == $key) { // If duplicates are // present it returns // the position of // last element while ($mid + 1 < $n && $arr[$mid + 1] == $key) $mid++; break; } // If key is smaller, // ignore right half else if ($mid > -1 && $arr[$mid] > $key) $right = $mid; // If key is greater, // ignore left half else $left = $mid + 1; } // If key is not found in // array then it will be // before mid while ($arr[$mid] > $key) $mid--; // Return mid + 1 because // of 0-based indexing // of array return $mid + 1;} // Driver Code$arr = array (1, 2, 4, 5, 8, 10);$key = 11;$n = sizeof($arr) ;echo binarySearchCount($arr, $n, $key); // This code is contributed by ajit?>", "e": 7407, "s": 6147, "text": null }, { "code": "<script> // Javascript program to // count smaller or equal // elements in sorted array. // A binary search function. It returns // number of elements less than of equal // to given key function binarySearchCount(arr, n, key) { let left = 0, right = n; let mid; while (left < right) { mid = (right + left) >> 1; // Check if key is present in array if (arr[mid] == key) { // If duplicates are // present it returns // the position of last element while ((mid + 1) < n && arr[mid + 1] == key) mid++; break; } // If key is smaller, ignore right half else if (arr[mid] > key) right = mid; // If key is greater, ignore left half else left = mid + 1; } // If key is not found // in array then it will be // before mid while (mid > -1 && arr[mid] > key) mid--; // Return mid + 1 because of 0-based indexing // of array return mid + 1; } let arr = [ 1, 2, 4, 5, 8, 10 ]; let key = 11; let n = arr.length; document.write(binarySearchCount(arr, n, key)); </script>", "e": 8741, "s": 7407, "text": null }, { "code": null, "e": 8743, "s": 8741, "text": "6" }, { "code": null, "e": 8788, "s": 8743, "text": "Time Complexity: O(n).Auxiliary Space: O(1)." }, { "code": null, "e": 9196, "s": 8788, "text": "Although this solution performs better on average, the worst-case time complexity of this solution is still O(n).The above program can be implemented using a more simplified binary search. The idea is to check if the middle element is greater than the given element then update right index as mid – 1 but if the middle element is less than or equal to key update answer as mid + 1 and left index as mid + 1." }, { "code": null, "e": 9247, "s": 9196, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 9251, "s": 9247, "text": "C++" }, { "code": null, "e": 9256, "s": 9251, "text": "Java" }, { "code": null, "e": 9264, "s": 9256, "text": "Python3" }, { "code": null, "e": 9267, "s": 9264, "text": "C#" }, { "code": null, "e": 9278, "s": 9267, "text": "Javascript" }, { "code": "// C++ program to count smaller or equal// elements in sorted array#include <bits/stdc++.h>using namespace std; // A binary search function to return// the number of elements less than// or equal to the given keyint binarySearchCount(int arr[], int n, int key){ int left = 0; int right = n - 1; int count = 0; while (left <= right) { int mid = (right + left) / 2; // Check if middle element is // less than or equal to key if (arr[mid] <= key) { // At least (mid + 1) elements are there // whose values are less than // or equal to key count = mid + 1; left = mid + 1; } // If key is smaller, ignore right half else right = mid - 1; } return count;} // Driver codeint main(){ int arr[] = { 1, 2, 4, 11, 11, 16 }; int key = 11; int n = sizeof(arr) / sizeof(arr[0]); cout << binarySearchCount(arr, n, key); return 0;}", "e": 10250, "s": 9278, "text": null }, { "code": "// Java program to count smaller or equalimport java.io.*; class GFG{ // A binary search function to return// the number of elements less than// or equal to the given keystatic int binarySearchCount(int arr[], int n, int key){ int left = 0; int right = n - 1; int count = 0; while (left <= right) { int mid = (right + left) / 2; // Check if middle element is // less than or equal to key if (arr[mid] <= key) { // At least (mid + 1) elements are there // whose values are less than // or equal to key count = mid + 1; left = mid + 1; } // If key is smaller, ignore right half else right = mid - 1; } return count;} // Driver codepublic static void main (String[] args){ int arr[] = { 1, 2, 4, 11, 11, 16 }; int key = 11; int n = arr.length; System.out.println (binarySearchCount(arr, n, key));}} // The code is contributed by Sachin.", "e": 11277, "s": 10250, "text": null }, { "code": "# Python3 program to count smaller or equal# elements in sorted array # A binary search function to return# the number of elements less than# or equal to the given keydef binarySearchCount(arr, n, key): left = 0 right = n - 1 count = 0 while (left <= right): mid = int((right + left) / 2) # Check if middle element is # less than or equal to key if (arr[mid] <= key): # At least (mid + 1) elements are there # whose values are less than # or equal to key count = mid + 1 left = mid + 1 # If key is smaller, ignore right half else: right = mid - 1 return count # Driver codearr = [ 1, 2, 4, 11, 11, 16 ]key = 11n = len(arr) print( binarySearchCount(arr, n, key)) # This code is contributed by Arnab Kundu", "e": 12123, "s": 11277, "text": null }, { "code": "// C# program to count smaller or equalusing System; class GFG{ // A binary search function to return// the number of elements less than// or equal to the given keystatic int binarySearchCount(int []arr, int n, int key){ int left = 0; int right = n - 1; int count = 0; while (left <= right) { int mid = (right + left) / 2; // Check if middle element is // less than or equal to key if (arr[mid] <= key) { // At least (mid + 1) elements are there // whose values are less than // or equal to key count = mid + 1; left = mid + 1; } // If key is smaller, // ignore right half else right = mid - 1; } return count;} // Driver codepublic static void Main (String[] args){ int []arr = { 1, 2, 4, 11, 11, 16 }; int key = 11; int n = arr.Length; Console.WriteLine(binarySearchCount(arr, n, key));}} // This code is contributed by PrinciRaj1992", "e": 13163, "s": 12123, "text": null }, { "code": "<script> // Javascript program to count smaller or equal // elements in sorted array // A binary search function to return // the number of elements less than // or equal to the given key function binarySearchCount(arr, n, key) { let left = 0; let right = n - 1; let count = 0; while (left <= right) { let mid = parseInt((right + left) / 2, 10); // Check if middle element is // less than or equal to key if (arr[mid] <= key) { // At least (mid + 1) elements are there // whose values are less than // or equal to key count = mid + 1; left = mid + 1; } // If key is smaller, ignore right half else right = mid - 1; } return count; } let arr = [ 1, 2, 4, 11, 11, 16 ]; let key = 11; let n = arr.length; document.write(binarySearchCount(arr, n, key)); // This code is contributed by rameshtravel07.</script>", "e": 14240, "s": 13163, "text": null }, { "code": null, "e": 14242, "s": 14240, "text": "5" }, { "code": null, "e": 14292, "s": 14242, "text": "Time Complexity: O(log(n)).Auxiliary Space: O(1)." }, { "code": null, "e": 14713, "s": 14292, "text": "This article is contributed by nuclode. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 14719, "s": 14713, "text": "jit_t" }, { "code": null, "e": 14736, "s": 14719, "text": "Brij Raj Kishore" }, { "code": null, "e": 14754, "s": 14736, "text": "Sakshi_Srivastava" }, { "code": null, "e": 14764, "s": 14754, "text": "Sach_Code" }, { "code": null, "e": 14778, "s": 14764, "text": "princiraj1992" }, { "code": null, "e": 14789, "s": 14778, "text": "andrew1234" }, { "code": null, "e": 14808, "s": 14789, "text": "princevishwakarma1" }, { "code": null, "e": 14823, "s": 14808, "text": "rameshtravel07" }, { "code": null, "e": 14837, "s": 14823, "text": "divyesh072019" }, { "code": null, "e": 14853, "s": 14837, "text": "amartyaghoshgfg" }, { "code": null, "e": 14874, "s": 14853, "text": "anandkumarshivam2266" }, { "code": null, "e": 14888, "s": 14874, "text": "Binary Search" }, { "code": null, "e": 14895, "s": 14888, "text": "Arrays" }, { "code": null, "e": 14902, "s": 14895, "text": "Arrays" }, { "code": null, "e": 14916, "s": 14902, "text": "Binary Search" }, { "code": null, "e": 15014, "s": 14916, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 15046, "s": 15014, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 15060, "s": 15046, "text": "Linear Search" }, { "code": null, "e": 15145, "s": 15060, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 15168, "s": 15145, "text": "Introduction to Arrays" }, { "code": null, "e": 15224, "s": 15168, "text": "K'th Smallest/Largest Element in Unsorted Array | Set 1" }, { "code": null, "e": 15251, "s": 15224, "text": "Subset Sum Problem | DP-25" }, { "code": null, "e": 15283, "s": 15251, "text": "Introduction to Data Structures" }, { "code": null, "e": 15328, "s": 15283, "text": "Python | Using 2D arrays/lists the right way" }, { "code": null, "e": 15376, "s": 15328, "text": "Search an element in a sorted and rotated array" } ]
Program to find largest sum of non-adjacent elements of a list in Python
Suppose we have a list of numbers called nums, we will define a function that returns the largest sum of non-adjacent numbers. Here the numbers can be 0 or negative. So, if the input is like [3, 5, 7, 3, 6], then the output will be 16, as we can take 3, 7, and 6 to get 16. To solve this, we will follow these steps− if size of nums <= 2, thenreturn maximum of nums if size of nums <= 2, then return maximum of nums return maximum of nums noTake := 0 noTake := 0 take := nums[0] take := nums[0] for i in range 1 to size of nums, dotake := noTake + nums[i]noTake := maximum of noTake and take for i in range 1 to size of nums, do take := noTake + nums[i] take := noTake + nums[i] noTake := maximum of noTake and take noTake := maximum of noTake and take return maximum of noTake and take return maximum of noTake and take Let us see the following implementation to get better understanding − Live Demo class Solution: def solve(self, nums): if len(nums) <= 2: return max(nums) noTake = 0 take = nums[0] for i in range(1, len(nums)): take, noTake = noTake + nums[i], max(noTake, take) return max(noTake, take) ob = Solution() nums = [3, 5, 7, 3, 6] print(ob.solve(nums)) [3, 5, 7, 3, 6] 16
[ { "code": null, "e": 1353, "s": 1187, "text": "Suppose we have a list of numbers called nums, we will define a function that returns the\nlargest sum of non-adjacent numbers. Here the numbers can be 0 or negative." }, { "code": null, "e": 1461, "s": 1353, "text": "So, if the input is like [3, 5, 7, 3, 6], then the output will be 16, as we can take 3, 7, and 6 to get\n16." }, { "code": null, "e": 1504, "s": 1461, "text": "To solve this, we will follow these steps−" }, { "code": null, "e": 1553, "s": 1504, "text": "if size of nums <= 2, thenreturn maximum of nums" }, { "code": null, "e": 1580, "s": 1553, "text": "if size of nums <= 2, then" }, { "code": null, "e": 1603, "s": 1580, "text": "return maximum of nums" }, { "code": null, "e": 1626, "s": 1603, "text": "return maximum of nums" }, { "code": null, "e": 1638, "s": 1626, "text": "noTake := 0" }, { "code": null, "e": 1650, "s": 1638, "text": "noTake := 0" }, { "code": null, "e": 1666, "s": 1650, "text": "take := nums[0]" }, { "code": null, "e": 1682, "s": 1666, "text": "take := nums[0]" }, { "code": null, "e": 1779, "s": 1682, "text": "for i in range 1 to size of nums, dotake := noTake + nums[i]noTake := maximum of noTake and take" }, { "code": null, "e": 1816, "s": 1779, "text": "for i in range 1 to size of nums, do" }, { "code": null, "e": 1841, "s": 1816, "text": "take := noTake + nums[i]" }, { "code": null, "e": 1866, "s": 1841, "text": "take := noTake + nums[i]" }, { "code": null, "e": 1903, "s": 1866, "text": "noTake := maximum of noTake and take" }, { "code": null, "e": 1940, "s": 1903, "text": "noTake := maximum of noTake and take" }, { "code": null, "e": 1974, "s": 1940, "text": "return maximum of noTake and take" }, { "code": null, "e": 2008, "s": 1974, "text": "return maximum of noTake and take" }, { "code": null, "e": 2078, "s": 2008, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 2089, "s": 2078, "text": " Live Demo" }, { "code": null, "e": 2411, "s": 2089, "text": "class Solution:\n def solve(self, nums):\n if len(nums) <= 2:\n return max(nums)\n noTake = 0\n take = nums[0]\n for i in range(1, len(nums)):\n take, noTake = noTake + nums[i], max(noTake, take)\n return max(noTake, take)\nob = Solution()\nnums = [3, 5, 7, 3, 6]\nprint(ob.solve(nums))" }, { "code": null, "e": 2427, "s": 2411, "text": "[3, 5, 7, 3, 6]" }, { "code": null, "e": 2430, "s": 2427, "text": "16" } ]
Invisible Cloak using OpenCV | Python Project
07 Jun, 2019 Have you ever seen Harry Potter’s Invisible Cloak; Was it wonderful? Have you ever wanted to wear that cloak? If Yes!! then in this post, we will build the same cloak which Harry Potter uses to become invisible. Yes, we are not building it in a real way but it is all about graphics trickery. In this post, we will learn how to create our own ‘Invisibility Cloak’ using simple computer vision techniques in OpenCV. Here we have written this code in Python because it provides exhaustive and sufficient library to build this program. Here, we will create this magical experience using an image processing technique called Color detection and segmentation. In order to run this code, you need an mp4 video named “video.mp4“. You must have a cloth of same color and no other color should be visible into that cloth. We are taking the red cloth. If you are taking some other cloth, the code will remain the same but with minute changes. Why Red? Green is my favorite?Sure, we could have used green, isn’t Red the magician’s color? Jokes aside, colors like green or blue will also work fine with a little bit of changes in code.This technique is opposite to the Green Screening. In green screening, we remove background but here we will remove the foreground frame. So let’s start our code. Algorithm: 1. Capture and store the background frame [ This will be done for some seconds ]2. Detect the red colored cloth using color detection and segmentation algorithm.3. Segment out the red colored cloth by generating a mask. [ used in code ]4. Generate the final augmented output to create a magical effect. [ video.mp4 ] Below is the Code: import cv2import numpy as npimport time # replace the red pixels ( or undesired area ) with# background pixels to generate the invisibility feature. ## 1. Hue: This channel encodes color information. Hue can be# thought of an angle where 0 degree corresponds to the red color, # 120 degrees corresponds to the green color, and 240 degrees # corresponds to the blue color. ## 2. Saturation: This channel encodes the intensity/purity of color.# For example, pink is less saturated than red. ## 3. Value: This channel encodes the brightness of color.# Shading and gloss components of an image appear in this # channel reading the videocapture video # in order to check the cv2 versionprint(cv2.__version__) # taking video.mp4 as input.# Make your path according to your needs capture_video = cv2.VideoCapture("video.mp4") # give the camera to warm uptime.sleep(1) count = 0 background = 0 # capturing the background in range of 60# you should have video that have some seconds# dedicated to background frame so that it # could easily save the background imagefor i in range(60): return_val, background = capture_video.read() if return_val == False : continue background = np.flip(background, axis = 1) # flipping of the frame # we are reading from video while (capture_video.isOpened()): return_val, img = capture_video.read() if not return_val : break count = count + 1 img = np.flip(img, axis = 1) # convert the image - BGR to HSV # as we focused on detection of red color # converting BGR to HSV for better # detection or you can convert it to gray hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) #-------------------------------------BLOCK----------------------------# # ranges should be carefully chosen # setting the lower and upper range for mask1 lower_red = np.array([100, 40, 40]) upper_red = np.array([100, 255, 255]) mask1 = cv2.inRange(hsv, lower_red, upper_red) # setting the lower and upper range for mask2 lower_red = np.array([155, 40, 40]) upper_red = np.array([180, 255, 255]) mask2 = cv2.inRange(hsv, lower_red, upper_red) #----------------------------------------------------------------------# # the above block of code could be replaced with # some other code depending upon the color of your cloth mask1 = mask1 + mask2 # Refining the mask corresponding to the detected red color mask1 = cv2.morphologyEx(mask1, cv2.MORPH_OPEN, np.ones((3, 3), np.uint8), iterations = 2) mask1 = cv2.dilate(mask1, np.ones((3, 3), np.uint8), iterations = 1) mask2 = cv2.bitwise_not(mask1) # Generating the final output res1 = cv2.bitwise_and(background, background, mask = mask1) res2 = cv2.bitwise_and(img, img, mask = mask2) final_output = cv2.addWeighted(res1, 1, res2, 1, 0) cv2.imshow("INVISIBLE MAN", final_output) k = cv2.waitKey(10) if k == 27: break Output:Harry Potter's Invisible Cloak using OpenCV and Python ( Image Processing ) - YouTubeAditya Atri18 subscribersHarry Potter's Invisible Cloak using OpenCV and Python ( Image Processing )Watch 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 / 0:56•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=9P-yUFdXG-I" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> You can check source code on the project github repository, for input video and more details – here Reference: http://datasciencenthusiast.com/?p=71 Image-Processing OpenCV Project Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. 10 Best Web Development Projects For Your Resume Simple Chat Room using Python Twitter Sentiment Analysis using Python A Group chat application in Java Student Information Management System Read JSON file using Python Python map() function Adding new column to existing DataFrame in Pandas Python Dictionary How to get column names in Pandas dataframe
[ { "code": null, "e": 54, "s": 26, "text": "\n07 Jun, 2019" }, { "code": null, "e": 347, "s": 54, "text": "Have you ever seen Harry Potter’s Invisible Cloak; Was it wonderful? Have you ever wanted to wear that cloak? If Yes!! then in this post, we will build the same cloak which Harry Potter uses to become invisible. Yes, we are not building it in a real way but it is all about graphics trickery." }, { "code": null, "e": 587, "s": 347, "text": "In this post, we will learn how to create our own ‘Invisibility Cloak’ using simple computer vision techniques in OpenCV. Here we have written this code in Python because it provides exhaustive and sufficient library to build this program." }, { "code": null, "e": 987, "s": 587, "text": "Here, we will create this magical experience using an image processing technique called Color detection and segmentation. In order to run this code, you need an mp4 video named “video.mp4“. You must have a cloth of same color and no other color should be visible into that cloth. We are taking the red cloth. If you are taking some other cloth, the code will remain the same but with minute changes." }, { "code": null, "e": 1340, "s": 987, "text": "Why Red? Green is my favorite?Sure, we could have used green, isn’t Red the magician’s color? Jokes aside, colors like green or blue will also work fine with a little bit of changes in code.This technique is opposite to the Green Screening. In green screening, we remove background but here we will remove the foreground frame. So let’s start our code." }, { "code": null, "e": 1351, "s": 1340, "text": "Algorithm:" }, { "code": null, "e": 1668, "s": 1351, "text": "1. Capture and store the background frame [ This will be done for some seconds ]2. Detect the red colored cloth using color detection and segmentation algorithm.3. Segment out the red colored cloth by generating a mask. [ used in code ]4. Generate the final augmented output to create a magical effect. [ video.mp4 ]" }, { "code": null, "e": 1687, "s": 1668, "text": "Below is the Code:" }, { "code": "import cv2import numpy as npimport time # replace the red pixels ( or undesired area ) with# background pixels to generate the invisibility feature. ## 1. Hue: This channel encodes color information. Hue can be# thought of an angle where 0 degree corresponds to the red color, # 120 degrees corresponds to the green color, and 240 degrees # corresponds to the blue color. ## 2. Saturation: This channel encodes the intensity/purity of color.# For example, pink is less saturated than red. ## 3. Value: This channel encodes the brightness of color.# Shading and gloss components of an image appear in this # channel reading the videocapture video # in order to check the cv2 versionprint(cv2.__version__) # taking video.mp4 as input.# Make your path according to your needs capture_video = cv2.VideoCapture(\"video.mp4\") # give the camera to warm uptime.sleep(1) count = 0 background = 0 # capturing the background in range of 60# you should have video that have some seconds# dedicated to background frame so that it # could easily save the background imagefor i in range(60): return_val, background = capture_video.read() if return_val == False : continue background = np.flip(background, axis = 1) # flipping of the frame # we are reading from video while (capture_video.isOpened()): return_val, img = capture_video.read() if not return_val : break count = count + 1 img = np.flip(img, axis = 1) # convert the image - BGR to HSV # as we focused on detection of red color # converting BGR to HSV for better # detection or you can convert it to gray hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) #-------------------------------------BLOCK----------------------------# # ranges should be carefully chosen # setting the lower and upper range for mask1 lower_red = np.array([100, 40, 40]) upper_red = np.array([100, 255, 255]) mask1 = cv2.inRange(hsv, lower_red, upper_red) # setting the lower and upper range for mask2 lower_red = np.array([155, 40, 40]) upper_red = np.array([180, 255, 255]) mask2 = cv2.inRange(hsv, lower_red, upper_red) #----------------------------------------------------------------------# # the above block of code could be replaced with # some other code depending upon the color of your cloth mask1 = mask1 + mask2 # Refining the mask corresponding to the detected red color mask1 = cv2.morphologyEx(mask1, cv2.MORPH_OPEN, np.ones((3, 3), np.uint8), iterations = 2) mask1 = cv2.dilate(mask1, np.ones((3, 3), np.uint8), iterations = 1) mask2 = cv2.bitwise_not(mask1) # Generating the final output res1 = cv2.bitwise_and(background, background, mask = mask1) res2 = cv2.bitwise_and(img, img, mask = mask2) final_output = cv2.addWeighted(res1, 1, res2, 1, 0) cv2.imshow(\"INVISIBLE MAN\", final_output) k = cv2.waitKey(10) if k == 27: break", "e": 4661, "s": 1687, "text": null }, { "code": null, "e": 5600, "s": 4661, "text": "Output:Harry Potter's Invisible Cloak using OpenCV and Python ( Image Processing ) - YouTubeAditya Atri18 subscribersHarry Potter's Invisible Cloak using OpenCV and Python ( Image Processing )Watch 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 / 0:56•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=9P-yUFdXG-I\" 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": 5749, "s": 5600, "text": "You can check source code on the project github repository, for input video and more details – here Reference: http://datasciencenthusiast.com/?p=71" }, { "code": null, "e": 5766, "s": 5749, "text": "Image-Processing" }, { "code": null, "e": 5773, "s": 5766, "text": "OpenCV" }, { "code": null, "e": 5781, "s": 5773, "text": "Project" }, { "code": null, "e": 5788, "s": 5781, "text": "Python" }, { "code": null, "e": 5886, "s": 5788, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5935, "s": 5886, "text": "10 Best Web Development Projects For Your Resume" }, { "code": null, "e": 5965, "s": 5935, "text": "Simple Chat Room using Python" }, { "code": null, "e": 6005, "s": 5965, "text": "Twitter Sentiment Analysis using Python" }, { "code": null, "e": 6038, "s": 6005, "text": "A Group chat application in Java" }, { "code": null, "e": 6076, "s": 6038, "text": "Student Information Management System" }, { "code": null, "e": 6104, "s": 6076, "text": "Read JSON file using Python" }, { "code": null, "e": 6126, "s": 6104, "text": "Python map() function" }, { "code": null, "e": 6176, "s": 6126, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 6194, "s": 6176, "text": "Python Dictionary" } ]
Increment (++) and Decrement (–) Operator Overloading in C++
19 May, 2022 Operator overloading is a feature in object-oriented programming which allows a programmer to redefine a built-in operator to work with user-defined data types. Why Operator Overloading? Let’s say we have defined a class Integer for handling operations on integers. We can have functions add(), subtract(), multiply() and divide() for handling the respective operations. However, to make the code more intuitive and enhance readability, it is preferred to use operators that correspond to the given operations(+, -, *, / respectively) i.e. we can replace the following code.Example: Replace i5 = divide(add(i1, i2), subtract(i3, i4)) by a simpler code: i5 = (i1 + i2) / (i3 - i4) The operator symbol for both prefix(++i) and postfix(i++) are the same. Hence, we need two different function definitions to distinguish between them. This is achieved by passing a dummy int parameter in the postfix version.Here is the code to demonstrate the same. Example: Pre-increment overloading CPP // C++ program to demonstrate// prefix increment operator overloading #include <bits/stdc++.h>using namespace std; class Integer {private: int i; public: // Parameterised constructor Integer(int i = 0) { this->i = i; } // Overloading the prefix operator Integer operator++() { Integer temp; temp.i = ++i; return temp; } // Function to display the value of i void display() { cout << "i = " << i << endl; }}; // Driver functionint main(){ Integer i1(3); cout << "Before increment: "; i1.display(); // Using the pre-increment operator Integer i2 = ++i1; cout << "After pre increment: "; i2.display();} Output: Before increment: i = 3 After pre increment: i = 4 Example: Post-Increment Overloading CPP // C++ program to demonstrate// postfix increment operator// overloading#include <bits/stdc++.h>using namespace std; class Integer {private: int i; public: // Parameterised constructor Integer(int i = 0) { this->i = i; } // Overloading the postfix operator Integer operator++(int) { Integer temp; temp.i = i++; return temp; } // Function to display the value of i void display() { cout << "i = " << i << endl; }}; // Driver functionint main(){ Integer i1(3); cout << "Before increment: "; i1.display(); // Using the post-increment operator Integer i2 = i1++; cout << "After post increment: "; i2.display();} Output: Before increment: i = 3 After post increment: i = 3 Similarly, we can also overload the decrement operator as follows: Example: Pre-Decrement Overloading CPP // C++ program to demonstrate// prefix decrement operator// overloading #include <bits/stdc++.h>using namespace std; class Integer {private: int i; public: // Parameterised constructor Integer(int i = 0) { this->i = i; } // Overloading the prefix operator Integer operator--() { Integer temp; temp.i = --i; return temp; } // Function to display the value of i void display() { cout << "i = " << i << endl; }}; // Driver functionint main(){ Integer i1(3); cout << "Before decrement: "; i1.display(); // Using the pre-decrement operator Integer i2 = --i1; cout << "After pre decrement: "; i2.display();} Output: Before decrement: i = 3 After pre decrement: i = 2 Example: Post-Decrement Overloading CPP // C++ program to demonstrate// postfix decrement operator// overloading#include <bits/stdc++.h>using namespace std; class Integer {private: int i; public: // Parameterised constructor Integer(int i = 0) { this->i = i; } // Overloading the postfix operator Integer operator--(int) { Integer temp; temp.i = i--; return temp; } // Function to display the value of i void display() { cout << "i = " << i << endl; }}; // Driver functionint main(){ Integer i1(3); cout << "Before decrement: "; i1.display(); // Using the post-decrement operator Integer i2 = i1--; cout << "After post decrement: "; i2.display();} Output: Before decrement: i = 3 After post decrement: i = 3 thotasravya28 sackshamsharmaintern cpp-operator cpp-operator-overloading C++ cpp-operator CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n19 May, 2022" }, { "code": null, "e": 215, "s": 54, "text": "Operator overloading is a feature in object-oriented programming which allows a programmer to redefine a built-in operator to work with user-defined data types." }, { "code": null, "e": 243, "s": 215, "text": "Why Operator Overloading? " }, { "code": null, "e": 640, "s": 243, "text": "Let’s say we have defined a class Integer for handling operations on integers. We can have functions add(), subtract(), multiply() and divide() for handling the respective operations. However, to make the code more intuitive and enhance readability, it is preferred to use operators that correspond to the given operations(+, -, *, / respectively) i.e. we can replace the following code.Example: " }, { "code": null, "e": 739, "s": 640, "text": "Replace\ni5 = divide(add(i1, i2), subtract(i3, i4))\n\nby a simpler code:\ni5 = (i1 + i2) / (i3 - i4) " }, { "code": null, "e": 1005, "s": 739, "text": "The operator symbol for both prefix(++i) and postfix(i++) are the same. Hence, we need two different function definitions to distinguish between them. This is achieved by passing a dummy int parameter in the postfix version.Here is the code to demonstrate the same." }, { "code": null, "e": 1041, "s": 1005, "text": "Example: Pre-increment overloading " }, { "code": null, "e": 1045, "s": 1041, "text": "CPP" }, { "code": "// C++ program to demonstrate// prefix increment operator overloading #include <bits/stdc++.h>using namespace std; class Integer {private: int i; public: // Parameterised constructor Integer(int i = 0) { this->i = i; } // Overloading the prefix operator Integer operator++() { Integer temp; temp.i = ++i; return temp; } // Function to display the value of i void display() { cout << \"i = \" << i << endl; }}; // Driver functionint main(){ Integer i1(3); cout << \"Before increment: \"; i1.display(); // Using the pre-increment operator Integer i2 = ++i1; cout << \"After pre increment: \"; i2.display();}", "e": 1745, "s": 1045, "text": null }, { "code": null, "e": 1753, "s": 1745, "text": "Output:" }, { "code": null, "e": 1804, "s": 1753, "text": "Before increment: i = 3\nAfter pre increment: i = 4" }, { "code": null, "e": 1840, "s": 1804, "text": "Example: Post-Increment Overloading" }, { "code": null, "e": 1844, "s": 1840, "text": "CPP" }, { "code": "// C++ program to demonstrate// postfix increment operator// overloading#include <bits/stdc++.h>using namespace std; class Integer {private: int i; public: // Parameterised constructor Integer(int i = 0) { this->i = i; } // Overloading the postfix operator Integer operator++(int) { Integer temp; temp.i = i++; return temp; } // Function to display the value of i void display() { cout << \"i = \" << i << endl; }}; // Driver functionint main(){ Integer i1(3); cout << \"Before increment: \"; i1.display(); // Using the post-increment operator Integer i2 = i1++; cout << \"After post increment: \"; i2.display();}", "e": 2552, "s": 1844, "text": null }, { "code": null, "e": 2560, "s": 2552, "text": "Output:" }, { "code": null, "e": 2612, "s": 2560, "text": "Before increment: i = 3\nAfter post increment: i = 3" }, { "code": null, "e": 2679, "s": 2612, "text": "Similarly, we can also overload the decrement operator as follows:" }, { "code": null, "e": 2714, "s": 2679, "text": "Example: Pre-Decrement Overloading" }, { "code": null, "e": 2718, "s": 2714, "text": "CPP" }, { "code": "// C++ program to demonstrate// prefix decrement operator// overloading #include <bits/stdc++.h>using namespace std; class Integer {private: int i; public: // Parameterised constructor Integer(int i = 0) { this->i = i; } // Overloading the prefix operator Integer operator--() { Integer temp; temp.i = --i; return temp; } // Function to display the value of i void display() { cout << \"i = \" << i << endl; }}; // Driver functionint main(){ Integer i1(3); cout << \"Before decrement: \"; i1.display(); // Using the pre-decrement operator Integer i2 = --i1; cout << \"After pre decrement: \"; i2.display();}", "e": 3420, "s": 2718, "text": null }, { "code": null, "e": 3428, "s": 3420, "text": "Output:" }, { "code": null, "e": 3479, "s": 3428, "text": "Before decrement: i = 3\nAfter pre decrement: i = 2" }, { "code": null, "e": 3515, "s": 3479, "text": "Example: Post-Decrement Overloading" }, { "code": null, "e": 3519, "s": 3515, "text": "CPP" }, { "code": "// C++ program to demonstrate// postfix decrement operator// overloading#include <bits/stdc++.h>using namespace std; class Integer {private: int i; public: // Parameterised constructor Integer(int i = 0) { this->i = i; } // Overloading the postfix operator Integer operator--(int) { Integer temp; temp.i = i--; return temp; } // Function to display the value of i void display() { cout << \"i = \" << i << endl; }}; // Driver functionint main(){ Integer i1(3); cout << \"Before decrement: \"; i1.display(); // Using the post-decrement operator Integer i2 = i1--; cout << \"After post decrement: \"; i2.display();}", "e": 4227, "s": 3519, "text": null }, { "code": null, "e": 4235, "s": 4227, "text": "Output:" }, { "code": null, "e": 4287, "s": 4235, "text": "Before decrement: i = 3\nAfter post decrement: i = 3" }, { "code": null, "e": 4301, "s": 4287, "text": "thotasravya28" }, { "code": null, "e": 4322, "s": 4301, "text": "sackshamsharmaintern" }, { "code": null, "e": 4335, "s": 4322, "text": "cpp-operator" }, { "code": null, "e": 4360, "s": 4335, "text": "cpp-operator-overloading" }, { "code": null, "e": 4364, "s": 4360, "text": "C++" }, { "code": null, "e": 4377, "s": 4364, "text": "cpp-operator" }, { "code": null, "e": 4381, "s": 4377, "text": "CPP" } ]
random.expovariate() function in Python
23 Dec, 2021 random module is used to generate random numbers in Python. Not actually random, rather this is used to generate pseudo-random numbers. That implies that these randomly generated numbers can be determined. expovariate() is an inbuilt method of the random module. It is used to return a random floating point number with exponential distribution. Syntax : random.expovariate(lambda) Parameters :lambda : a non zero value Returns : a random exponential distribution floating numberif the parameter is positive, the results range from 0 to positive infinityif the parameter is negative, the results range from 0 to negative infinity Example 1: # import the random moduleimport random # determining the values of the parameterlambda = 1.5 # using the expovariate() methodprint(random.expovariate(lambda)) Output : 0.22759592233982198 Example 2: We can generate the number multiple times and plot a graph to observe the exponential distribution. # import the required libraries import random import matplotlib.pyplot as plt # store the random numbers in a # list nums = [] alpha = 3 for i in range(100): temp = random.paretovariate(alpha) nums.append(temp) # plotting a graph plt.plot(nums) plt.show() Output :Example 3: We can create a histogram to observe the density of the exponential distribution. # import the required libraries import random import matplotlib.pyplot as plt # store the random numbers in a list nums = [] lambda = 1.5 for i in range(10000): temp = random.expovariate(lambda) nums.append(temp) # plotting a graph plt.hist(nums, bins = 200) plt.show() Output : nnr223442 Python-random 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 Taking input in Python Enumerate() in Python Read a file line by line in Python Python String | replace()
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Dec, 2021" }, { "code": null, "e": 234, "s": 28, "text": "random module is used to generate random numbers in Python. Not actually random, rather this is used to generate pseudo-random numbers. That implies that these randomly generated numbers can be determined." }, { "code": null, "e": 374, "s": 234, "text": "expovariate() is an inbuilt method of the random module. It is used to return a random floating point number with exponential distribution." }, { "code": null, "e": 410, "s": 374, "text": "Syntax : random.expovariate(lambda)" }, { "code": null, "e": 448, "s": 410, "text": "Parameters :lambda : a non zero value" }, { "code": null, "e": 658, "s": 448, "text": "Returns : a random exponential distribution floating numberif the parameter is positive, the results range from 0 to positive infinityif the parameter is negative, the results range from 0 to negative infinity" }, { "code": null, "e": 669, "s": 658, "text": "Example 1:" }, { "code": "# import the random moduleimport random # determining the values of the parameterlambda = 1.5 # using the expovariate() methodprint(random.expovariate(lambda))", "e": 831, "s": 669, "text": null }, { "code": null, "e": 840, "s": 831, "text": "Output :" }, { "code": null, "e": 860, "s": 840, "text": "0.22759592233982198" }, { "code": null, "e": 971, "s": 860, "text": "Example 2: We can generate the number multiple times and plot a graph to observe the exponential distribution." }, { "code": "# import the required libraries import random import matplotlib.pyplot as plt # store the random numbers in a # list nums = [] alpha = 3 for i in range(100): temp = random.paretovariate(alpha) nums.append(temp) # plotting a graph plt.plot(nums) plt.show()", "e": 1250, "s": 971, "text": null }, { "code": null, "e": 1351, "s": 1250, "text": "Output :Example 3: We can create a histogram to observe the density of the exponential distribution." }, { "code": "# import the required libraries import random import matplotlib.pyplot as plt # store the random numbers in a list nums = [] lambda = 1.5 for i in range(10000): temp = random.expovariate(lambda) nums.append(temp) # plotting a graph plt.hist(nums, bins = 200) plt.show()", "e": 1643, "s": 1351, "text": null }, { "code": null, "e": 1652, "s": 1643, "text": "Output :" }, { "code": null, "e": 1662, "s": 1652, "text": "nnr223442" }, { "code": null, "e": 1676, "s": 1662, "text": "Python-random" }, { "code": null, "e": 1683, "s": 1676, "text": "Python" }, { "code": null, "e": 1781, "s": 1683, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1809, "s": 1781, "text": "Read JSON file using Python" }, { "code": null, "e": 1859, "s": 1809, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 1881, "s": 1859, "text": "Python map() function" }, { "code": null, "e": 1925, "s": 1881, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 1943, "s": 1925, "text": "Python Dictionary" }, { "code": null, "e": 1985, "s": 1943, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2008, "s": 1985, "text": "Taking input in Python" }, { "code": null, "e": 2030, "s": 2008, "text": "Enumerate() in Python" }, { "code": null, "e": 2065, "s": 2030, "text": "Read a file line by line in Python" } ]
Short Note on Function-Oriented Metrics
29 Jun, 2020 Prerequisites – Functional Point Analysis, Calculation of Function Point Function-Oriented Metrics is a method that is developed by Albrecht in 1979 for IBM (International Business Machine). He simply suggested a measure known as Function points that are derived using an empirical relationship that is based on countable measures of software’s information or requirements domain and assessments of the complexity of software. Function-Oriented Metrics are also known as Function Point Model. This model generally focuses on the functionality of the software application being delivered. These methods are actually independent of the programming language that is being used in software applications and based on calculating the Function Point (FP). A function point is a unit of measurement that measures the business functionality provided by the business product. To determine whether or not a particular entry is simple, easy, average, or complex, a criterion is needed and should be developed by the organization. With the help of observations or experiments, the different weighing factors should be determined as shown below in the table. With the help of these tables, the count table can be computed. The software complexity can be computed by answering the following questions : Does the system need reliable backup and recovery? Are data communications required? Are there distribute processing functions? Is the performance of the system critical? Can the system be able to run in an existing, heavily, and largely utilized operational environment? Does the system require on-line data entry? Does the input transaction is required by the on-line data entry to be built over multiple screens or operations? Are the master files updated on-line? Are the inputs, outputs, files, or inquiries complex? Is the internal processing complex? Is the code which is designed to be reusable? Are conversion and installation included in the design? Is the system designed for multiple installations in various organizations whenever required? Is the application designed to facilitate or make the change and provide effective ease of use by the user? Each of the above questions is answered using a scale that ranges from o to 5 (not important or applicable to absolutely essential).This scale is shown below : Calculating Function Point : After calculating the function point, various other measures can be calculated as shown below : Productivity = FP / person-month Quality = Number of faults / FP Cost = $ / FP Documentation = Pages of documentation / FP Some figures – Small Project: <2000 Function Points Medium Project: 2, 000 to 10, 000 Function Points Large Project: > 10, 000 Function Points Disadvantages of Function-Oriented Metrics : Function Oriented Metrics was only developed for business systems, therefore it is valid for only that domain. In this, some of the aspects are subjective and have not been validated. The function point does not have any physical meaning. It is just a number. Software Testing Software Engineering Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Jun, 2020" }, { "code": null, "e": 101, "s": 28, "text": "Prerequisites – Functional Point Analysis, Calculation of Function Point" }, { "code": null, "e": 455, "s": 101, "text": "Function-Oriented Metrics is a method that is developed by Albrecht in 1979 for IBM (International Business Machine). He simply suggested a measure known as Function points that are derived using an empirical relationship that is based on countable measures of software’s information or requirements domain and assessments of the complexity of software." }, { "code": null, "e": 894, "s": 455, "text": "Function-Oriented Metrics are also known as Function Point Model. This model generally focuses on the functionality of the software application being delivered. These methods are actually independent of the programming language that is being used in software applications and based on calculating the Function Point (FP). A function point is a unit of measurement that measures the business functionality provided by the business product." }, { "code": null, "e": 1237, "s": 894, "text": "To determine whether or not a particular entry is simple, easy, average, or complex, a criterion is needed and should be developed by the organization. With the help of observations or experiments, the different weighing factors should be determined as shown below in the table. With the help of these tables, the count table can be computed." }, { "code": null, "e": 1316, "s": 1237, "text": "The software complexity can be computed by answering the following questions :" }, { "code": null, "e": 1367, "s": 1316, "text": "Does the system need reliable backup and recovery?" }, { "code": null, "e": 1401, "s": 1367, "text": "Are data communications required?" }, { "code": null, "e": 1444, "s": 1401, "text": "Are there distribute processing functions?" }, { "code": null, "e": 1487, "s": 1444, "text": "Is the performance of the system critical?" }, { "code": null, "e": 1588, "s": 1487, "text": "Can the system be able to run in an existing, heavily, and largely utilized operational environment?" }, { "code": null, "e": 1632, "s": 1588, "text": "Does the system require on-line data entry?" }, { "code": null, "e": 1746, "s": 1632, "text": "Does the input transaction is required by the on-line data entry to be built over multiple screens or operations?" }, { "code": null, "e": 1784, "s": 1746, "text": "Are the master files updated on-line?" }, { "code": null, "e": 1838, "s": 1784, "text": "Are the inputs, outputs, files, or inquiries complex?" }, { "code": null, "e": 1874, "s": 1838, "text": "Is the internal processing complex?" }, { "code": null, "e": 1920, "s": 1874, "text": "Is the code which is designed to be reusable?" }, { "code": null, "e": 1976, "s": 1920, "text": "Are conversion and installation included in the design?" }, { "code": null, "e": 2070, "s": 1976, "text": "Is the system designed for multiple installations in various organizations whenever required?" }, { "code": null, "e": 2178, "s": 2070, "text": "Is the application designed to facilitate or make the change and provide effective ease of use by the user?" }, { "code": null, "e": 2338, "s": 2178, "text": "Each of the above questions is answered using a scale that ranges from o to 5 (not important or applicable to absolutely essential).This scale is shown below :" }, { "code": null, "e": 2367, "s": 2338, "text": "Calculating Function Point :" }, { "code": null, "e": 2463, "s": 2367, "text": "After calculating the function point, various other measures can be calculated as shown below :" }, { "code": null, "e": 2588, "s": 2463, "text": "Productivity = FP / person-month\nQuality = Number of faults / FP\nCost = $ / FP\nDocumentation = Pages of documentation / FP " }, { "code": null, "e": 2603, "s": 2588, "text": "Some figures –" }, { "code": null, "e": 2734, "s": 2603, "text": "Small Project: <2000 Function Points \nMedium Project: 2, 000 to 10, 000 Function Points \nLarge Project: > 10, 000 Function Points " }, { "code": null, "e": 2779, "s": 2734, "text": "Disadvantages of Function-Oriented Metrics :" }, { "code": null, "e": 2890, "s": 2779, "text": "Function Oriented Metrics was only developed for business systems, therefore it is valid for only that domain." }, { "code": null, "e": 2963, "s": 2890, "text": "In this, some of the aspects are subjective and have not been validated." }, { "code": null, "e": 3039, "s": 2963, "text": "The function point does not have any physical meaning. It is just a number." }, { "code": null, "e": 3056, "s": 3039, "text": "Software Testing" }, { "code": null, "e": 3077, "s": 3056, "text": "Software Engineering" } ]
Environment Variables in ElectronJS - GeeksforGeeks
08 Oct, 2021 ElectronJS is an Open Source Framework used for building Cross-Platform native desktop applications using web technologies such as HTML, CSS, and JavaScript which are capable of running on Windows, macOS, and Linux operating systems. It combines the Chromium engine and NodeJS into a Single Runtime. We have already discussed Command Line Arguments in ElectronJS. Command-line arguments are important because they can be used to control the behaviour of the application. We can pass Command-line arguments to Electron from outside the application while launching or we can simply hard code these values within the application. Environment Variables in Electron also control the application configuration and behaviour without changing the code. Some specific behaviours in Electron are controlled by environment variables rather than command-line arguments because they are initialized earlier than the command-line flags and the application’s main function code. In this tutorial, we will look at the different environment variables used by Electron and their respective classifications. We assume that you are familiar with the prerequisites as covered in the above-mentioned link. For Electron to work, node and npm need to be pre-installed in the system. As mentioned above, in case we are hardcoding command-line flags within the application, we need to import the CommandLine Property of the app Module, but we don’t need any additional code changes for setting environment variables in Electron. However, Since Electron also supports the global process object, we can set the environment variables via code as well. For example: process.env.GOOGLE_API_KEY = 'YOUR_KEY_HERE' For more details on the process object, follow Process Object in ElectronJS. There are two main kinds of Environment Variables provided by Electron: Development variables Production variables Development Environment Variables as the name suggests, are intended primarily for development and debugging purposes within the application. ELECTRON_ENABLE_LOGGING: This environment variable is set to true, Prints Chromium’s internal logging to the console of the application. ELECTRON_LOG_ASAR_READS: When Electron reads from an ASAR file, if this environment variable is set to true, logs the read offset and filepath to the system tmpdir. The resulting file can be provided to the ASAR module to optimize file ordering which improves the performance of the Electron application and reduces the load on the system resources. An ASAR archive is a simple tar-like format that concatenates files into a single file. The electron can read arbitrary files from it without unpacking the whole file. This environment variable was introduced in the later versions of Electron. ELECTRON_ENABLE_STACK_DUMPING: This environment variable is set to true, then prints the error stack trace to the console when the Electron application crashes. This environment variable will not work if the crashReporter is started. crashReporter module in Electron is responsible for submitting crash reports to a remote server. For more details on the crashReporter module. ELECTRON_DEFAULT_ERROR_MODE: This environment variable is only supported in the Windows Operating System. This environment variable is set to true, shows the Windows’s OS crash dialog when the Electron application crashes. Just like ELECTRON_ENABLE_STACK_DUMPING, this environment variable will not work if the crashReporter is started. ELECTRON_OVERRIDE_DIST_PATH: When running the application from a packaged file in the development environment, this environment variable tells Electron to use the specified build of Electron instead of the one downloaded by npm install. This environment variable takes in a String filepath, where the specific build of Electron is stored on the native System. This is especially useful when we have made our own changes to the source code of the original downloaded Electron package. Production Environment Variables as the name suggests, are intended primarily for use at runtime in a packaged Electron applications. These Environment variables are especially useful when deploying the packaged Electron application to a different server in a production environment. NODE_OPTIONS: Since Electron combines the NodeJS and Chromium into a Single runtime, Electron includes supports for a subset of NodeJS NODE_OPTIONS environment variables. The majority of options provided are supported in Electron with the exception of those which conflict with Chromium’s use of BoringSSL. BoringSSL is a fork of OpenSSL that is designed to meet Google’s needs. OpenSSL is a robust, commercial-grade, and full-featured toolkit for the Transport Layer Security (TLS) and Secure Sockets Layer (SSL) protocols in HTTP. It is also a general-purpose cryptography library. We can provide multiple options to the NODE_OPTIONS environment variable. The Unsupported options are:–use-bundled-ca–force-fips–enable-fips–openssl-config–use-openssl-ca–max-http-header-size–http-parser –use-bundled-ca –force-fips –enable-fips –openssl-config –use-openssl-ca –max-http-header-size –http-parser GOOGLE_API_KEY: Many of Google’s services require an API_KEY to be generated for that particular project for that particular user for the services to be accessed from within the application. For example, Geolocation support in Electron requires the use of Google Cloud Platform’s geolocation webservice. To enable this feature, we need to acquire a Google API Key. This Key is usually Hardcoded within the Electron application and since this API key is included in every version of Electron for every valid session, it often exceeds its usage quota. To prevent this, we need to add the API Key as part of the environment. We can do so by placing the following code in the main process file, before opening any application windows or features that will make Google Services requests: process.env.GOOGLE_API_KEY = 'YOUR_KEY_HERE' We can also set this environment variable from outside the application so that it is valid for every new Google Service requests session until it expires. ELECTRON_RUN_AS_NODE: This environment variable is set to true, Starts the Electron process as a normal NodeJS process. ELECTRON_NO_ASAR: This environment variable is set to true, disables ASAR support for the Electron application. This variable is only supported in forked child processes and spawned child processes that set ELECTRON_RUN_AS_NODE environment variable as well. ELECTRON_NO_ATTACH_CONSOLE: This Environment Variable is only supported in the Windows Operating System. This environment variable is set to true, doesn’t attach console logs to the current console session. Hence, no logs will be printed from within the application. ELECTRON_FORCE_WINDOW_MENU_BAR: This environment variable is only supported in the Linux Operating System. This environment variable is set to true, does not use the global menu bar on Linux platform for the Electron application. ELECTRON_TRASH: This environment variable is only supported in the Linux Operating System. This environment variable sets the trash implementation on Linux platform. Default value set for this environment variable is gio. It can hold the following values:gvfs-trashtrash-clikioclient5kioclient gvfs-trash trash-cli kioclient5 kioclient Apart from the Production and Development Environment variables, there are some variables which are set by Electron itself in the native System environment at runtime. ORIGINAL_XDG_CURRENT_DESKTOP: This variable is set to the value of XDG_CURRENT_DESKTOP that your application originally launched with. Electron sometimes modifies the value of XDG_CURRENT_DESKTOP to affect other logic within Chromium. So if we want access to the original value we should look up this environment variable instead. The XDG_CURRENT_DESKTOP environment variables inform you of what desktop environment is currently being used. This variable differs with different OS and different platforms. This variable is also used by other processes and applications apart from Electron and it is a System environment variable. Example usage of Setting Environment Variables for Electron in Windows Console: ~$ set ELECTRON_ENABLE_LOGGING=true POSIX shell : ~$ export ELECTRON_ENABLE_LOGGING=true Output: Note: These environment variables are reset and need to be set again every time we restart the computer. If we want to avoid doing so, we need to add these environment variables with their respective values to the .bashrc files. .bashrc is a shell script that Bash runs whenever it is started interactively. It initializes an interactive shell session. We can put any command in that file that we could type in the command prompt, and they will not be reset such as in this case, Electron’s environment variables. rajeev0719singh ElectronJS JavaScript Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to append HTML code to a div using JavaScript ? How to Open URL in New Tab using JavaScript ? Installation of Node.js on Linux How to update Node.js and NPM to next version ? How to update NPM ? How to install the previous version of node.js and npm ? Difference between promise and async await in Node.js
[ { "code": null, "e": 24622, "s": 24594, "text": "\n08 Oct, 2021" }, { "code": null, "e": 24923, "s": 24622, "text": "ElectronJS is an Open Source Framework used for building Cross-Platform native desktop applications using web technologies such as HTML, CSS, and JavaScript which are capable of running on Windows, macOS, and Linux operating systems. It combines the Chromium engine and NodeJS into a Single Runtime. " }, { "code": null, "e": 25713, "s": 24923, "text": "We have already discussed Command Line Arguments in ElectronJS. Command-line arguments are important because they can be used to control the behaviour of the application. We can pass Command-line arguments to Electron from outside the application while launching or we can simply hard code these values within the application. Environment Variables in Electron also control the application configuration and behaviour without changing the code. Some specific behaviours in Electron are controlled by environment variables rather than command-line arguments because they are initialized earlier than the command-line flags and the application’s main function code. In this tutorial, we will look at the different environment variables used by Electron and their respective classifications. " }, { "code": null, "e": 25884, "s": 25713, "text": "We assume that you are familiar with the prerequisites as covered in the above-mentioned link. For Electron to work, node and npm need to be pre-installed in the system. " }, { "code": null, "e": 26261, "s": 25884, "text": "As mentioned above, in case we are hardcoding command-line flags within the application, we need to import the CommandLine Property of the app Module, but we don’t need any additional code changes for setting environment variables in Electron. However, Since Electron also supports the global process object, we can set the environment variables via code as well. For example:" }, { "code": null, "e": 26306, "s": 26261, "text": "process.env.GOOGLE_API_KEY = 'YOUR_KEY_HERE'" }, { "code": null, "e": 26456, "s": 26306, "text": "For more details on the process object, follow Process Object in ElectronJS. There are two main kinds of Environment Variables provided by Electron: " }, { "code": null, "e": 26478, "s": 26456, "text": "Development variables" }, { "code": null, "e": 26499, "s": 26478, "text": "Production variables" }, { "code": null, "e": 26642, "s": 26499, "text": "Development Environment Variables as the name suggests, are intended primarily for development and debugging purposes within the application. " }, { "code": null, "e": 26779, "s": 26642, "text": "ELECTRON_ENABLE_LOGGING: This environment variable is set to true, Prints Chromium’s internal logging to the console of the application." }, { "code": null, "e": 27373, "s": 26779, "text": "ELECTRON_LOG_ASAR_READS: When Electron reads from an ASAR file, if this environment variable is set to true, logs the read offset and filepath to the system tmpdir. The resulting file can be provided to the ASAR module to optimize file ordering which improves the performance of the Electron application and reduces the load on the system resources. An ASAR archive is a simple tar-like format that concatenates files into a single file. The electron can read arbitrary files from it without unpacking the whole file. This environment variable was introduced in the later versions of Electron." }, { "code": null, "e": 27750, "s": 27373, "text": "ELECTRON_ENABLE_STACK_DUMPING: This environment variable is set to true, then prints the error stack trace to the console when the Electron application crashes. This environment variable will not work if the crashReporter is started. crashReporter module in Electron is responsible for submitting crash reports to a remote server. For more details on the crashReporter module." }, { "code": null, "e": 28087, "s": 27750, "text": "ELECTRON_DEFAULT_ERROR_MODE: This environment variable is only supported in the Windows Operating System. This environment variable is set to true, shows the Windows’s OS crash dialog when the Electron application crashes. Just like ELECTRON_ENABLE_STACK_DUMPING, this environment variable will not work if the crashReporter is started." }, { "code": null, "e": 28571, "s": 28087, "text": "ELECTRON_OVERRIDE_DIST_PATH: When running the application from a packaged file in the development environment, this environment variable tells Electron to use the specified build of Electron instead of the one downloaded by npm install. This environment variable takes in a String filepath, where the specific build of Electron is stored on the native System. This is especially useful when we have made our own changes to the source code of the original downloaded Electron package." }, { "code": null, "e": 28856, "s": 28571, "text": "Production Environment Variables as the name suggests, are intended primarily for use at runtime in a packaged Electron applications. These Environment variables are especially useful when deploying the packaged Electron application to a different server in a production environment. " }, { "code": null, "e": 29644, "s": 28856, "text": "NODE_OPTIONS: Since Electron combines the NodeJS and Chromium into a Single runtime, Electron includes supports for a subset of NodeJS NODE_OPTIONS environment variables. The majority of options provided are supported in Electron with the exception of those which conflict with Chromium’s use of BoringSSL. BoringSSL is a fork of OpenSSL that is designed to meet Google’s needs. OpenSSL is a robust, commercial-grade, and full-featured toolkit for the Transport Layer Security (TLS) and Secure Sockets Layer (SSL) protocols in HTTP. It is also a general-purpose cryptography library. We can provide multiple options to the NODE_OPTIONS environment variable. The Unsupported options are:–use-bundled-ca–force-fips–enable-fips–openssl-config–use-openssl-ca–max-http-header-size–http-parser" }, { "code": null, "e": 29660, "s": 29644, "text": "–use-bundled-ca" }, { "code": null, "e": 29672, "s": 29660, "text": "–force-fips" }, { "code": null, "e": 29685, "s": 29672, "text": "–enable-fips" }, { "code": null, "e": 29701, "s": 29685, "text": "–openssl-config" }, { "code": null, "e": 29717, "s": 29701, "text": "–use-openssl-ca" }, { "code": null, "e": 29739, "s": 29717, "text": "–max-http-header-size" }, { "code": null, "e": 29752, "s": 29739, "text": "–http-parser" }, { "code": null, "e": 30537, "s": 29752, "text": "GOOGLE_API_KEY: Many of Google’s services require an API_KEY to be generated for that particular project for that particular user for the services to be accessed from within the application. For example, Geolocation support in Electron requires the use of Google Cloud Platform’s geolocation webservice. To enable this feature, we need to acquire a Google API Key. This Key is usually Hardcoded within the Electron application and since this API key is included in every version of Electron for every valid session, it often exceeds its usage quota. To prevent this, we need to add the API Key as part of the environment. We can do so by placing the following code in the main process file, before opening any application windows or features that will make Google Services requests: " }, { "code": null, "e": 30582, "s": 30537, "text": "process.env.GOOGLE_API_KEY = 'YOUR_KEY_HERE'" }, { "code": null, "e": 30737, "s": 30582, "text": "We can also set this environment variable from outside the application so that it is valid for every new Google Service requests session until it expires." }, { "code": null, "e": 30857, "s": 30737, "text": "ELECTRON_RUN_AS_NODE: This environment variable is set to true, Starts the Electron process as a normal NodeJS process." }, { "code": null, "e": 31115, "s": 30857, "text": "ELECTRON_NO_ASAR: This environment variable is set to true, disables ASAR support for the Electron application. This variable is only supported in forked child processes and spawned child processes that set ELECTRON_RUN_AS_NODE environment variable as well." }, { "code": null, "e": 31382, "s": 31115, "text": "ELECTRON_NO_ATTACH_CONSOLE: This Environment Variable is only supported in the Windows Operating System. This environment variable is set to true, doesn’t attach console logs to the current console session. Hence, no logs will be printed from within the application." }, { "code": null, "e": 31612, "s": 31382, "text": "ELECTRON_FORCE_WINDOW_MENU_BAR: This environment variable is only supported in the Linux Operating System. This environment variable is set to true, does not use the global menu bar on Linux platform for the Electron application." }, { "code": null, "e": 31906, "s": 31612, "text": "ELECTRON_TRASH: This environment variable is only supported in the Linux Operating System. This environment variable sets the trash implementation on Linux platform. Default value set for this environment variable is gio. It can hold the following values:gvfs-trashtrash-clikioclient5kioclient" }, { "code": null, "e": 31917, "s": 31906, "text": "gvfs-trash" }, { "code": null, "e": 31927, "s": 31917, "text": "trash-cli" }, { "code": null, "e": 31938, "s": 31927, "text": "kioclient5" }, { "code": null, "e": 31948, "s": 31938, "text": "kioclient" }, { "code": null, "e": 32117, "s": 31948, "text": "Apart from the Production and Development Environment variables, there are some variables which are set by Electron itself in the native System environment at runtime. " }, { "code": null, "e": 32747, "s": 32117, "text": "ORIGINAL_XDG_CURRENT_DESKTOP: This variable is set to the value of XDG_CURRENT_DESKTOP that your application originally launched with. Electron sometimes modifies the value of XDG_CURRENT_DESKTOP to affect other logic within Chromium. So if we want access to the original value we should look up this environment variable instead. The XDG_CURRENT_DESKTOP environment variables inform you of what desktop environment is currently being used. This variable differs with different OS and different platforms. This variable is also used by other processes and applications apart from Electron and it is a System environment variable." }, { "code": null, "e": 32811, "s": 32747, "text": "Example usage of Setting Environment Variables for Electron in " }, { "code": null, "e": 32828, "s": 32811, "text": "Windows Console:" }, { "code": null, "e": 32864, "s": 32828, "text": "~$ set ELECTRON_ENABLE_LOGGING=true" }, { "code": null, "e": 32878, "s": 32864, "text": "POSIX shell :" }, { "code": null, "e": 32917, "s": 32878, "text": "~$ export ELECTRON_ENABLE_LOGGING=true" }, { "code": null, "e": 32926, "s": 32917, "text": "Output: " }, { "code": null, "e": 33441, "s": 32926, "text": "Note: These environment variables are reset and need to be set again every time we restart the computer. If we want to avoid doing so, we need to add these environment variables with their respective values to the .bashrc files. .bashrc is a shell script that Bash runs whenever it is started interactively. It initializes an interactive shell session. We can put any command in that file that we could type in the command prompt, and they will not be reset such as in this case, Electron’s environment variables. " }, { "code": null, "e": 33457, "s": 33441, "text": "rajeev0719singh" }, { "code": null, "e": 33468, "s": 33457, "text": "ElectronJS" }, { "code": null, "e": 33479, "s": 33468, "text": "JavaScript" }, { "code": null, "e": 33487, "s": 33479, "text": "Node.js" }, { "code": null, "e": 33504, "s": 33487, "text": "Web Technologies" }, { "code": null, "e": 33602, "s": 33504, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33611, "s": 33602, "text": "Comments" }, { "code": null, "e": 33624, "s": 33611, "text": "Old Comments" }, { "code": null, "e": 33669, "s": 33624, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 33730, "s": 33669, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 33802, "s": 33730, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 33854, "s": 33802, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 33900, "s": 33854, "text": "How to Open URL in New Tab using JavaScript ?" }, { "code": null, "e": 33933, "s": 33900, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 33981, "s": 33933, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 34001, "s": 33981, "text": "How to update NPM ?" }, { "code": null, "e": 34058, "s": 34001, "text": "How to install the previous version of node.js and npm ?" } ]
A guide to building WhatsApp chatbots using Dialogflow and FireBase | by Aissam Outchakoucht | Towards Data Science
ChatBots are conversational agents, programs capable of conducting a conversation with an Internet user. In this tutorial I’ll walk you through an implementation of WhatsApp chatbot using Twilio platform. In addition to static chatbots, we will also benefit from the power of Google’s Dialogflow to create intelligent bots, capable of understanding human language. WhatsApp is the most popular OTT app in many parts of the world. Thanks to WhatsApp chatbots you can provide your customers with support on a platform they use and answer their questions immediately. Using Twilio, Flask and Heroku, as well as many other advanced platforms like DialogFlow, we can build amazing chatbots as we will do in this tutorial. Twilio is a cloud communications platform as a service (CPaaS) company which allows software developers to programmatically make and receive phone calls, send and receive text messages, and perform other communication functions using its web service APIs. With the Twilio API for WhatsApp, you can send notifications, have two-way conversations, or build chatbots. For free, and without waiting for your Twilio number to be approved for WhatsApp, Twilio Sandbox for WhatsApp enables you to create your chatbot immediately as we are about to see in this project. 1. Create a Twilio account 2. Create a new project 3. On project console, open Programmable SMS Dashboard 4. Select WhatsApp Beta When you activate your sandbox, you will see the phone number associated with it (here +1 415 ...) as well as its name (here regular-syllable) 1. Create a new Python virtual environment : In a new folder open terminal and execute : python -m venv myvenv 2. Activate your virtual environment : Windows : myvenv\Scripts\activate Linux : source myvenv/bin/activate 3. Install these two Python packages : Twilio : pip install twilio Flask : pip install flask Flask is a micro web framework written in Python. This means flask provides you with tools, libraries and technologies that allow you to build a web application. 4. Create a Flask App : In your folder, create a file named app.py then copy&paste the following code: from flask import Flask, requestfrom twilio.twiml.messaging_response import MessagingResponseapp = Flask(__name__)@app.route("/")def hello(): return "Hello, World!"@app.route("/sms", methods=['POST'])def sms_reply(): """Respond to incoming calls with a simple text message.""" # Fetch the message msg = request.form.get('Body') # Create reply resp = MessagingResponse() resp.message("You said: {}".format(msg)) return str(resp)if __name__ == "__main__": app.run(debug=True) This is a basic flask web app which enables us to get Hello, world! in / route, and get back our message if we POST it to /sms route as we can see in the following steps 5. Run the app : python app.py Your application is now running. You can check that by typing http://127.0.0.1:5000/ in your browser. (You'll get Hello, world!) However, it wouldn’t be possible for distant machines to access your app, hence the need for Ngrok Ngrok will enable us to have a public URL for our application running locally. 1. Download Ngrok and unzip it 2. Run it from the command line by executing : ./ngrok http 5000 3. Now you can access your app running locally from a distant machine using the provided URL (something like this https://******.ngrok.io) 4. Go back to Twilio sandbox and paste it as the URL for incoming messages : 5. You can now open WhatsApp in your phone, add the number you’ve got from Twilio in previous steps (+1 415 ...), and start the conversation by the code they told you to start with (here join regular-syllable) 6. You can now send whatever WhatsApp message you want and the bot will reply by sending back the same message. It is kind of a parrot bot 😃 However, we still have a major problem here, your machine should remain running all the time to allow the application to answer users’ requests. Thanks to Heroku we will be able to deploy our application, and all the requirements it needs to run effectively, in the Cloud. Hence our machine will benefit from the luxury of being turned off. To do so we need to : 1. In our virtual environment, install gunicorn: pip install gunicorn 2. Create these files in your folder : Procfile: then save this content in it web gunicorn app:app runtime.txt: then save this content in it python-3.7.2 requirements.txt: You can simply type pip freeze > requirements.txt to fill it with all 3rd party libraries required by your app. .gitignore: then save this content in it myvenv/*.pyc 3. Download & install Git; then in your virtual environment: Initialize a new git repository in your project folder : git init Add all untracked files to git repository : git add . Commit the changes to git repository : git commit -m "first commit" 4. Create a new Heroku account if you don’t have one. Then download Heroku Command Line Interface (CLI) which makes it easy to create and manage your Heroku apps directly from the terminal. 5. Connect to your Heroku account from your virtual environment using heroku login then you will be forwarded to a web-based interface in the browser to complete the authentication phase. 6. Create a new Heroku app heroku create <app-name> 7. Deploy your app by pushing your local git repository to the remote Heroku app’s git repository : git push heroku master Finally, when the deployment is done, you will see in the terminal the address where you can reach to your app. -something like https://<app-name>.herokuapp.com/sms- Copy it and go back to your sandbox to replace the Ngrok URL by the new Heroku one. Congratulations your parrot WhatsApp Bot is now running 24/7, it does not need assistance from your machine anymore 😃 you can turn it off. Say, you come up tomorrow with another idea rather than this parrot bot which you’ve made, all you need to do is to make the changes in your code (in the file app.py. You can also add more files if the project is complex) then: # connect to your virtual environment<virtual_environment_name>\Scripts\activate #Windowssource <virtual_environment_name>/bin/activate #Linux# connect to your heroku accountheroku login# prepare all the modified files and push them to Herokugit add .git commit -m "first change"git push heroku master ⚠️ In case you have installed new packages in your virtual environment, you have to tell Heroku about them by updating the file requirements.txt too: Just type pip freeze > requirements.txt before git add . to do so. If you want to create a serious business WhatsApp bot, the approach I presented earlier presents two drawbacks for you : (1) In order to use the bot, your clients must kick off the conversation with a certain bizarre message 😑 (here join regular-syllable); (2) The bot comes up with the logo of Twilio instead of yours. This is due to the fact that we used the Twilio sandbox and the number we were provided with is not ours. However, Twilio offers you the possibility to own a number and consequently get rid of the aforementioned problems. To do so, here are the steps you need to follow : Step 1: Buy a Twilio number Step 2: Request access to enable your Twilio number for WhatsApp by filling out Twilio’s “Request Access” form (make sure you have your Facebook Business Manager ID beforehand) When your request will be approved, Twilio will notify you by an email which will walk you through the next steps to follow for submitting your sender Profile and WhatsApp Message Templates, then another email will show you how to approve Twilio to send messages on your behalf and to verify your Facebook Business Manager account. So, after sending the request, make sure you check your emails frequently for the next steps. The whole process takes 2 to 3 weeks. Further information about the process So far, we created a chatbot which have the capability to manage simple conversations and repeat what one says😅 isn’t that cool 🙄. Actually, what we focused on in previous sections is to have this bot working over the popular chat platform WhatsApp. In fact, we didn’t use any of our data to train or personalize the bot. In this section, we will train and fine-tune our chatbot and have it interact with the backend. Let’s take a shopping/delivery store case study for instance. A Dialogflow agent is a virtual agent that handles conversations with your end-users. It is a natural language understanding module that understands the nuances of human language. DialogFlow’s agents use Intents to categorize end-user intentions for each conversation turn and Entities to identify and extract specific data from end-user expressions (We’ll use them to send data to the backend). So first things first .. Login into DialogFlow Console and create a new agent .. In the left-side menu, you can enable “Small talk”. Basically your bot is now able to automatically handle the ‘hi, hello, how are you, bye, ...’-kind of things. Try it! (there is a “Try it now” section in the right) When an end-user writes or says something, Dialogflow matches the end-user expression to the best intent in your agent. In order to do that, your agent have to be trained on some training phrases (example phrases for what end-users might say). When an end-user expression resembles one of these phrases, Dialogflow matches the intent. You don’t have to define every possible example, because Dialogflow’s built-in machine learning expands on your list with other, similar phrases. In your left-hand menu, select Intent and create a new one. In the training phrases section, add some expressions that will trigger this intent. While you are adding them you will see that some entities are automatically highlighted (like location or date-time etc); you can also add custom entities if you want. Under the action and parameters section, you can mark some entities as required so that the agent will always ask for them when the intent is triggered. Note that if you mark a parameter as required you have to add the question(s) the agent will ask end users in the prompts column. Moreover, you have to possibility to add a default answer(s) under the Responses section or let the back-end generate custom answers. We’ll be using Google’s Firebase real time database, which is a cloud-hosted NoSQL database that lets you store and sync data between you and your users in real time using JSON format. 1- Go to Firebase website and add a new project. 2- In the left-hand menu, select Database then choose realtime database in test mode. In order to be able to access your DB, add and delete data, you have to have the DB credentials. 3- Click on the gear icon next to the Project overview, then select Project settings. In the Firebase SDK snippet choose config and copy the credentials in a separate file in your computer. 4- In your computer/virtual environment, create an app.py file and import these credentials, together with other useful libraries. 5- Add your products and their characteristics to the realtime database: 5.1. In a separate file configure the authentication to Firebase: import pyrebase #install pyrebase first using pip installfrom firebaseconfig import config # firebase credentialsfirebase = pyrebase.initialize_app(config)db = firebase.database() 5.2. Prepare your products in JSON format and add them to the DB using the following commands: prod1 = {"ID":"0","order":"0","number": 10,"color": "black","size":"S","address":"-","date":"-"}# add a productdb.child("products").push({"shirt":prod1})# update a productdb.child("products").update({"shirt":prod2}) #define prod2 before# remove the whole chain of productsdb.child("products").remove() You can check (in realtime) your DB’s web interface to see the updates you are making. In the usefulfunction.py file, we define the functions we are about to use in our implementation, among them there is the is_available() function, which checks whether a given product exists in the realtime DB The characteristics of the user’s order come from Dialogflow in a JSON format. The following function extracts these characteristics and checks whether there is a product satisfying these requirements. You might note the presence of two undefined functions: all_fields() function just checks if all the required fields are filled by the end user, while the location_format() function adapts the format of the location variable to a readable one. In your file app.py we set up the Flask API. The / main root shows just a hello world .. Professionals have standards ;) The /check path is where we receive the POST request, extract data from Dialogflow, process it, check the availability of the product in the realtime DB and reply the user always using JSON format. Now, you can run the app.py locally and use Ngrok to get a public address, or push your application to Heroku as we’ve done previously. In Dialogflow, by default, your agent responds to a matched intent with a static response. In order to use dynamic answers, you have to enable the fulfillment option. Go back to your Dialogflow console, in the left-hand menu click on fulfillment, enable webhook, change the URL to the one where your app is hosted and save the changes. When an intent with fulfillment enabled is matched, Dialogflow sends a request to your webhook service (backend app) with information about the matched intent. Now go to the intent you’ve created previously (under the Intents section), on the bottom of that page you’ll see a fulfillment section, enable webhook call for intent and for slot filling. Congratulations .. Your chatbot is now running as expected, check it under the Try it now section. When an end-user starts a conversation with the chatbot, this latter tries to match the incoming expressions to one of its Intents. When it manages to do so, it will try to fill in all the required entities, and it sends all these entities (the characteristics of the product in our case) to the link we mentioned in the Fulfillment section. After our Flask web application receives the characteristics, it verifies if the requested product is available in the database, and if so, it adds the command in the Firebase RT DB. Then, an appropriate response is sent to the end-user. You can follow the steps mentioned in the above sections to use this chatbot on WhatsApp, just as you can use the DialogFlow’s Integration option to integrate it with Facebook Messenger, Slack, your own website and many other platforms.
[ { "code": null, "e": 377, "s": 172, "text": "ChatBots are conversational agents, programs capable of conducting a conversation with an Internet user. In this tutorial I’ll walk you through an implementation of WhatsApp chatbot using Twilio platform." }, { "code": null, "e": 537, "s": 377, "text": "In addition to static chatbots, we will also benefit from the power of Google’s Dialogflow to create intelligent bots, capable of understanding human language." }, { "code": null, "e": 737, "s": 537, "text": "WhatsApp is the most popular OTT app in many parts of the world. Thanks to WhatsApp chatbots you can provide your customers with support on a platform they use and answer their questions immediately." }, { "code": null, "e": 889, "s": 737, "text": "Using Twilio, Flask and Heroku, as well as many other advanced platforms like DialogFlow, we can build amazing chatbots as we will do in this tutorial." }, { "code": null, "e": 1145, "s": 889, "text": "Twilio is a cloud communications platform as a service (CPaaS) company which allows software developers to programmatically make and receive phone calls, send and receive text messages, and perform other communication functions using its web service APIs." }, { "code": null, "e": 1254, "s": 1145, "text": "With the Twilio API for WhatsApp, you can send notifications, have two-way conversations, or build chatbots." }, { "code": null, "e": 1451, "s": 1254, "text": "For free, and without waiting for your Twilio number to be approved for WhatsApp, Twilio Sandbox for WhatsApp enables you to create your chatbot immediately as we are about to see in this project." }, { "code": null, "e": 1478, "s": 1451, "text": "1. Create a Twilio account" }, { "code": null, "e": 1502, "s": 1478, "text": "2. Create a new project" }, { "code": null, "e": 1557, "s": 1502, "text": "3. On project console, open Programmable SMS Dashboard" }, { "code": null, "e": 1581, "s": 1557, "text": "4. Select WhatsApp Beta" }, { "code": null, "e": 1724, "s": 1581, "text": "When you activate your sandbox, you will see the phone number associated with it (here +1 415 ...) as well as its name (here regular-syllable)" }, { "code": null, "e": 1769, "s": 1724, "text": "1. Create a new Python virtual environment :" }, { "code": null, "e": 1835, "s": 1769, "text": "In a new folder open terminal and execute : python -m venv myvenv" }, { "code": null, "e": 1874, "s": 1835, "text": "2. Activate your virtual environment :" }, { "code": null, "e": 1908, "s": 1874, "text": "Windows : myvenv\\Scripts\\activate" }, { "code": null, "e": 1943, "s": 1908, "text": "Linux : source myvenv/bin/activate" }, { "code": null, "e": 1982, "s": 1943, "text": "3. Install these two Python packages :" }, { "code": null, "e": 2010, "s": 1982, "text": "Twilio : pip install twilio" }, { "code": null, "e": 2036, "s": 2010, "text": "Flask : pip install flask" }, { "code": null, "e": 2198, "s": 2036, "text": "Flask is a micro web framework written in Python. This means flask provides you with tools, libraries and technologies that allow you to build a web application." }, { "code": null, "e": 2222, "s": 2198, "text": "4. Create a Flask App :" }, { "code": null, "e": 2301, "s": 2222, "text": "In your folder, create a file named app.py then copy&paste the following code:" }, { "code": null, "e": 2802, "s": 2301, "text": "from flask import Flask, requestfrom twilio.twiml.messaging_response import MessagingResponseapp = Flask(__name__)@app.route(\"/\")def hello(): return \"Hello, World!\"@app.route(\"/sms\", methods=['POST'])def sms_reply(): \"\"\"Respond to incoming calls with a simple text message.\"\"\" # Fetch the message msg = request.form.get('Body') # Create reply resp = MessagingResponse() resp.message(\"You said: {}\".format(msg)) return str(resp)if __name__ == \"__main__\": app.run(debug=True)" }, { "code": null, "e": 2972, "s": 2802, "text": "This is a basic flask web app which enables us to get Hello, world! in / route, and get back our message if we POST it to /sms route as we can see in the following steps" }, { "code": null, "e": 3003, "s": 2972, "text": "5. Run the app : python app.py" }, { "code": null, "e": 3036, "s": 3003, "text": "Your application is now running." }, { "code": null, "e": 3132, "s": 3036, "text": "You can check that by typing http://127.0.0.1:5000/ in your browser. (You'll get Hello, world!)" }, { "code": null, "e": 3231, "s": 3132, "text": "However, it wouldn’t be possible for distant machines to access your app, hence the need for Ngrok" }, { "code": null, "e": 3310, "s": 3231, "text": "Ngrok will enable us to have a public URL for our application running locally." }, { "code": null, "e": 3341, "s": 3310, "text": "1. Download Ngrok and unzip it" }, { "code": null, "e": 3406, "s": 3341, "text": "2. Run it from the command line by executing : ./ngrok http 5000" }, { "code": null, "e": 3545, "s": 3406, "text": "3. Now you can access your app running locally from a distant machine using the provided URL (something like this https://******.ngrok.io)" }, { "code": null, "e": 3622, "s": 3545, "text": "4. Go back to Twilio sandbox and paste it as the URL for incoming messages :" }, { "code": null, "e": 3832, "s": 3622, "text": "5. You can now open WhatsApp in your phone, add the number you’ve got from Twilio in previous steps (+1 415 ...), and start the conversation by the code they told you to start with (here join regular-syllable)" }, { "code": null, "e": 3973, "s": 3832, "text": "6. You can now send whatever WhatsApp message you want and the bot will reply by sending back the same message. It is kind of a parrot bot 😃" }, { "code": null, "e": 4118, "s": 3973, "text": "However, we still have a major problem here, your machine should remain running all the time to allow the application to answer users’ requests." }, { "code": null, "e": 4336, "s": 4118, "text": "Thanks to Heroku we will be able to deploy our application, and all the requirements it needs to run effectively, in the Cloud. Hence our machine will benefit from the luxury of being turned off. To do so we need to :" }, { "code": null, "e": 4406, "s": 4336, "text": "1. In our virtual environment, install gunicorn: pip install gunicorn" }, { "code": null, "e": 4445, "s": 4406, "text": "2. Create these files in your folder :" }, { "code": null, "e": 4505, "s": 4445, "text": "Procfile: then save this content in it web gunicorn app:app" }, { "code": null, "e": 4560, "s": 4505, "text": "runtime.txt: then save this content in it python-3.7.2" }, { "code": null, "e": 4690, "s": 4560, "text": "requirements.txt: You can simply type pip freeze > requirements.txt to fill it with all 3rd party libraries required by your app." }, { "code": null, "e": 4731, "s": 4690, "text": ".gitignore: then save this content in it" }, { "code": null, "e": 4744, "s": 4731, "text": "myvenv/*.pyc" }, { "code": null, "e": 4805, "s": 4744, "text": "3. Download & install Git; then in your virtual environment:" }, { "code": null, "e": 4871, "s": 4805, "text": "Initialize a new git repository in your project folder : git init" }, { "code": null, "e": 4925, "s": 4871, "text": "Add all untracked files to git repository : git add ." }, { "code": null, "e": 4993, "s": 4925, "text": "Commit the changes to git repository : git commit -m \"first commit\"" }, { "code": null, "e": 5183, "s": 4993, "text": "4. Create a new Heroku account if you don’t have one. Then download Heroku Command Line Interface (CLI) which makes it easy to create and manage your Heroku apps directly from the terminal." }, { "code": null, "e": 5371, "s": 5183, "text": "5. Connect to your Heroku account from your virtual environment using heroku login then you will be forwarded to a web-based interface in the browser to complete the authentication phase." }, { "code": null, "e": 5423, "s": 5371, "text": "6. Create a new Heroku app heroku create <app-name>" }, { "code": null, "e": 5546, "s": 5423, "text": "7. Deploy your app by pushing your local git repository to the remote Heroku app’s git repository : git push heroku master" }, { "code": null, "e": 5796, "s": 5546, "text": "Finally, when the deployment is done, you will see in the terminal the address where you can reach to your app. -something like https://<app-name>.herokuapp.com/sms- Copy it and go back to your sandbox to replace the Ngrok URL by the new Heroku one." }, { "code": null, "e": 5935, "s": 5796, "text": "Congratulations your parrot WhatsApp Bot is now running 24/7, it does not need assistance from your machine anymore 😃 you can turn it off." }, { "code": null, "e": 6163, "s": 5935, "text": "Say, you come up tomorrow with another idea rather than this parrot bot which you’ve made, all you need to do is to make the changes in your code (in the file app.py. You can also add more files if the project is complex) then:" }, { "code": null, "e": 6465, "s": 6163, "text": "# connect to your virtual environment<virtual_environment_name>\\Scripts\\activate #Windowssource <virtual_environment_name>/bin/activate #Linux# connect to your heroku accountheroku login# prepare all the modified files and push them to Herokugit add .git commit -m \"first change\"git push heroku master" }, { "code": null, "e": 6682, "s": 6465, "text": "⚠️ In case you have installed new packages in your virtual environment, you have to tell Heroku about them by updating the file requirements.txt too: Just type pip freeze > requirements.txt before git add . to do so." }, { "code": null, "e": 6803, "s": 6682, "text": "If you want to create a serious business WhatsApp bot, the approach I presented earlier presents two drawbacks for you :" }, { "code": null, "e": 6939, "s": 6803, "text": "(1) In order to use the bot, your clients must kick off the conversation with a certain bizarre message 😑 (here join regular-syllable);" }, { "code": null, "e": 7002, "s": 6939, "text": "(2) The bot comes up with the logo of Twilio instead of yours." }, { "code": null, "e": 7274, "s": 7002, "text": "This is due to the fact that we used the Twilio sandbox and the number we were provided with is not ours. However, Twilio offers you the possibility to own a number and consequently get rid of the aforementioned problems. To do so, here are the steps you need to follow :" }, { "code": null, "e": 7302, "s": 7274, "text": "Step 1: Buy a Twilio number" }, { "code": null, "e": 7479, "s": 7302, "text": "Step 2: Request access to enable your Twilio number for WhatsApp by filling out Twilio’s “Request Access” form (make sure you have your Facebook Business Manager ID beforehand)" }, { "code": null, "e": 7811, "s": 7479, "text": "When your request will be approved, Twilio will notify you by an email which will walk you through the next steps to follow for submitting your sender Profile and WhatsApp Message Templates, then another email will show you how to approve Twilio to send messages on your behalf and to verify your Facebook Business Manager account." }, { "code": null, "e": 7943, "s": 7811, "text": "So, after sending the request, make sure you check your emails frequently for the next steps. The whole process takes 2 to 3 weeks." }, { "code": null, "e": 7981, "s": 7943, "text": "Further information about the process" }, { "code": null, "e": 8231, "s": 7981, "text": "So far, we created a chatbot which have the capability to manage simple conversations and repeat what one says😅 isn’t that cool 🙄. Actually, what we focused on in previous sections is to have this bot working over the popular chat platform WhatsApp." }, { "code": null, "e": 8461, "s": 8231, "text": "In fact, we didn’t use any of our data to train or personalize the bot. In this section, we will train and fine-tune our chatbot and have it interact with the backend. Let’s take a shopping/delivery store case study for instance." }, { "code": null, "e": 8857, "s": 8461, "text": "A Dialogflow agent is a virtual agent that handles conversations with your end-users. It is a natural language understanding module that understands the nuances of human language. DialogFlow’s agents use Intents to categorize end-user intentions for each conversation turn and Entities to identify and extract specific data from end-user expressions (We’ll use them to send data to the backend)." }, { "code": null, "e": 9155, "s": 8857, "text": "So first things first .. Login into DialogFlow Console and create a new agent .. In the left-side menu, you can enable “Small talk”. Basically your bot is now able to automatically handle the ‘hi, hello, how are you, bye, ...’-kind of things. Try it! (there is a “Try it now” section in the right)" }, { "code": null, "e": 9636, "s": 9155, "text": "When an end-user writes or says something, Dialogflow matches the end-user expression to the best intent in your agent. In order to do that, your agent have to be trained on some training phrases (example phrases for what end-users might say). When an end-user expression resembles one of these phrases, Dialogflow matches the intent. You don’t have to define every possible example, because Dialogflow’s built-in machine learning expands on your list with other, similar phrases." }, { "code": null, "e": 9696, "s": 9636, "text": "In your left-hand menu, select Intent and create a new one." }, { "code": null, "e": 9949, "s": 9696, "text": "In the training phrases section, add some expressions that will trigger this intent. While you are adding them you will see that some entities are automatically highlighted (like location or date-time etc); you can also add custom entities if you want." }, { "code": null, "e": 10232, "s": 9949, "text": "Under the action and parameters section, you can mark some entities as required so that the agent will always ask for them when the intent is triggered. Note that if you mark a parameter as required you have to add the question(s) the agent will ask end users in the prompts column." }, { "code": null, "e": 10366, "s": 10232, "text": "Moreover, you have to possibility to add a default answer(s) under the Responses section or let the back-end generate custom answers." }, { "code": null, "e": 10551, "s": 10366, "text": "We’ll be using Google’s Firebase real time database, which is a cloud-hosted NoSQL database that lets you store and sync data between you and your users in real time using JSON format." }, { "code": null, "e": 10600, "s": 10551, "text": "1- Go to Firebase website and add a new project." }, { "code": null, "e": 10686, "s": 10600, "text": "2- In the left-hand menu, select Database then choose realtime database in test mode." }, { "code": null, "e": 10783, "s": 10686, "text": "In order to be able to access your DB, add and delete data, you have to have the DB credentials." }, { "code": null, "e": 10973, "s": 10783, "text": "3- Click on the gear icon next to the Project overview, then select Project settings. In the Firebase SDK snippet choose config and copy the credentials in a separate file in your computer." }, { "code": null, "e": 11104, "s": 10973, "text": "4- In your computer/virtual environment, create an app.py file and import these credentials, together with other useful libraries." }, { "code": null, "e": 11177, "s": 11104, "text": "5- Add your products and their characteristics to the realtime database:" }, { "code": null, "e": 11243, "s": 11177, "text": "5.1. In a separate file configure the authentication to Firebase:" }, { "code": null, "e": 11434, "s": 11243, "text": "import pyrebase #install pyrebase first using pip installfrom firebaseconfig import config # firebase credentialsfirebase = pyrebase.initialize_app(config)db = firebase.database()" }, { "code": null, "e": 11529, "s": 11434, "text": "5.2. Prepare your products in JSON format and add them to the DB using the following commands:" }, { "code": null, "e": 11831, "s": 11529, "text": "prod1 = {\"ID\":\"0\",\"order\":\"0\",\"number\": 10,\"color\": \"black\",\"size\":\"S\",\"address\":\"-\",\"date\":\"-\"}# add a productdb.child(\"products\").push({\"shirt\":prod1})# update a productdb.child(\"products\").update({\"shirt\":prod2}) #define prod2 before# remove the whole chain of productsdb.child(\"products\").remove()" }, { "code": null, "e": 11918, "s": 11831, "text": "You can check (in realtime) your DB’s web interface to see the updates you are making." }, { "code": null, "e": 12128, "s": 11918, "text": "In the usefulfunction.py file, we define the functions we are about to use in our implementation, among them there is the is_available() function, which checks whether a given product exists in the realtime DB" }, { "code": null, "e": 12330, "s": 12128, "text": "The characteristics of the user’s order come from Dialogflow in a JSON format. The following function extracts these characteristics and checks whether there is a product satisfying these requirements." }, { "code": null, "e": 12574, "s": 12330, "text": "You might note the presence of two undefined functions: all_fields() function just checks if all the required fields are filled by the end user, while the location_format() function adapts the format of the location variable to a readable one." }, { "code": null, "e": 12619, "s": 12574, "text": "In your file app.py we set up the Flask API." }, { "code": null, "e": 12695, "s": 12619, "text": "The / main root shows just a hello world .. Professionals have standards ;)" }, { "code": null, "e": 12893, "s": 12695, "text": "The /check path is where we receive the POST request, extract data from Dialogflow, process it, check the availability of the product in the realtime DB and reply the user always using JSON format." }, { "code": null, "e": 13029, "s": 12893, "text": "Now, you can run the app.py locally and use Ngrok to get a public address, or push your application to Heroku as we’ve done previously." }, { "code": null, "e": 13196, "s": 13029, "text": "In Dialogflow, by default, your agent responds to a matched intent with a static response. In order to use dynamic answers, you have to enable the fulfillment option." }, { "code": null, "e": 13365, "s": 13196, "text": "Go back to your Dialogflow console, in the left-hand menu click on fulfillment, enable webhook, change the URL to the one where your app is hosted and save the changes." }, { "code": null, "e": 13525, "s": 13365, "text": "When an intent with fulfillment enabled is matched, Dialogflow sends a request to your webhook service (backend app) with information about the matched intent." }, { "code": null, "e": 13715, "s": 13525, "text": "Now go to the intent you’ve created previously (under the Intents section), on the bottom of that page you’ll see a fulfillment section, enable webhook call for intent and for slot filling." }, { "code": null, "e": 13814, "s": 13715, "text": "Congratulations .. Your chatbot is now running as expected, check it under the Try it now section." }, { "code": null, "e": 14156, "s": 13814, "text": "When an end-user starts a conversation with the chatbot, this latter tries to match the incoming expressions to one of its Intents. When it manages to do so, it will try to fill in all the required entities, and it sends all these entities (the characteristics of the product in our case) to the link we mentioned in the Fulfillment section." }, { "code": null, "e": 14394, "s": 14156, "text": "After our Flask web application receives the characteristics, it verifies if the requested product is available in the database, and if so, it adds the command in the Firebase RT DB. Then, an appropriate response is sent to the end-user." } ]
Association Rule Mining in R. Association Rule Mining (also called as... | by Avinash Kadimisetty | Towards Data Science
Association Rule Mining (also called as Association Rule Learning) is a common technique used to find associations between many variables. It is often used by grocery stores, e-commerce websites, and anyone with large transactional databases. A most common example that we encounter in our daily lives — Amazon knows what else you want to buy when you order something on their site. The same idea extends to Spotify too — They know what song you want to listen to next. All of these incorporate, at some level, data mining concepts and association rule mining algorithms. Market Basket Analysis is similar to ARM. Market Basket Analysis is a modelling technique based upon the theory that if you buy a certain group of items, you are more (or less) likely to buy another group of items. For example, if you are in an English pub and you buy a pint of beer and don’t buy a bar meal, you are more likely to buy crisps at the same time than somebody who didn’t buy beer. Based on the concept of strong rules, Rakesh Agrawal, Tomasz Imieliński and Arun Swami introduced association rules for discovering regularities between products in large-scale transaction data recorded by point-of-sale (POS) systems in supermarkets. This article explains the concept of Association Rule Mining and how to use this technique in R To perform Association Rule Mining in R, we use the arules and the arulesViz packages in R. Michael Hahsler, et al. has authored and maintains two very useful R packages relating to association rule mining: the arules package and the arulesViz package. If you don’t have these packages installed in your system, please use the following commands to install them. > install.packages("arules")> install.packages("arulesViz") I’m using the AdultUCI dataset that comes bundled with the arules package. > data(“Groceries”) Lets inspect the Groceries data first. > class(Groceries) [1] "transactions" attr(,"package") [1] "arules" It is a transactional dataset. > inspect(head(Groceries, 2)) items [1] {citrus fruit,semi-finished bread,margarine,ready soups} [2] {tropical fruit,yogurt,coffee} The first two transactions and the items involved in each transaction can be observed from the output above. There are three parameters controlling the number of rules to be generated viz. Support and Confidence. Another parameter Lift is generated using Support and Confidence and is one of the major parameters to filter the generated rules. Support is an indication of how frequently the itemset appears in the dataset. Consider only the two transactions from the above output. The support of the item citrus fruit is 1/2 as it appears in only 1 out of the two transactions. Confidence is an indication of how often the rule has been found to be true. We will discuss more about confidence after generating the rules. Lets find out the rules using the apriori algorithm. > grocery_rules <- apriori(Groceries, parameter = list(support = 0.01, confidence = 0.5))AprioriParameter specification: confidence minval smax arem aval originalSupport maxtime support minlen maxlen target ext 0.5 0.1 1 none FALSE TRUE 5 0.01 1 10 rules FALSEAlgorithmic control: filter tree heap memopt load sort verbose 0.1 TRUE TRUE FALSE TRUE 2 TRUEAbsolute minimum support count: 98set item appearances ...[0 item(s)] done [0.00s]. set transactions ...[169 item(s), 9835 transaction(s)] done [0.00s]. sorting and recoding items ... [88 item(s)] done [0.00s]. creating transaction tree ... done [0.00s]. checking subsets of size 1 2 3 4 done [0.00s]. writing ... [15 rule(s)] done [0.00s]. creating S4 object ... done [0.00s]. The Apriori algorithm generated 15 rules with the given constraints. Lets dive into the Parameter Specification section of the output. minval is the minimum value of the support an itemset should satisfy to be a part of a rule. smax is the maximum support value for an itemset. arem is an Additional Rule Evaluation Parameter. In the above code we have constrained the number of rules using Support and Confidence. There are several other ways to constrain the rules using the arem parameter in the function and we will discuss more about it later in the article. aval is a logical indicating whether to return the additional rule evaluation measure selected with arem. originalSupport The traditional support value only considers both LHS and RHS items for calculating support. If you want to use only the LHS items for the calculation then you need to set this to FALSE. maxtime is the maximum amount of time allowed to check for subsets. minlen is the minimum number of items required in the rule. maxlen is the maximum number of items that can be present in the rule. > inspect(head(sort(rules, by = "confidence"), 3)) lhs rhs support confidence lift count [1] {citrus fruit,root vegetables} => {other vegetables} 0.01037112 0.5862069 3.029608 102 [2] {tropical fruit,root vegetables} => {other vegetables} 0.01230300 0.5845411 3.020999 121 [3] {curd,yogurt} => {whole milk} 0.01006609 0.5823529 2.279125 99 The top 3 rules sorted by confidence are shown above. In many cases, you would like to limit the number of rules generated. For example, you can use association rules as predictors in Regression/Classification. You can generate rules with the Right Hand Side of the rule as your response and use the rules generated as the modelling features. In this case, you would not want to use all the rules generated as the predictors because many rules are actually subsets of bigger rules and hence you would want to eliminate them. The following code snippet shows how to generate rules whose RHS is pre-defined. wholemilk_rules <- apriori(data=Groceries, parameter=list (supp=0.001,conf = 0.08), appearance = list (rhs="whole milk"))# The above code shows what products are bought before buying "whole milk" and will generate rules that lead to buying "whole milk". You can limit the number of rules by tweaking a few parameters. Although the parameter tweaking depends on the kind of data you are dealing with, the most common ways include changing support, confidence and other parameters like minlen, maxlen etc. > grocery_rules_increased_support <- apriori(Groceries, parameter = list(support = 0.02, confidence = 0.5))# This generates only one rule in the output. If you want to get stronger rules, you have to increase the confidence. If you want lengthier rules increase the maxlen parameter. If you want to eliminate shorter rules, decrease the minlen parameter. Sometimes you might be interested in finding the rules involving maximum number of items and remove the shorter rules that are subsets of the longer rules. The below code removes such redundant rules. > subsets <- which(colSums(is.subset(grocery_rules, groery_rules)) > 1)> grocery_rules <- grocery_rules[-subsets] Lets look at the arem parameter that was described earlier. The rules, after geneartion, are further evaluated based on the value of the arem parameter. The arem parameter takes the following values — none, diff, quot, aimp, info, chi2. # This gives more than 1,500,000 rules> rules <- apriori(Groceries, parameter = list(supp = 0.0001, conf = 0.5))# This gives 982,000 rules.> rules_chi2 <- apriori(Groceries, parameter = list(supp = 0.0001, conf = 0.5, arem = "chi2")) The AdultUCI dataset bundled with arules package is used. > data("AdultUCI")> class(AdultUCI) "data.frame" When you look at the structure of the AdultUCI dataframe, you observe that a few columns are numeric. Each transaction of a transactional dataset contains the list of items involved in that transaction. When we convert the dataframe into a transactional dataset, each row of this dataframe will become a transaction. Each column will become an item. But if the value of a column is numeric, it cannot be used as the column can take infinite values. So before converting the dataframe into a transactional dataset, we must ensure that we convert each column into a factor or a logical to ensure that the column takes values only from a fixed set. > str(AdultUCI)'data.frame': 48842 obs. of 15 variables: $ age : int 39 50 38 53 28 37 49 52 31 42 ... $ workclass : Factor w/ 8 levels "Federal-gov",..: 7 6 4 4 4 4 $ fnlwgt : int 77516 83311 215646 234721 338409 284582 $ education : Ord.factor w/ 16 levels "Preschool"<"1st-4th"<..: $ education-num : int 13 13 9 7 13 14 5 9 14 13 ... $ marital-status: Factor w/ 7 levels "Divorced","Married-AF-Spouse" $ occupation : Factor w/ 14 levels "Adm-clerical",..: 1 4 6 6 10 $ relationship : Factor w/ 6 levels "Husband","Not-in-family",..: $ race : Factor w/ 5 levels "Amer-Indian-Eskimo",..: 5 5 5 $ sex : Factor w/ 2 levels "Female","Male": 2 2 2 2 1 1 1 $ capital-gain : int 2174 0 0 0 0 0 0 0 14084 5178 ... $ capital-loss : int 0 0 0 0 0 0 0 0 0 0 ... $ hours-per-week: int 40 13 40 40 40 40 16 45 50 40 ... $ native-country: Factor w/ 41 levels "Cambodia","Canada",..: 39 39 $ income : Ord.factor w/ 2 levels "small"<"large": 1 1 1 1 1 In AdultUCI dataframe, columns 1, 3, 5, 11, 12, 13 are integers. So convert each of the column into factor. > AdultUCI <- lapply(AdultUCI, function(x){as.factor(x)})> str(AdultUCI)List of 15 $ age : Factor w/ 74 levels "17","18","19",..: 23 34 22 $ workclass : Factor w/ 8 levels "Federal-gov",..: 7 6 4 4 4 4 $ fnlwgt : Factor w/ 28523 levels "12285","13492",..: 3462 $ education : Ord.factor w/ 16 levels "Preschool"<"1st-4th"<..: $ education-num : Factor w/ 16 levels "1","2","3","4",..: 13 13 9 7 $ marital-status: Factor w/ 7 levels "Divorced","Married-AF- $ occupation : Factor w/ 14 levels "Adm-clerical",..: 1 4 6 6 10 $ relationship : Factor w/ 6 levels "Husband","Not-in-family",..: $ race : Factor w/ 5 levels "Amer-Indian-Eskimo",..: 5 5 5 $ sex : Factor w/ 2 levels "Female","Male": 2 2 2 2 1 1 $ capital-gain : Factor w/ 123 levels "0","114","401",..: 28 1 1 1 $ capital-loss : Factor w/ 99 levels "0","155","213",..: 1 1 1 1 1 $ hours-per-week: Factor w/ 96 levels "1","2","3","4",..: 40 13 40 $ native-country: Factor w/ 41 levels "Cambodia","Canada",..: 39 39 $ income : Ord.factor w/ 2 levels "small"<"large": 1 1 1 1 1 Now AdultUCI dataframe can be converted into a transactional dataset using the code snippet below. > transactional_data <- as(AdultUCI, "transactions") This concludes this article on Association Rule Mining.
[ { "code": null, "e": 744, "s": 172, "text": "Association Rule Mining (also called as Association Rule Learning) is a common technique used to find associations between many variables. It is often used by grocery stores, e-commerce websites, and anyone with large transactional databases. A most common example that we encounter in our daily lives — Amazon knows what else you want to buy when you order something on their site. The same idea extends to Spotify too — They know what song you want to listen to next. All of these incorporate, at some level, data mining concepts and association rule mining algorithms." }, { "code": null, "e": 1140, "s": 744, "text": "Market Basket Analysis is similar to ARM. Market Basket Analysis is a modelling technique based upon the theory that if you buy a certain group of items, you are more (or less) likely to buy another group of items. For example, if you are in an English pub and you buy a pint of beer and don’t buy a bar meal, you are more likely to buy crisps at the same time than somebody who didn’t buy beer." }, { "code": null, "e": 1392, "s": 1140, "text": "Based on the concept of strong rules, Rakesh Agrawal, Tomasz Imieliński and Arun Swami introduced association rules for discovering regularities between products in large-scale transaction data recorded by point-of-sale (POS) systems in supermarkets." }, { "code": null, "e": 1488, "s": 1392, "text": "This article explains the concept of Association Rule Mining and how to use this technique in R" }, { "code": null, "e": 1580, "s": 1488, "text": "To perform Association Rule Mining in R, we use the arules and the arulesViz packages in R." }, { "code": null, "e": 1741, "s": 1580, "text": "Michael Hahsler, et al. has authored and maintains two very useful R packages relating to association rule mining: the arules package and the arulesViz package." }, { "code": null, "e": 1851, "s": 1741, "text": "If you don’t have these packages installed in your system, please use the following commands to install them." }, { "code": null, "e": 1911, "s": 1851, "text": "> install.packages(\"arules\")> install.packages(\"arulesViz\")" }, { "code": null, "e": 1986, "s": 1911, "text": "I’m using the AdultUCI dataset that comes bundled with the arules package." }, { "code": null, "e": 2006, "s": 1986, "text": "> data(“Groceries”)" }, { "code": null, "e": 2045, "s": 2006, "text": "Lets inspect the Groceries data first." }, { "code": null, "e": 2128, "s": 2045, "text": "> class(Groceries) [1] \"transactions\" attr(,\"package\") [1] \"arules\"" }, { "code": null, "e": 2159, "s": 2128, "text": "It is a transactional dataset." }, { "code": null, "e": 2361, "s": 2159, "text": "> inspect(head(Groceries, 2)) items [1] {citrus fruit,semi-finished bread,margarine,ready soups} [2] {tropical fruit,yogurt,coffee}" }, { "code": null, "e": 2470, "s": 2361, "text": "The first two transactions and the items involved in each transaction can be observed from the output above." }, { "code": null, "e": 2705, "s": 2470, "text": "There are three parameters controlling the number of rules to be generated viz. Support and Confidence. Another parameter Lift is generated using Support and Confidence and is one of the major parameters to filter the generated rules." }, { "code": null, "e": 2939, "s": 2705, "text": "Support is an indication of how frequently the itemset appears in the dataset. Consider only the two transactions from the above output. The support of the item citrus fruit is 1/2 as it appears in only 1 out of the two transactions." }, { "code": null, "e": 3082, "s": 2939, "text": "Confidence is an indication of how often the rule has been found to be true. We will discuss more about confidence after generating the rules." }, { "code": null, "e": 3135, "s": 3082, "text": "Lets find out the rules using the apriori algorithm." }, { "code": null, "e": 3966, "s": 3135, "text": "> grocery_rules <- apriori(Groceries, parameter = list(support = 0.01, confidence = 0.5))AprioriParameter specification: confidence minval smax arem aval originalSupport maxtime support minlen maxlen target ext 0.5 0.1 1 none FALSE TRUE 5 0.01 1 10 rules FALSEAlgorithmic control: filter tree heap memopt load sort verbose 0.1 TRUE TRUE FALSE TRUE 2 TRUEAbsolute minimum support count: 98set item appearances ...[0 item(s)] done [0.00s]. set transactions ...[169 item(s), 9835 transaction(s)] done [0.00s]. sorting and recoding items ... [88 item(s)] done [0.00s]. creating transaction tree ... done [0.00s]. checking subsets of size 1 2 3 4 done [0.00s]. writing ... [15 rule(s)] done [0.00s]. creating S4 object ... done [0.00s]." }, { "code": null, "e": 4101, "s": 3966, "text": "The Apriori algorithm generated 15 rules with the given constraints. Lets dive into the Parameter Specification section of the output." }, { "code": null, "e": 4194, "s": 4101, "text": "minval is the minimum value of the support an itemset should satisfy to be a part of a rule." }, { "code": null, "e": 4244, "s": 4194, "text": "smax is the maximum support value for an itemset." }, { "code": null, "e": 4530, "s": 4244, "text": "arem is an Additional Rule Evaluation Parameter. In the above code we have constrained the number of rules using Support and Confidence. There are several other ways to constrain the rules using the arem parameter in the function and we will discuss more about it later in the article." }, { "code": null, "e": 4636, "s": 4530, "text": "aval is a logical indicating whether to return the additional rule evaluation measure selected with arem." }, { "code": null, "e": 4839, "s": 4636, "text": "originalSupport The traditional support value only considers both LHS and RHS items for calculating support. If you want to use only the LHS items for the calculation then you need to set this to FALSE." }, { "code": null, "e": 4907, "s": 4839, "text": "maxtime is the maximum amount of time allowed to check for subsets." }, { "code": null, "e": 4967, "s": 4907, "text": "minlen is the minimum number of items required in the rule." }, { "code": null, "e": 5038, "s": 4967, "text": "maxlen is the maximum number of items that can be present in the rule." }, { "code": null, "e": 5487, "s": 5038, "text": "> inspect(head(sort(rules, by = \"confidence\"), 3)) lhs rhs support confidence lift count [1] {citrus fruit,root vegetables} => {other vegetables} 0.01037112 0.5862069 3.029608 102 [2] {tropical fruit,root vegetables} => {other vegetables} 0.01230300 0.5845411 3.020999 121 [3] {curd,yogurt} => {whole milk} 0.01006609 0.5823529 2.279125 99" }, { "code": null, "e": 5541, "s": 5487, "text": "The top 3 rules sorted by confidence are shown above." }, { "code": null, "e": 6093, "s": 5541, "text": "In many cases, you would like to limit the number of rules generated. For example, you can use association rules as predictors in Regression/Classification. You can generate rules with the Right Hand Side of the rule as your response and use the rules generated as the modelling features. In this case, you would not want to use all the rules generated as the predictors because many rules are actually subsets of bigger rules and hence you would want to eliminate them. The following code snippet shows how to generate rules whose RHS is pre-defined." }, { "code": null, "e": 6347, "s": 6093, "text": "wholemilk_rules <- apriori(data=Groceries, parameter=list (supp=0.001,conf = 0.08), appearance = list (rhs=\"whole milk\"))# The above code shows what products are bought before buying \"whole milk\" and will generate rules that lead to buying \"whole milk\"." }, { "code": null, "e": 6597, "s": 6347, "text": "You can limit the number of rules by tweaking a few parameters. Although the parameter tweaking depends on the kind of data you are dealing with, the most common ways include changing support, confidence and other parameters like minlen, maxlen etc." }, { "code": null, "e": 6750, "s": 6597, "text": "> grocery_rules_increased_support <- apriori(Groceries, parameter = list(support = 0.02, confidence = 0.5))# This generates only one rule in the output." }, { "code": null, "e": 6952, "s": 6750, "text": "If you want to get stronger rules, you have to increase the confidence. If you want lengthier rules increase the maxlen parameter. If you want to eliminate shorter rules, decrease the minlen parameter." }, { "code": null, "e": 7153, "s": 6952, "text": "Sometimes you might be interested in finding the rules involving maximum number of items and remove the shorter rules that are subsets of the longer rules. The below code removes such redundant rules." }, { "code": null, "e": 7267, "s": 7153, "text": "> subsets <- which(colSums(is.subset(grocery_rules, groery_rules)) > 1)> grocery_rules <- grocery_rules[-subsets]" }, { "code": null, "e": 7504, "s": 7267, "text": "Lets look at the arem parameter that was described earlier. The rules, after geneartion, are further evaluated based on the value of the arem parameter. The arem parameter takes the following values — none, diff, quot, aimp, info, chi2." }, { "code": null, "e": 7738, "s": 7504, "text": "# This gives more than 1,500,000 rules> rules <- apriori(Groceries, parameter = list(supp = 0.0001, conf = 0.5))# This gives 982,000 rules.> rules_chi2 <- apriori(Groceries, parameter = list(supp = 0.0001, conf = 0.5, arem = \"chi2\"))" }, { "code": null, "e": 7796, "s": 7738, "text": "The AdultUCI dataset bundled with arules package is used." }, { "code": null, "e": 7850, "s": 7796, "text": "> data(\"AdultUCI\")> class(AdultUCI) \"data.frame\"" }, { "code": null, "e": 8496, "s": 7850, "text": "When you look at the structure of the AdultUCI dataframe, you observe that a few columns are numeric. Each transaction of a transactional dataset contains the list of items involved in that transaction. When we convert the dataframe into a transactional dataset, each row of this dataframe will become a transaction. Each column will become an item. But if the value of a column is numeric, it cannot be used as the column can take infinite values. So before converting the dataframe into a transactional dataset, we must ensure that we convert each column into a factor or a logical to ensure that the column takes values only from a fixed set." }, { "code": null, "e": 9507, "s": 8496, "text": "> str(AdultUCI)'data.frame':\t48842 obs. of 15 variables: $ age : int 39 50 38 53 28 37 49 52 31 42 ... $ workclass : Factor w/ 8 levels \"Federal-gov\",..: 7 6 4 4 4 4 $ fnlwgt : int 77516 83311 215646 234721 338409 284582 $ education : Ord.factor w/ 16 levels \"Preschool\"<\"1st-4th\"<..: $ education-num : int 13 13 9 7 13 14 5 9 14 13 ... $ marital-status: Factor w/ 7 levels \"Divorced\",\"Married-AF-Spouse\" $ occupation : Factor w/ 14 levels \"Adm-clerical\",..: 1 4 6 6 10 $ relationship : Factor w/ 6 levels \"Husband\",\"Not-in-family\",..: $ race : Factor w/ 5 levels \"Amer-Indian-Eskimo\",..: 5 5 5 $ sex : Factor w/ 2 levels \"Female\",\"Male\": 2 2 2 2 1 1 1 $ capital-gain : int 2174 0 0 0 0 0 0 0 14084 5178 ... $ capital-loss : int 0 0 0 0 0 0 0 0 0 0 ... $ hours-per-week: int 40 13 40 40 40 40 16 45 50 40 ... $ native-country: Factor w/ 41 levels \"Cambodia\",\"Canada\",..: 39 39 $ income : Ord.factor w/ 2 levels \"small\"<\"large\": 1 1 1 1 1 " }, { "code": null, "e": 9615, "s": 9507, "text": "In AdultUCI dataframe, columns 1, 3, 5, 11, 12, 13 are integers. So convert each of the column into factor." }, { "code": null, "e": 10712, "s": 9615, "text": "> AdultUCI <- lapply(AdultUCI, function(x){as.factor(x)})> str(AdultUCI)List of 15 $ age : Factor w/ 74 levels \"17\",\"18\",\"19\",..: 23 34 22 $ workclass : Factor w/ 8 levels \"Federal-gov\",..: 7 6 4 4 4 4 $ fnlwgt : Factor w/ 28523 levels \"12285\",\"13492\",..: 3462 $ education : Ord.factor w/ 16 levels \"Preschool\"<\"1st-4th\"<..: $ education-num : Factor w/ 16 levels \"1\",\"2\",\"3\",\"4\",..: 13 13 9 7 $ marital-status: Factor w/ 7 levels \"Divorced\",\"Married-AF- $ occupation : Factor w/ 14 levels \"Adm-clerical\",..: 1 4 6 6 10 $ relationship : Factor w/ 6 levels \"Husband\",\"Not-in-family\",..: $ race : Factor w/ 5 levels \"Amer-Indian-Eskimo\",..: 5 5 5 $ sex : Factor w/ 2 levels \"Female\",\"Male\": 2 2 2 2 1 1 $ capital-gain : Factor w/ 123 levels \"0\",\"114\",\"401\",..: 28 1 1 1 $ capital-loss : Factor w/ 99 levels \"0\",\"155\",\"213\",..: 1 1 1 1 1 $ hours-per-week: Factor w/ 96 levels \"1\",\"2\",\"3\",\"4\",..: 40 13 40 $ native-country: Factor w/ 41 levels \"Cambodia\",\"Canada\",..: 39 39 $ income : Ord.factor w/ 2 levels \"small\"<\"large\": 1 1 1 1 1 " }, { "code": null, "e": 10811, "s": 10712, "text": "Now AdultUCI dataframe can be converted into a transactional dataset using the code snippet below." }, { "code": null, "e": 10864, "s": 10811, "text": "> transactional_data <- as(AdultUCI, \"transactions\")" } ]
How to check whether a script is running under Node.js or not ? - GeeksforGeeks
14 Jul, 2020 In JavaScript, there is not any specific function or method to get the environment on which the script is running. But we can make some checks to identify whether a script is running on Node.js or in the browser. Using process class in Node.js: Each Node.js process has a set of built-in functionality, accessible through the global process module. The process module doesn’t need to be required – it is somewhat literally a wrapper around the currently executing process, and many of the methods it exposes are actually wrappers around calls into core C libraries. Code Snippet: if ((typeof process !== 'undefined') && (process.release.name.search(/node|io.js/) !== -1)) { console.log('this script is running in Node.js');} else { console.log('this script is not running in Node.js');} In this code snippet, all we are doing is just checking if the process module is exists or not. If the process is not undefined then we have to check if the name property of release method in process class is either node or io.js (for io.js releases of the node). Using module in Node.js: This is the generally accepted solution that is also used in the underscore.js library. This technique is actually perfectly fine for the server-side, as when the require function is called, it resets the this object to an empty object, and redefines module for you again, this means you don’t have to worry about any outside tampering. As long as your code is loaded with require, you are safe. Code Snippet: if (typeof module !== 'undefined' && module.exports) { console.log('this script is running in Node.js');} else { console.log('this script is not running in Node.js');} However, this falls apart on the browser, as anyone can easily define a module to make it seem like it’s the object you are looking for. On one hand, this might be the behavior you want, but it also dictates what variables the library user can use in the global scope. Maybe someone wants to use a variable with the named module that has exports inside of it for another use. Steps to Run the code with Node.js: Create a file index.js with the above code.Run the file on Terminal with the following command:node index.jsOutput:Output of program in Node.js Create a file index.js with the above code. Run the file on Terminal with the following command:node index.jsOutput:Output of program in Node.js node index.js Output: Output of program in Node.js Steps to Run the code in Browser: Create a file index.js with the above code.Create another file index.html in the same directory with the code below:<!DOCTYPE html><html><head> <title>GFG</title> <script src="./index.js"></script></head><body> <h3> How to check whether a script is running under Node.js or not? </h3></body></html>To run the code, double click on index.html and it will open in browser.Open browser console to check the output.Output:Output of program in Browser Create a file index.js with the above code. Create another file index.html in the same directory with the code below:<!DOCTYPE html><html><head> <title>GFG</title> <script src="./index.js"></script></head><body> <h3> How to check whether a script is running under Node.js or not? </h3></body></html> <!DOCTYPE html><html><head> <title>GFG</title> <script src="./index.js"></script></head><body> <h3> How to check whether a script is running under Node.js or not? </h3></body></html> To run the code, double click on index.html and it will open in browser. Open browser console to check the output.Output:Output of program in Browser Output: Output of program in Browser Conclusion: You can use any of the above methods to determine whether your script is running in Node or not. But the problem with trying to figure out what environment your code is running is that any object can be modified and re-declared making it close to impossible to figure out which objects are native to the environment, and which have been modified by the program. Node.js-Misc Picked Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between dependencies, devDependencies and peerDependencies Mongoose Populate() Method Node.js Export Module Mongoose find() Function How to connect Node.js with React.js ? Remove elements from a JavaScript Array 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? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26267, "s": 26239, "text": "\n14 Jul, 2020" }, { "code": null, "e": 26480, "s": 26267, "text": "In JavaScript, there is not any specific function or method to get the environment on which the script is running. But we can make some checks to identify whether a script is running on Node.js or in the browser." }, { "code": null, "e": 26833, "s": 26480, "text": "Using process class in Node.js: Each Node.js process has a set of built-in functionality, accessible through the global process module. The process module doesn’t need to be required – it is somewhat literally a wrapper around the currently executing process, and many of the methods it exposes are actually wrappers around calls into core C libraries." }, { "code": null, "e": 26847, "s": 26833, "text": "Code Snippet:" }, { "code": "if ((typeof process !== 'undefined') && (process.release.name.search(/node|io.js/) !== -1)) { console.log('this script is running in Node.js');} else { console.log('this script is not running in Node.js');}", "e": 27060, "s": 26847, "text": null }, { "code": null, "e": 27324, "s": 27060, "text": "In this code snippet, all we are doing is just checking if the process module is exists or not. If the process is not undefined then we have to check if the name property of release method in process class is either node or io.js (for io.js releases of the node)." }, { "code": null, "e": 27745, "s": 27324, "text": "Using module in Node.js: This is the generally accepted solution that is also used in the underscore.js library. This technique is actually perfectly fine for the server-side, as when the require function is called, it resets the this object to an empty object, and redefines module for you again, this means you don’t have to worry about any outside tampering. As long as your code is loaded with require, you are safe." }, { "code": null, "e": 27759, "s": 27745, "text": "Code Snippet:" }, { "code": "if (typeof module !== 'undefined' && module.exports) { console.log('this script is running in Node.js');} else { console.log('this script is not running in Node.js');}", "e": 27933, "s": 27759, "text": null }, { "code": null, "e": 28309, "s": 27933, "text": "However, this falls apart on the browser, as anyone can easily define a module to make it seem like it’s the object you are looking for. On one hand, this might be the behavior you want, but it also dictates what variables the library user can use in the global scope. Maybe someone wants to use a variable with the named module that has exports inside of it for another use." }, { "code": null, "e": 28345, "s": 28309, "text": "Steps to Run the code with Node.js:" }, { "code": null, "e": 28489, "s": 28345, "text": "Create a file index.js with the above code.Run the file on Terminal with the following command:node index.jsOutput:Output of program in Node.js" }, { "code": null, "e": 28533, "s": 28489, "text": "Create a file index.js with the above code." }, { "code": null, "e": 28634, "s": 28533, "text": "Run the file on Terminal with the following command:node index.jsOutput:Output of program in Node.js" }, { "code": null, "e": 28648, "s": 28634, "text": "node index.js" }, { "code": null, "e": 28656, "s": 28648, "text": "Output:" }, { "code": null, "e": 28685, "s": 28656, "text": "Output of program in Node.js" }, { "code": null, "e": 28719, "s": 28685, "text": "Steps to Run the code in Browser:" }, { "code": null, "e": 29193, "s": 28719, "text": "Create a file index.js with the above code.Create another file index.html in the same directory with the code below:<!DOCTYPE html><html><head> <title>GFG</title> <script src=\"./index.js\"></script></head><body> <h3> How to check whether a script is running under Node.js or not? </h3></body></html>To run the code, double click on index.html and it will open in browser.Open browser console to check the output.Output:Output of program in Browser" }, { "code": null, "e": 29237, "s": 29193, "text": "Create a file index.js with the above code." }, { "code": null, "e": 29520, "s": 29237, "text": "Create another file index.html in the same directory with the code below:<!DOCTYPE html><html><head> <title>GFG</title> <script src=\"./index.js\"></script></head><body> <h3> How to check whether a script is running under Node.js or not? </h3></body></html>" }, { "code": "<!DOCTYPE html><html><head> <title>GFG</title> <script src=\"./index.js\"></script></head><body> <h3> How to check whether a script is running under Node.js or not? </h3></body></html>", "e": 29730, "s": 29520, "text": null }, { "code": null, "e": 29803, "s": 29730, "text": "To run the code, double click on index.html and it will open in browser." }, { "code": null, "e": 29880, "s": 29803, "text": "Open browser console to check the output.Output:Output of program in Browser" }, { "code": null, "e": 29888, "s": 29880, "text": "Output:" }, { "code": null, "e": 29917, "s": 29888, "text": "Output of program in Browser" }, { "code": null, "e": 30291, "s": 29917, "text": "Conclusion: You can use any of the above methods to determine whether your script is running in Node or not. But the problem with trying to figure out what environment your code is running is that any object can be modified and re-declared making it close to impossible to figure out which objects are native to the environment, and which have been modified by the program." }, { "code": null, "e": 30304, "s": 30291, "text": "Node.js-Misc" }, { "code": null, "e": 30311, "s": 30304, "text": "Picked" }, { "code": null, "e": 30319, "s": 30311, "text": "Node.js" }, { "code": null, "e": 30336, "s": 30319, "text": "Web Technologies" }, { "code": null, "e": 30434, "s": 30336, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30504, "s": 30434, "text": "Difference between dependencies, devDependencies and peerDependencies" }, { "code": null, "e": 30531, "s": 30504, "text": "Mongoose Populate() Method" }, { "code": null, "e": 30553, "s": 30531, "text": "Node.js Export Module" }, { "code": null, "e": 30578, "s": 30553, "text": "Mongoose find() Function" }, { "code": null, "e": 30617, "s": 30578, "text": "How to connect Node.js with React.js ?" }, { "code": null, "e": 30657, "s": 30617, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 30702, "s": 30657, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 30745, "s": 30702, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 30795, "s": 30745, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Project Manager | Practice | GeeksforGeeks
An IT company is working on a large project. The project is broken into N modules and distributed to different teams. Each team can work parallelly. The amount of time (in months) required to complete each module is given in an array duration[ ] i.e. time needed to complete ith module is duration[i] months. You are also given M dependencies such that for each i (1 ≤ i ≤ M) dependencies[i][1]th module can be started after dependencies[i][0]th module is completed. As the project manager, compute the minimum time required to complete the project. Note: It is guaranteed that a module is not dependent on itself. Example 1: Input: N = 6, M = 6 duration[] = {1, 2, 3, 1, 3, 2} dependencies[][]: [[5, 2] [5, 0] [4, 0] [4, 1] [2, 3] [3, 1]] Output: 8 Explanation: The Graph of dependency forms this and the project will be completed when Module 1 is completed which takes 8 months. Example 2: Input: N = 3, M = 3 duration[] = {5, 5, 5} dependencies[][]: [[0, 1] [1, 2] [2, 0]] Output: -1 Explanation: There is a cycle in the dependency graph hence the project cannot be completed. Your Task: Complete the function minTime() which takes N, M, duration array, and dependencies array as input parameter and return the minimum time required. return -1 if the project can not be completed. Expected Time Complexity: O(N+M) Expected Auxiliary Space: O(N) Constraints: 1 ≤ N ≤ 105 0 ≤ M ≤ 2*105 1 ≤ duration[i] ≤ 105 0 ≤ dependencies[i][j] < N 0 aliaksandrhn2 months ago class Solution { public int minTime(ArrayList<pair> dependency, int[] duration, int n, int m) { int max = 0, tasks = 0; for(int num: duration) max = Math.max(max, num); Map<Integer, List<Integer>> map = new HashMap<>(); int[] inDegree = new int[n], time = new int[n]; for(pair p: dependency) { map.putIfAbsent(p.x, new ArrayList<>()); map.get(p.x).add(p.y); inDegree[p.y] ++ ; } Queue<Integer> que = new LinkedList<>(); for(int i = 0; i < n; i ++) { if(inDegree[i] == 0) { que.add(i); time[i] = duration[i]; } } while(!que.isEmpty()) { int cur = que.poll(); tasks ++ ; if(!map.containsKey(cur)) continue; List<Integer> l = map.get(cur); for(int next: l) { if(--inDegree[next] == 0) que.add(next); time[next] = Math.max(time[next], time[cur] + duration[next]); max = Math.max(max, time[next]); } } return tasks < n ? -1 : max; } } 0 aliaksandrhn2 months ago How is the answer in Example 1 8? In order to complete task 1, we need to complete 5→2→3→1 which is: 5→2 1 month, 2→3 3 months, 3→1 2 months, so 1 + 3 + 2 = 6. How did they get 8? 0 triple2double13 months ago JUST 3 LINE CHANGE IN TYPICAL TOPOSORT I feel so dumb for not able to solve this “79% accuracy rate question”. The answer to first question in not 6 ,don't do that mistake , take luck against you ,you can do module 1 in 5 and 8 months , but if someone asks you for guarantee ,you won't say 5. you just need to find the max(min time to complete each module) ,where the min time to complete module i is max(all ways you can do that module following the dependencies) class Solution{ public: int minTime(vector<pair<int, int>> &dedency, int dur[], int n, int m) { vector<vector<int>> adj_list(n); vector<int>mt_of_modules(dur,dur+n); vector<int>topo_sort; vector<int>in(n,0); for(auto &d:dedency){ adj_list[d.first].push_back(d.second); in[d.second]++; } queue<int>q; for(int i=0;i<n;i++){ if(in[i]==0) q.push(i); } while(q.size()!=0) { auto f=q.front();q.pop(); topo_sort.push_back(f); for(auto nbr:adj_list[f]){ in[nbr]--; if(in[nbr]==0){ q.push(nbr); } } } if(topo_sort.size()!=n) return -1; for(auto ts:topo_sort) { for(auto nbr:adj_list[ts]){ mt_of_modules[nbr]=max(mt_of_modules[nbr], mt_of_modules[ts]+dur[nbr]); } } return *max_element(mt_of_modules.begin(),mt_of_modules.end()); } }; 0 ghazanferwahab26 months ago can someone give solution in java?? 0 rohit_iiitl7 months ago dp[i] = min time required to complete ith task. Algorithm:Firstly assign dp[i] to duration[i], as it is min time required to perform that task. Now, lets say task B is dependent on A, then time reqd for B will be time of A + time of B (as A needs to be performed before B) (dp[B] = dp[A] + dp[B]). Now lets say B is also dependent on C, and C and A are independent. For this case dp[B] = dp[C] + dp[B], but this this will not solve our problem, as we are ignoring A. Therefore, dp[B] = max(dp[A] + dp[B], dp[C] + dp[B]), as if A takes more time than C, then we need to wait for A to complete before performing task B. i.e; calculating max of both. We are taking maximum of it, but actually dp[B] is minimum time required to complete task B (waiting for both A and C before doing B). Use kahn's algorithm to solve for all dependency. At last for every i, dp[i] will contain minimum time required to complete that particular task. Hence if we find max of this array. Then it will be minimum time required for whole process (to complete all tasks), as other tasks can run parallelly and complete before that max time. In solution denoting dp[ ] as timeReqd[ ] int minTime(vector<pair<int, int>> &dependency, int duration[], int n, int m) { vector<int> indegree(n, 0), timeReqd(n, 0), adj[n]; queue<int> q; for(int i=0; i<m; i++) { indegree[dependency[i].second]++; adj[dependency[i].first].push_back(dependency[i].second); } for(int i=0; i<n; i++) { if(indegree[i] == 0) q.push(i), timeReqd[i]=duration[i]; } int numNodes=0; while(!q.empty()) { int front = q.front(); q.pop(); numNodes++; for(auto v:adj[front]) { timeReqd[v] = max(timeReqd[v], timeReqd[front]+duration[v]); if(--indegree[v] == 0) q.push(v); } } if(numNodes != n) return -1; return *max_element(timeReqd.begin(), timeReqd.end()); } +1 anutiger7 months ago public: struct Node{ int node; int val; int price; Node(int x,int y){ node = x; val = y; price = 0; } }; int minTime(vector<pair<int, int>> &dep, int dur[], int n, int m) { vector<int> vis(n , 1); vector<int> adj[n]; vector<int> cnt(n , 0); vector<Node*> tmp; for(int i = 0 ; i < n ; i ++){ Node *temp = new Node(i,dur[i]); tmp.push_back(temp); } for(int i = 0 ; i < m ; i ++){ int x = dep[i].first; int y = dep[i].second; adj[x].push_back(y); cnt[y]++; } queue<Node*>pq; while(true){ if(pq.empty()){ int flag = 1; for(int i = 0; i < n ; i ++){ if(cnt[i] == 0){ pq.push(tmp[i]); cnt[i] = -1; flag = 0; } } if(flag) break; } int size = pq.size(); for(int i = 0; i < size; i ++){ auto it = pq.front();pq.pop(); int price = it->val + it->price; if(adj[it->node].size() == 0){ tmp[it->node]->price += tmp[it->node]->val; continue; } for(int j : adj[it->node]){ auto t = tmp[j]; if(t->price < price){ t->price = max(t->price,price); } cnt[j]--; } } } for(int i = 0; i < n ; i ++){ if(cnt[i] > 0) return -1; } int res = 0; for(int i = 0 ; i < n ; i ++){ res = max(res,tmp[i]->price); } if(res == 0) return -1; return res; } +1 sunnysaraff7 months ago int minTime(vector<pair<int, int>> &dependency, int duration[], int n, int m) { vector<int> adj[n],in(n),dist(n,INT_MIN); vector<bool> vis(n,false),rec(n,false); for(auto& edge:dependency){ adj[edge.first].push_back(edge.second); in[edge.second]++; } queue<int> q; for(int i=0;i<n;i++){ if(!in[i]){ dist[i] = duration[i]; q.push(i); } } int cnt = 0; while(!q.empty()){ int v = q.front(); q.pop(); cnt++; for(auto& u:adj[v]){ in[u]--; dist[u] = max(dist[u],dist[v]); if(!in[u]){ dist[u] += duration[u]; q.push(u); } } } return (cnt==n)?*max_element(dist.begin(),dist.end()):-1; } +3 geminicode7 months ago Hi can anyone explain why the answer of example-1 is 8 and not 9? 0 rishug7707 months ago #Python Solution. Topological Sorting and a touch of dynamic programming indeg=[0]*n ans=[] q=[] dp=[] adj=[] for i in range(n): adj.append([]) dp.append(duration[i]) for i in range(m): indeg[dependency[i][1]]+=1 adj[dependency[i][0]].append(dependency[i][1]) for i in range(n): if(indeg[i]==0): q.append(i) while(q): a=q.pop(0) ans.append(a) for i in adj[a]: dp[i]=max(dp[i],duration[i]+dp[a]) indeg[i]-=1 if(indeg[i]==0): q.append(i) if(len(ans)!=n): return -1 return max(dp) +4 mastermind_7 months ago (C++) Topological Sorting( Kahn's Algorithm ) + DP Solution, ~ Fastest ~ 0.0 s ~ O(M+N) int minTime(vector<pair<int, int>> &d, int dur[], int n, int m) { vector<int> indeg(n, 0), topo, dp(n, 0), adj[n]; queue<int> q; for(int i=0;i<m;i++)indeg[d[i].second]++,adj[d[i].first].push_back(d[i].second); for (int i = 0; i < n; i++)if (indeg[i] == 0)q.push(i), dp[i] = dur[i]; while (!q.empty()) { auto x = q.front(); q.pop(); topo.push_back(x); for (auto v : adj[x]) { dp[v] = max(dp[v], dur[v] + dp[x]); if (--indeg[v]==0)q.push(v); } } if (topo.size() != n)return -1; // contains cycle !!! return *max_element(dp.begin(), dp.end()); } We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 843, "s": 226, "text": "An IT company is working on a large project. The project is broken into N modules and distributed to different teams. Each team can work parallelly. The amount of time (in months) required to complete each module is given in an array duration[ ] i.e. time needed to complete ith module is duration[i] months. \nYou are also given M dependencies such that for each i (1 ≤ i ≤ M) dependencies[i][1]th module can be started after dependencies[i][0]th module is completed.\nAs the project manager, compute the minimum time required to complete the project.\nNote: It is guaranteed that a module is not dependent on itself." }, { "code": null, "e": 854, "s": 843, "text": "Example 1:" }, { "code": null, "e": 1121, "s": 854, "text": "Input:\nN = 6, M = 6\nduration[] = {1, 2, 3, 1, 3, 2}\ndependencies[][]:\n[[5, 2]\n [5, 0]\n [4, 0] \n [4, 1]\n [2, 3]\n [3, 1]]\nOutput: \n8\nExplanation: \n\nThe Graph of dependency forms this and \nthe project will be completed when Module \n1 is completed which takes 8 months.\n" }, { "code": null, "e": 1132, "s": 1121, "text": "Example 2:" }, { "code": null, "e": 1326, "s": 1132, "text": "Input:\nN = 3, M = 3\nduration[] = {5, 5, 5}\ndependencies[][]:\n[[0, 1]\n [1, 2]\n [2, 0]]\nOutput: \n-1\nExplanation: \nThere is a cycle in the dependency graph \nhence the project cannot be completed.\n" }, { "code": null, "e": 1531, "s": 1326, "text": "Your Task:\nComplete the function minTime() which takes N, M, duration array, and dependencies array as input parameter and return the minimum time required. return -1 if the project can not be completed. " }, { "code": null, "e": 1595, "s": 1531, "text": "Expected Time Complexity: O(N+M)\nExpected Auxiliary Space: O(N)" }, { "code": null, "e": 1683, "s": 1595, "text": "Constraints:\n1 ≤ N ≤ 105\n0 ≤ M ≤ 2*105\n1 ≤ duration[i] ≤ 105\n0 ≤ dependencies[i][j] < N" }, { "code": null, "e": 1685, "s": 1683, "text": "0" }, { "code": null, "e": 1710, "s": 1685, "text": "aliaksandrhn2 months ago" }, { "code": null, "e": 2877, "s": 1710, "text": "class Solution {\n public int minTime(ArrayList<pair> dependency, int[] duration, int n, int m) {\n int max = 0, tasks = 0;\n for(int num: duration) max = Math.max(max, num);\n Map<Integer, List<Integer>> map = new HashMap<>();\n int[] inDegree = new int[n], time = new int[n];\n for(pair p: dependency) {\n map.putIfAbsent(p.x, new ArrayList<>());\n map.get(p.x).add(p.y);\n inDegree[p.y] ++ ;\n }\n Queue<Integer> que = new LinkedList<>();\n for(int i = 0; i < n; i ++) {\n if(inDegree[i] == 0) {\n que.add(i);\n time[i] = duration[i];\n }\n }\n while(!que.isEmpty()) {\n int cur = que.poll();\n tasks ++ ;\n if(!map.containsKey(cur)) continue;\n List<Integer> l = map.get(cur);\n for(int next: l) {\n if(--inDegree[next] == 0) \n que.add(next);\n time[next] = Math.max(time[next], time[cur] + duration[next]);\n max = Math.max(max, time[next]);\n }\n }\n return tasks < n ? -1 : max;\n }\n}" }, { "code": null, "e": 2879, "s": 2877, "text": "0" }, { "code": null, "e": 2904, "s": 2879, "text": "aliaksandrhn2 months ago" }, { "code": null, "e": 3084, "s": 2904, "text": "How is the answer in Example 1 8? In order to complete task 1, we need to complete 5→2→3→1 which is: 5→2 1 month, 2→3 3 months, 3→1 2 months, so 1 + 3 + 2 = 6. How did they get 8?" }, { "code": null, "e": 3086, "s": 3084, "text": "0" }, { "code": null, "e": 3113, "s": 3086, "text": "triple2double13 months ago" }, { "code": null, "e": 3152, "s": 3113, "text": "JUST 3 LINE CHANGE IN TYPICAL TOPOSORT" }, { "code": null, "e": 3224, "s": 3152, "text": "I feel so dumb for not able to solve this “79% accuracy rate question”." }, { "code": null, "e": 3409, "s": 3226, "text": "The answer to first question in not 6 ,don't do that mistake , take luck against you ,you can do module 1 in 5 and 8 months , but if someone asks you for guarantee ,you won't say 5. " }, { "code": null, "e": 3581, "s": 3409, "text": "you just need to find the max(min time to complete each module) ,where the min time to complete module i is max(all ways you can do that module following the dependencies)" }, { "code": null, "e": 4723, "s": 3583, "text": "class Solution{\n public:\n int minTime(vector<pair<int, int>> &dedency, int dur[], int n, int m) {\n vector<vector<int>> adj_list(n);\n vector<int>mt_of_modules(dur,dur+n);\n vector<int>topo_sort;\n \n vector<int>in(n,0);\n for(auto &d:dedency){\n adj_list[d.first].push_back(d.second);\n in[d.second]++;\n }\n \n queue<int>q;\n for(int i=0;i<n;i++){\n if(in[i]==0)\n q.push(i);\n }\n \n \n while(q.size()!=0)\n {\n auto f=q.front();q.pop();\n topo_sort.push_back(f);\n for(auto nbr:adj_list[f]){\n in[nbr]--;\n if(in[nbr]==0){\n q.push(nbr);\n }\n }\n }\n if(topo_sort.size()!=n)\n return -1;\n \n for(auto ts:topo_sort)\n { \n for(auto nbr:adj_list[ts]){\n mt_of_modules[nbr]=max(mt_of_modules[nbr], mt_of_modules[ts]+dur[nbr]);\n }\n }\n return *max_element(mt_of_modules.begin(),mt_of_modules.end());\n \n }\n};" }, { "code": null, "e": 4727, "s": 4725, "text": "0" }, { "code": null, "e": 4755, "s": 4727, "text": "ghazanferwahab26 months ago" }, { "code": null, "e": 4791, "s": 4755, "text": "can someone give solution in java??" }, { "code": null, "e": 4793, "s": 4791, "text": "0" }, { "code": null, "e": 4817, "s": 4793, "text": "rohit_iiitl7 months ago" }, { "code": null, "e": 4867, "s": 4819, "text": "dp[i] = min time required to complete ith task." }, { "code": null, "e": 5654, "s": 4869, "text": "Algorithm:Firstly assign dp[i] to duration[i], as it is min time required to perform that task. Now, lets say task B is dependent on A, then time reqd for B will be time of A + time of B (as A needs to be performed before B) (dp[B] = dp[A] + dp[B]). Now lets say B is also dependent on C, and C and A are independent. For this case dp[B] = dp[C] + dp[B], but this this will not solve our problem, as we are ignoring A. Therefore, dp[B] = max(dp[A] + dp[B], dp[C] + dp[B]), as if A takes more time than C, then we need to wait for A to complete before performing task B. i.e; calculating max of both. We are taking maximum of it, but actually dp[B] is minimum time required to complete task B (waiting for both A and C before doing B). Use kahn's algorithm to solve for all dependency." }, { "code": null, "e": 5938, "s": 5656, "text": "At last for every i, dp[i] will contain minimum time required to complete that particular task. Hence if we find max of this array. Then it will be minimum time required for whole process (to complete all tasks), as other tasks can run parallelly and complete before that max time." }, { "code": null, "e": 5982, "s": 5940, "text": "In solution denoting dp[ ] as timeReqd[ ]" }, { "code": null, "e": 6767, "s": 5984, "text": "int minTime(vector<pair<int, int>> &dependency, int duration[], int n, int m) {\n vector<int> indegree(n, 0), timeReqd(n, 0), adj[n];\n queue<int> q;\n for(int i=0; i<m; i++) {\n indegree[dependency[i].second]++;\n adj[dependency[i].first].push_back(dependency[i].second);\n }\n for(int i=0; i<n; i++) {\n if(indegree[i] == 0)\n q.push(i), timeReqd[i]=duration[i];\n }\n int numNodes=0;\n while(!q.empty()) {\n int front = q.front();\n q.pop();\n numNodes++;\n for(auto v:adj[front]) {\n timeReqd[v] = max(timeReqd[v], timeReqd[front]+duration[v]);\n if(--indegree[v] == 0) q.push(v);\n }\n }\n if(numNodes != n) return -1;\n return *max_element(timeReqd.begin(), timeReqd.end());\n}" }, { "code": null, "e": 6770, "s": 6767, "text": "+1" }, { "code": null, "e": 6791, "s": 6770, "text": "anutiger7 months ago" }, { "code": null, "e": 8575, "s": 6791, "text": " public:\n struct Node{\n int node;\n int val;\n int price;\n Node(int x,int y){\n node = x;\n val = y;\n price = 0;\n }\n }; \n int minTime(vector<pair<int, int>> &dep, int dur[], int n, int m) {\n vector<int> vis(n , 1);\n vector<int> adj[n];\n vector<int> cnt(n , 0);\n vector<Node*> tmp;\n for(int i = 0 ; i < n ; i ++){\n Node *temp = new Node(i,dur[i]);\n tmp.push_back(temp);\n }\n for(int i = 0 ; i < m ; i ++){\n int x = dep[i].first;\n int y = dep[i].second;\n adj[x].push_back(y);\n cnt[y]++;\n }\n queue<Node*>pq;\n while(true){\n if(pq.empty()){\n int flag = 1;\n for(int i = 0; i < n ; i ++){\n if(cnt[i] == 0){\n pq.push(tmp[i]);\n cnt[i] = -1;\n flag = 0;\n }\n }\n if(flag)\n break;\n }\n int size = pq.size();\n for(int i = 0; i < size; i ++){\n auto it = pq.front();pq.pop();\n int price = it->val + it->price;\n if(adj[it->node].size() == 0){\n tmp[it->node]->price += tmp[it->node]->val;\n continue;\n }\n for(int j : adj[it->node]){\n auto t = tmp[j];\n if(t->price < price){\n t->price = max(t->price,price);\n }\n cnt[j]--;\n }\n }\n }\n for(int i = 0; i < n ; i ++){\n if(cnt[i] > 0)\n return -1;\n }\n int res = 0;\n for(int i = 0 ; i < n ; i ++){\n res = max(res,tmp[i]->price);\n }\n if(res == 0) return -1;\n return res;\n }" }, { "code": null, "e": 8578, "s": 8575, "text": "+1" }, { "code": null, "e": 8602, "s": 8578, "text": "sunnysaraff7 months ago" }, { "code": null, "e": 9579, "s": 8602, "text": "int minTime(vector<pair<int, int>> &dependency, int duration[], int n, int m) {\n vector<int> adj[n],in(n),dist(n,INT_MIN);\n vector<bool> vis(n,false),rec(n,false);\n for(auto& edge:dependency){\n adj[edge.first].push_back(edge.second);\n in[edge.second]++;\n }\n \n queue<int> q;\n for(int i=0;i<n;i++){\n if(!in[i]){\n dist[i] = duration[i];\n q.push(i);\n }\n }\n \n int cnt = 0;\n while(!q.empty()){\n int v = q.front();\n q.pop();\n \n cnt++;\n \n for(auto& u:adj[v]){\n in[u]--;\n dist[u] = max(dist[u],dist[v]);\n if(!in[u]){\n dist[u] += duration[u];\n q.push(u);\n }\n }\n }\n \n return (cnt==n)?*max_element(dist.begin(),dist.end()):-1;\n \n }" }, { "code": null, "e": 9582, "s": 9579, "text": "+3" }, { "code": null, "e": 9605, "s": 9582, "text": "geminicode7 months ago" }, { "code": null, "e": 9671, "s": 9605, "text": "Hi can anyone explain why the answer of example-1 is 8 and not 9?" }, { "code": null, "e": 9675, "s": 9673, "text": "0" }, { "code": null, "e": 9697, "s": 9675, "text": "rishug7707 months ago" }, { "code": null, "e": 9770, "s": 9697, "text": "#Python Solution. Topological Sorting and a touch of dynamic programming" }, { "code": null, "e": 10429, "s": 9770, "text": "indeg=[0]*n ans=[] q=[] dp=[] adj=[] for i in range(n): adj.append([]) dp.append(duration[i]) for i in range(m): indeg[dependency[i][1]]+=1 adj[dependency[i][0]].append(dependency[i][1]) for i in range(n): if(indeg[i]==0): q.append(i) while(q): a=q.pop(0) ans.append(a) for i in adj[a]: dp[i]=max(dp[i],duration[i]+dp[a]) indeg[i]-=1 if(indeg[i]==0): q.append(i) if(len(ans)!=n): return -1 return max(dp)" }, { "code": null, "e": 10432, "s": 10429, "text": "+4" }, { "code": null, "e": 10456, "s": 10432, "text": "mastermind_7 months ago" }, { "code": null, "e": 10548, "s": 10456, "text": "(C++) Topological Sorting( Kahn's Algorithm ) + DP Solution, ~ Fastest ~ 0.0 s ~ O(M+N) " }, { "code": null, "e": 11113, "s": 10548, "text": "int minTime(vector<pair<int, int>> &d, int dur[], int n, int m) {\n\tvector<int> indeg(n, 0), topo, dp(n, 0), adj[n];\n\tqueue<int> q;\n\tfor(int i=0;i<m;i++)indeg[d[i].second]++,adj[d[i].first].push_back(d[i].second);\n\tfor (int i = 0; i < n; i++)if (indeg[i] == 0)q.push(i), dp[i] = dur[i];\n\twhile (!q.empty()) {\n\t\tauto x = q.front(); q.pop();\n\t\ttopo.push_back(x);\n\t\tfor (auto v : adj[x]) {\n\t\t\tdp[v] = max(dp[v], dur[v] + dp[x]);\n\t\t\tif (--indeg[v]==0)q.push(v);\n\t\t}\n\t}\n\tif (topo.size() != n)return -1; // contains cycle !!!\n\treturn *max_element(dp.begin(), dp.end());\n}" }, { "code": null, "e": 11259, "s": 11113, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 11295, "s": 11259, "text": " Login to access your submissions. " }, { "code": null, "e": 11305, "s": 11295, "text": "\nProblem\n" }, { "code": null, "e": 11315, "s": 11305, "text": "\nContest\n" }, { "code": null, "e": 11378, "s": 11315, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 11526, "s": 11378, "text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 11734, "s": 11526, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints." }, { "code": null, "e": 11840, "s": 11734, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
C++ Program for Bubble Sort - GeeksforGeeks
12 Feb, 2018 Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in wrong order. // Optimized implementation of Bubble sort#include <stdio.h> void swap(int *xp, int *yp){ int temp = *xp; *xp = *yp; *yp = temp;} // An optimized version of Bubble Sortvoid bubbleSort(int arr[], int n){ int i, j; bool swapped; for (i = 0; i < n-1; i++) { swapped = false; for (j = 0; j < n-i-1; j++) { if (arr[j] > arr[j+1]) { swap(&arr[j], &arr[j+1]); swapped = true; } } // IF no two elements were swapped by inner loop, then break if (swapped == false) break; }} /* Function to print an array */void printArray(int arr[], int size){ int i; for (i=0; i < size; i++) printf("%d ", arr[i]); printf("n");} // Driver program to test above functionsint main(){ int arr[] = {64, 34, 25, 12, 22, 11, 90}; int n = sizeof(arr)/sizeof(arr[0]); bubbleSort(arr, n); printf("Sorted array: \n"); printArray(arr, n); return 0;} Please refer complete article on Bubble Sort for more details! BubbleSort C++ Programs Sorting Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Passing a function as a parameter in C++ Program to implement Singly Linked List in C++ using class Const keyword in C++ cout in C++ Handling the Divide by Zero Exception in C++
[ { "code": null, "e": 24630, "s": 24602, "text": "\n12 Feb, 2018" }, { "code": null, "e": 24760, "s": 24630, "text": "Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in wrong order." }, { "code": "// Optimized implementation of Bubble sort#include <stdio.h> void swap(int *xp, int *yp){ int temp = *xp; *xp = *yp; *yp = temp;} // An optimized version of Bubble Sortvoid bubbleSort(int arr[], int n){ int i, j; bool swapped; for (i = 0; i < n-1; i++) { swapped = false; for (j = 0; j < n-i-1; j++) { if (arr[j] > arr[j+1]) { swap(&arr[j], &arr[j+1]); swapped = true; } } // IF no two elements were swapped by inner loop, then break if (swapped == false) break; }} /* Function to print an array */void printArray(int arr[], int size){ int i; for (i=0; i < size; i++) printf(\"%d \", arr[i]); printf(\"n\");} // Driver program to test above functionsint main(){ int arr[] = {64, 34, 25, 12, 22, 11, 90}; int n = sizeof(arr)/sizeof(arr[0]); bubbleSort(arr, n); printf(\"Sorted array: \\n\"); printArray(arr, n); return 0;}", "e": 25706, "s": 24760, "text": null }, { "code": null, "e": 25769, "s": 25706, "text": "Please refer complete article on Bubble Sort for more details!" }, { "code": null, "e": 25780, "s": 25769, "text": "BubbleSort" }, { "code": null, "e": 25793, "s": 25780, "text": "C++ Programs" }, { "code": null, "e": 25801, "s": 25793, "text": "Sorting" }, { "code": null, "e": 25809, "s": 25801, "text": "Sorting" }, { "code": null, "e": 25907, "s": 25809, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25916, "s": 25907, "text": "Comments" }, { "code": null, "e": 25929, "s": 25916, "text": "Old Comments" }, { "code": null, "e": 25970, "s": 25929, "text": "Passing a function as a parameter in C++" }, { "code": null, "e": 26029, "s": 25970, "text": "Program to implement Singly Linked List in C++ using class" }, { "code": null, "e": 26050, "s": 26029, "text": "Const keyword in C++" }, { "code": null, "e": 26062, "s": 26050, "text": "cout in C++" } ]
Modulus of two double numbers | Practice | GeeksforGeeks
Given two floating point numbers a and b, find a%b. Example 1: Input: a = 36.5, b = 5.0 Output: 1.5 Explanation: 36.5 % 5.0 = 1.5 Example 2: Input: a = 9.7, b = 2.3 Output: 0.5 Explanation: 9.7 % 2.3 = 0.5 Your Task: You don't need to read input or print anything. Your task is to complete the function floatMod() which takes 2 doubles a, and b as input and returns a%b. Expected Time Complexity: O(1) Expected Auxiliary Space: O(1) Constraints: 1 <= a,b<= 103 +1 badgujarsachin837 months ago +1 badgujarsachin837 months ago class Solution { public: double floatMod(double a, double b) { // code here return fmod(a,b); } }; 0 Fasil Shafi1 year ago Fasil Shafi class Solution { public: double floatMod(double a, double b) { return fmod(a,b); }}; 0 mawzir ।2 years ago mawzir । N=int(input())for i in range(N): n1=input() l1=n1.split() for i in range(len(l1)): l1[i]=float(l1[i]) print(round((l1[0]%l1[1]),2)) 0 Rony Hajong2 years ago Rony Hajong #include<bits stdc++.h="">using namespace std;int main(){ int t; double a,b; cin>>t; while (t--) { cin>>a>>b; long long int p=a*10000000000; long long int q=b*10000000000; long long int mod=p%q; double mod_m=mod/10000000000.0; cout<<mod_m<<endl; }="" return="" 0;="" }=""> 0 Hitesh Sandal4 years ago Hitesh Sandal https://ide.geeksforgeeks.o... here is the link to my code!for input 205.4 234.6its correct output is: 205.4, and my code's output is: 205.40 !and for some test case, correct output was 0.17 and my code's output was 0.170005! How to control number of digits after decimal point for every case!? 0 Tech Today4 years ago Tech Today def remainder(a,b): return round(a%b,2) test = int(input())for t in range(test): a,b = map(float,input().split()) print(remainder(a,b)) 0 Ratnesh Tiwari4 years ago Ratnesh Tiwari https://ide.geeksforgeeks.o...producing wrong output for Input:93.83 108.86 Its Correct output is:93.83And My Code's output is:93.8 We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 290, "s": 238, "text": "Given two floating point numbers a and b, find a%b." }, { "code": null, "e": 303, "s": 292, "text": "Example 1:" }, { "code": null, "e": 370, "s": 303, "text": "Input:\na = 36.5, b = 5.0\nOutput:\n1.5\nExplanation:\n36.5 % 5.0 = 1.5" }, { "code": null, "e": 381, "s": 370, "text": "Example 2:" }, { "code": null, "e": 446, "s": 381, "text": "Input:\na = 9.7, b = 2.3\nOutput:\n0.5\nExplanation:\n9.7 % 2.3 = 0.5" }, { "code": null, "e": 613, "s": 448, "text": "Your Task:\nYou don't need to read input or print anything. Your task is to complete the function floatMod() which takes 2 doubles a, and b as input and returns a%b." }, { "code": null, "e": 677, "s": 615, "text": "Expected Time Complexity: O(1)\nExpected Auxiliary Space: O(1)" }, { "code": null, "e": 707, "s": 679, "text": "Constraints:\n1 <= a,b<= 103" }, { "code": null, "e": 710, "s": 707, "text": "+1" }, { "code": null, "e": 739, "s": 710, "text": "badgujarsachin837 months ago" }, { "code": null, "e": 742, "s": 739, "text": "+1" }, { "code": null, "e": 771, "s": 742, "text": "badgujarsachin837 months ago" }, { "code": null, "e": 895, "s": 771, "text": "class Solution {\n public:\n double floatMod(double a, double b) {\n // code here\n return fmod(a,b);\n }\n};" }, { "code": null, "e": 897, "s": 895, "text": "0" }, { "code": null, "e": 919, "s": 897, "text": "Fasil Shafi1 year ago" }, { "code": null, "e": 931, "s": 919, "text": "Fasil Shafi" }, { "code": null, "e": 998, "s": 931, "text": "class Solution { public: double floatMod(double a, double b) {" }, { "code": null, "e": 1031, "s": 998, "text": " return fmod(a,b); }};" }, { "code": null, "e": 1033, "s": 1031, "text": "0" }, { "code": null, "e": 1053, "s": 1033, "text": "mawzir ।2 years ago" }, { "code": null, "e": 1062, "s": 1053, "text": "mawzir ।" }, { "code": null, "e": 1213, "s": 1062, "text": "N=int(input())for i in range(N): n1=input() l1=n1.split() for i in range(len(l1)): l1[i]=float(l1[i]) print(round((l1[0]%l1[1]),2))" }, { "code": null, "e": 1215, "s": 1213, "text": "0" }, { "code": null, "e": 1238, "s": 1215, "text": "Rony Hajong2 years ago" }, { "code": null, "e": 1250, "s": 1238, "text": "Rony Hajong" }, { "code": null, "e": 1333, "s": 1250, "text": "#include<bits stdc++.h=\"\">using namespace std;int main(){ int t; double a,b;" }, { "code": null, "e": 1459, "s": 1333, "text": " cin>>t; while (t--) { cin>>a>>b; long long int p=a*10000000000; long long int q=b*10000000000;" }, { "code": null, "e": 1529, "s": 1459, "text": " long long int mod=p%q; double mod_m=mod/10000000000.0;" }, { "code": null, "e": 1583, "s": 1529, "text": " cout<<mod_m<<endl; }=\"\" return=\"\" 0;=\"\" }=\"\">" }, { "code": null, "e": 1585, "s": 1583, "text": "0" }, { "code": null, "e": 1610, "s": 1585, "text": "Hitesh Sandal4 years ago" }, { "code": null, "e": 1624, "s": 1610, "text": "Hitesh Sandal" }, { "code": null, "e": 1851, "s": 1624, "text": "https://ide.geeksforgeeks.o... here is the link to my code!for input 205.4 234.6its correct output is: 205.4, and my code's output is: 205.40 !and for some test case, correct output was 0.17 and my code's output was 0.170005!" }, { "code": null, "e": 1920, "s": 1851, "text": "How to control number of digits after decimal point for every case!?" }, { "code": null, "e": 1922, "s": 1920, "text": "0" }, { "code": null, "e": 1944, "s": 1922, "text": "Tech Today4 years ago" }, { "code": null, "e": 1955, "s": 1944, "text": "Tech Today" }, { "code": null, "e": 1998, "s": 1955, "text": "def remainder(a,b): return round(a%b,2)" }, { "code": null, "e": 2100, "s": 1998, "text": "test = int(input())for t in range(test): a,b = map(float,input().split()) print(remainder(a,b))" }, { "code": null, "e": 2102, "s": 2100, "text": "0" }, { "code": null, "e": 2128, "s": 2102, "text": "Ratnesh Tiwari4 years ago" }, { "code": null, "e": 2143, "s": 2128, "text": "Ratnesh Tiwari" }, { "code": null, "e": 2200, "s": 2143, "text": "https://ide.geeksforgeeks.o...producing wrong output for" }, { "code": null, "e": 2219, "s": 2200, "text": "Input:93.83 108.86" }, { "code": null, "e": 2275, "s": 2219, "text": "Its Correct output is:93.83And My Code's output is:93.8" }, { "code": null, "e": 2421, "s": 2275, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 2457, "s": 2421, "text": " Login to access your submissions. " }, { "code": null, "e": 2467, "s": 2457, "text": "\nProblem\n" }, { "code": null, "e": 2477, "s": 2467, "text": "\nContest\n" }, { "code": null, "e": 2540, "s": 2477, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 2688, "s": 2540, "text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 2896, "s": 2688, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints." }, { "code": null, "e": 3002, "s": 2896, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
How to pass check boxes data using JSP?
Checkboxes are used when more than one option is required to be selected. Following is an example HTML code, CheckBox.htm, for a form with two checkboxes. <html> <body> <form action = "main.jsp" method = "POST" target = "_blank"> <input type = "checkbox" name = "maths" checked = "checked" /> Maths <input type = "checkbox" name = "physics" /> Physics <input type = "checkbox" name = "chemistry" checked = "checked" /> Chemistry <input type = "submit" value = "Select Subject" /> </form> </body> </html> The above code will generate the following result − Following is main.jsp JSP program to handle the input given by the web browser for the checkbox button. <html> <head> <title>Reading Checkbox Data</title> </head> <body> <h1>Reading Checkbox Data</h1> <ul> <li><p><b>Maths Flag:</b> <%= request.getParameter("maths")%> </p></li> <li><p><b>Physics Flag:</b> <%= request.getParameter("physics")%> </p></li> <li><p><b>Chemistry Flag:</b> <%= request.getParameter("chemistry")%> </p></li> </ul> </body> </html> The above program will generate the following result − Maths Flag :: on Maths Flag :: on Physics Flag:: null Physics Flag:: null Chemistry Flag:: on Chemistry Flag:: on
[ { "code": null, "e": 1136, "s": 1062, "text": "Checkboxes are used when more than one option is required to be selected." }, { "code": null, "e": 1217, "s": 1136, "text": "Following is an example HTML code, CheckBox.htm, for a form with two checkboxes." }, { "code": null, "e": 1620, "s": 1217, "text": "<html>\n <body>\n <form action = \"main.jsp\" method = \"POST\" target = \"_blank\">\n <input type = \"checkbox\" name = \"maths\" checked = \"checked\" /> Maths\n <input type = \"checkbox\" name = \"physics\" /> Physics\n <input type = \"checkbox\" name = \"chemistry\" checked = \"checked\" /> Chemistry\n <input type = \"submit\" value = \"Select Subject\" />\n </form>\n </body>\n</html>" }, { "code": null, "e": 1672, "s": 1620, "text": "The above code will generate the following result −" }, { "code": null, "e": 1776, "s": 1672, "text": "Following is main.jsp JSP program to handle the input given by the web browser for the checkbox button." }, { "code": null, "e": 2263, "s": 1776, "text": "<html>\n <head>\n <title>Reading Checkbox Data</title>\n </head>\n <body>\n <h1>Reading Checkbox Data</h1>\n <ul>\n <li><p><b>Maths Flag:</b>\n <%= request.getParameter(\"maths\")%>\n </p></li>\n <li><p><b>Physics Flag:</b>\n <%= request.getParameter(\"physics\")%>\n </p></li>\n <li><p><b>Chemistry Flag:</b>\n <%= request.getParameter(\"chemistry\")%>\n </p></li>\n </ul>\n </body>\n</html>" }, { "code": null, "e": 2318, "s": 2263, "text": "The above program will generate the following result −" }, { "code": null, "e": 2335, "s": 2318, "text": "Maths Flag :: on" }, { "code": null, "e": 2352, "s": 2335, "text": "Maths Flag :: on" }, { "code": null, "e": 2372, "s": 2352, "text": "Physics Flag:: null" }, { "code": null, "e": 2392, "s": 2372, "text": "Physics Flag:: null" }, { "code": null, "e": 2412, "s": 2392, "text": "Chemistry Flag:: on" }, { "code": null, "e": 2432, "s": 2412, "text": "Chemistry Flag:: on" } ]
How to select only one column from an R data frame and return it as a data frame instead of vector?
Generally, if we extract a single column from an R data frame then it is extracted as a vector but we might want it in data frame form so that we can apply operations of a data frame on it. Therefore, we can use single square brackets for the extraction with T (TRUE) or (FALSE) values and drop = FALSE so that the output becomes a data frame. Consider the below data frame − Live Demo set.seed(999) x1<-rnorm(20,5,1) x2<-rnorm(20,5,2) x3<-rnorm(20,10,2) x4<-rnorm(20,10,1.5) x5<-rnorm(20,10,4) df1<-data.frame(x1,x2,x3,x4,x5) df1 x1 x2 x3 x4 x5 1 4.718260 2.542873 9.028727 8.615033 7.428309 2 3.687440 6.286089 10.016996 11.747431 13.941194 3 5.795184 4.280474 7.435773 11.563103 5.085707 4 5.270070 5.588071 7.776842 11.655743 10.340899 5 4.722694 2.749463 10.601331 9.972138 5.183625 6 4.433976 6.284531 10.552958 8.279563 8.492609 7 3.121342 2.786525 5.898245 7.887731 15.454594 8 3.733209 3.230319 10.028380 9.576507 8.988469 9 4.032250 1.891810 11.164533 9.373345 14.025960 10 3.878991 4.746642 9.930547 11.494995 11.748597 11 6.325464 9.765328 9.766672 9.840571 16.634154 12 5.133977 6.202552 8.710036 9.895897 10.110741 13 5.938749 5.358723 13.488823 11.424552 6.085122 14 5.172538 7.161063 10.732189 9.375201 15.134917 15 5.957650 4.506376 9.866380 11.461001 5.481034 16 3.637314 0.772526 10.565225 10.093437 14.186631 17 5.068335 4.258945 11.135390 10.807633 7.688271 18 5.100658 6.045736 7.441568 6.902765 8.824823 19 5.901345 6.035611 10.870738 10.654647 9.032894 20 2.925643 2.194978 8.868998 9.759660 10.879791 Extracting column x1 − df1[,c(T,F,F,F,F)] [1] 4.718260 3.687440 5.795184 5.270070 4.722694 4.433976 3.121342 3.733209 [9] 4.032250 3.878991 6.325464 5.133977 5.938749 5.172538 5.957650 3.637314 [17] 5.068335 5.100658 5.901345 2.925643 is.vector(df1[,c(T,F,F,F,F)]) [1] TRUE Extracting column x1 as a data frame − df1[,c(T,F,F,F,F),drop=FALSE] x1 1 4.718260 2 3.687440 3 5.795184 4 5.270070 5 4.722694 6 4.433976 7 3.121342 8 3.733209 9 4.032250 10 3.878991 11 6.325464 12 5.133977 13 5.938749 14 5.172538 15 5.957650 16 3.637314 17 5.068335 18 5.100658 19 5.901345 20 2.925643 Extracting different columns in the same way − df1[,c(F,T,F,F,F),drop=FALSE] x2 1 2.542873 2 6.286089 3 4.280474 4 5.588071 5 2.749463 6 6.284531 7 2.786525 8 3.230319 9 1.891810 10 4.746642 11 9.765328 12 6.202552 13 5.358723 14 7.161063 15 4.506376 16 0.772526 17 4.258945 18 6.045736 19 6.035611 20 2.194978 df1[,c(F,F,T,F,F),drop=FALSE] x3 1 9.028727 2 10.016996 3 7.435773 4 7.776842 5 10.601331 6 10.552958 7 5.898245 8 10.028380 9 11.164533 10 9.930547 11 9.766672 12 8.710036 13 13.488823 14 10.732189 15 9.866380 16 10.565225 17 11.135390 18 7.441568 19 10.870738 20 8.868998 df1[,c(F,F,F,F,T),drop=FALSE] x5 1 7.428309 2 13.941194 3 5.085707 4 10.340899 5 5.183625 6 8.492609 7 15.454594 8 8.988469 9 14.025960 10 11.748597 11 16.634154 12 10.110741 13 6.085122 14 15.134917 15 5.481034 16 14.186631 17 7.688271 18 8.824823 19 9.032894 20 10.879791
[ { "code": null, "e": 1406, "s": 1062, "text": "Generally, if we extract a single column from an R data frame then it is extracted as a vector but we might want it in data frame form so that we can apply operations of a data frame on it. Therefore, we can use single square brackets for the extraction with T (TRUE) or (FALSE) values and drop = FALSE so that the output becomes a data frame." }, { "code": null, "e": 1438, "s": 1406, "text": "Consider the below data frame −" }, { "code": null, "e": 1449, "s": 1438, "text": " Live Demo" }, { "code": null, "e": 1594, "s": 1449, "text": "set.seed(999)\nx1<-rnorm(20,5,1)\nx2<-rnorm(20,5,2)\nx3<-rnorm(20,10,2)\nx4<-rnorm(20,10,1.5)\nx5<-rnorm(20,10,4)\ndf1<-data.frame(x1,x2,x3,x4,x5)\ndf1" }, { "code": null, "e": 2617, "s": 1594, "text": " x1 x2 x3 x4 x5\n1 4.718260 2.542873 9.028727 8.615033 7.428309\n2 3.687440 6.286089 10.016996 11.747431 13.941194\n3 5.795184 4.280474 7.435773 11.563103 5.085707\n4 5.270070 5.588071 7.776842 11.655743 10.340899\n5 4.722694 2.749463 10.601331 9.972138 5.183625\n6 4.433976 6.284531 10.552958 8.279563 8.492609\n7 3.121342 2.786525 5.898245 7.887731 15.454594\n8 3.733209 3.230319 10.028380 9.576507 8.988469\n9 4.032250 1.891810 11.164533 9.373345 14.025960\n10 3.878991 4.746642 9.930547 11.494995 11.748597\n11 6.325464 9.765328 9.766672 9.840571 16.634154\n12 5.133977 6.202552 8.710036 9.895897 10.110741\n13 5.938749 5.358723 13.488823 11.424552 6.085122\n14 5.172538 7.161063 10.732189 9.375201 15.134917\n15 5.957650 4.506376 9.866380 11.461001 5.481034\n16 3.637314 0.772526 10.565225 10.093437 14.186631\n17 5.068335 4.258945 11.135390 10.807633 7.688271\n18 5.100658 6.045736 7.441568 6.902765 8.824823\n19 5.901345 6.035611 10.870738 10.654647 9.032894\n20 2.925643 2.194978 8.868998 9.759660 10.879791" }, { "code": null, "e": 2640, "s": 2617, "text": "Extracting column x1 −" }, { "code": null, "e": 2659, "s": 2640, "text": "df1[,c(T,F,F,F,F)]" }, { "code": null, "e": 2852, "s": 2659, "text": "[1] 4.718260 3.687440 5.795184 5.270070 4.722694 4.433976 3.121342 3.733209\n[9] 4.032250 3.878991 6.325464 5.133977 5.938749 5.172538 5.957650 3.637314\n[17] 5.068335 5.100658 5.901345 2.925643" }, { "code": null, "e": 2891, "s": 2852, "text": "is.vector(df1[,c(T,F,F,F,F)]) [1] TRUE" }, { "code": null, "e": 2930, "s": 2891, "text": "Extracting column x1 as a data frame −" }, { "code": null, "e": 2960, "s": 2930, "text": "df1[,c(T,F,F,F,F),drop=FALSE]" }, { "code": null, "e": 3194, "s": 2960, "text": "x1\n1 4.718260\n2 3.687440\n3 5.795184\n4 5.270070\n5 4.722694\n6 4.433976\n7 3.121342\n8 3.733209\n9 4.032250\n10 3.878991\n11 6.325464\n12 5.133977\n13 5.938749\n14 5.172538\n15 5.957650\n16 3.637314\n17 5.068335\n18 5.100658\n19 5.901345\n20 2.925643" }, { "code": null, "e": 3241, "s": 3194, "text": "Extracting different columns in the same way −" }, { "code": null, "e": 3271, "s": 3241, "text": "df1[,c(F,T,F,F,F),drop=FALSE]" }, { "code": null, "e": 3507, "s": 3271, "text": " x2\n1 2.542873\n2 6.286089\n3 4.280474\n4 5.588071\n5 2.749463\n6 6.284531\n7 2.786525\n8 3.230319\n9 1.891810\n10 4.746642\n11 9.765328\n12 6.202552\n13 5.358723\n14 7.161063\n15 4.506376\n16 0.772526\n17 4.258945\n18 6.045736\n19 6.035611\n20 2.194978" }, { "code": null, "e": 3537, "s": 3507, "text": "df1[,c(F,F,T,F,F),drop=FALSE]" }, { "code": null, "e": 3781, "s": 3537, "text": "x3\n1 9.028727\n2 10.016996\n3 7.435773\n4 7.776842\n5 10.601331\n6 10.552958\n7 5.898245\n8 10.028380\n9 11.164533\n10 9.930547\n11 9.766672\n12 8.710036\n13 13.488823\n14 10.732189\n15 9.866380\n16 10.565225\n17 11.135390\n18 7.441568\n19 10.870738\n20 8.868998" }, { "code": null, "e": 3811, "s": 3781, "text": "df1[,c(F,F,F,F,T),drop=FALSE]" }, { "code": null, "e": 4055, "s": 3811, "text": "x5\n1 7.428309\n2 13.941194\n3 5.085707\n4 10.340899\n5 5.183625\n6 8.492609\n7 15.454594\n8 8.988469\n9 14.025960\n10 11.748597\n11 16.634154\n12 10.110741\n13 6.085122\n14 15.134917\n15 5.481034\n16 14.186631\n17 7.688271\n18 8.824823\n19 9.032894\n20 10.879791" } ]
What is crypto data?. A practical guide for data science... | by Yifei Huang | Towards Data Science
In my last post, I argued that with an increasing number of consumer crypto applications gaining traction, the growing trove of publicly available crypto data will fundamentally change how the next generation of products compete and operate. Effectively leveraging the data asset will be crucial to realizing this future, and data science will play a key role. In this post, I want to provide more background on crypto data — what they represent in the context of crypto applications, what they look like and how to work with them [1]. If you haven’t read my last post, please consider doing so, as it will provide useful context for this post. Before diving into the data, it is useful to contextualize what a decentralized crypto (sometimes referred to as web 3.0) application looks like and how it differs from a web 2.0 application. In a traditional web 2.0 application, users interact with the application frontend via a browser. The frontend translates user requests into queries to the backend APIs. The backend performs the necessary computation to fulfill the requests and persist the relevant data to storage. In a web 3.0 application, the frontend more or less works in the same way, with the added requirement of a software wallet that helps uniquely identify the user to the blockchain network. The backend servers, however, are replaced by a decentralized blockchain network that functions like a distributed virtual machine. Smart contracts, written in high level languages like Solidity, live on this virtual machine and serve as the backend APIs. With the help of a node on the blockchain network (typically accessed through a node-as-a-service provider), the frontend broadcasts the user requests in the form of transactions to these smart contracts, which executes the invoked logic on the virtual machine. Upon completion, the transaction details and state changes are persisted in the blockchain ledger in a cryptographically verifiable manner. In an admittedly simplified view, one can think of the blockchain virtual machine as the backend server, smart contracts as the backend APIs, and the blockchain ledger as the storage [2]. However, there are two key differences in Web 3.0 architecture that are worth emphasizing Unlike traditional backend APIs, smart contracts are decentralized and publicly accessible. Anyone on the network can see the code, and build new smart contracts or frontends on top of them. No one entity controls access to the smart contracts like the way Facebook does with its APIs. This is sometimes referred to as the composability of smart contracts.Every single backend API call (i.e. transaction) is published on the blockchain ledger in a way that is verifiable and effectively immutable. Each transaction record contains detailed metadata on the specific request and the resulting state changes. This level of transparency represents a paradigm shift from web 2.0 applications, and is what makes crypto data such a compelling opportunity. Unlike traditional backend APIs, smart contracts are decentralized and publicly accessible. Anyone on the network can see the code, and build new smart contracts or frontends on top of them. No one entity controls access to the smart contracts like the way Facebook does with its APIs. This is sometimes referred to as the composability of smart contracts. Every single backend API call (i.e. transaction) is published on the blockchain ledger in a way that is verifiable and effectively immutable. Each transaction record contains detailed metadata on the specific request and the resulting state changes. This level of transparency represents a paradigm shift from web 2.0 applications, and is what makes crypto data such a compelling opportunity. Transactions are central to how crypto applications function and the data that is created, therefore it is important to precisely define how they work. In the broader context of blockchain networks, transactions are atomic units of activity that change the state of the blockchain virtual machine. There are 3 distinct types of transactions: Transfer of value in the form of the base currency by one externally owned accounts (EOA) to another, e.g. Emily sends Bob 3 ETH on the Ethereum networkCreation of a smart contract by an EOA, e.g. Emily commits code to an address on the blockchain, creating a smart contract that enable users to exchange of ETH with BTCCall to a smart contract by an EOA, e.g. Bob calls Emily’s smart contract to exchange 15 ETH for 1 BTC Transfer of value in the form of the base currency by one externally owned accounts (EOA) to another, e.g. Emily sends Bob 3 ETH on the Ethereum network Creation of a smart contract by an EOA, e.g. Emily commits code to an address on the blockchain, creating a smart contract that enable users to exchange of ETH with BTC Call to a smart contract by an EOA, e.g. Bob calls Emily’s smart contract to exchange 15 ETH for 1 BTC All transactions must be initiated by an externally owned account (EOA), which is a unique blockchain address, controlled by a private key. This typically represents a human user, but can also sometimes be a bot. Smart contracts, once created, are also just accounts with a unique blockchain address. The only difference between a smart contract account and an EOA is that smart contract accounts are controlled by the contract code, rather than a private key. One notable feature of transactions is that they require payments to the network (or miner nodes to be more precise) called gas fees. A useful analogy for gas on a blockchain network is actual gasoline. Just as gasoline is needed to power vehicles, gas is required to run code on a blockchain network. Gasoline quantity is measured in volume metrics like liters, and price per unit is measured in fiat currency like dollars. Ethereum gas is measured in quantity units called gas, and price per unit is measured in wei, which is 1/10^18th of an Ethereum. When initiating a transaction, the EOA must specify the amount of gas it is willing to pay to the network for executing the transaction. If the specified amount is insufficient, then the transaction will fail and all staged state changes are reverted. This serves two primary functions Incentivize miner nodes to participate and run code on the network. The gas prices fluctuate based on supply and demand of computational capacity, similar to the concept of surge pricing in ride sharingDis-incentivize bad actors who may want to spam the network Incentivize miner nodes to participate and run code on the network. The gas prices fluctuate based on supply and demand of computational capacity, similar to the concept of surge pricing in ride sharing Dis-incentivize bad actors who may want to spam the network When user makes a request in a crypto application, what happens underneath the hood is: The EOA associated with the user initiates a transaction that specifies the target smart contract address, the target function, the arguments for that function, the transaction payment (if any), and the gas fee that it is willing to payThe transaction is broadcast to the network and picked up by a willing miner who executes the specified function in the target smart contractIf execution is successful, the smart contract emits events that mark the completion of certain milestones. The resulting event data structure is called logs.The target smart contract may initiate internal transactions (additional calls) to other smart contracts. These internal transactions create data structures called traces, and may also emit additional log events during their respective executions. The EOA associated with the user initiates a transaction that specifies the target smart contract address, the target function, the arguments for that function, the transaction payment (if any), and the gas fee that it is willing to pay The transaction is broadcast to the network and picked up by a willing miner who executes the specified function in the target smart contract If execution is successful, the smart contract emits events that mark the completion of certain milestones. The resulting event data structure is called logs. The target smart contract may initiate internal transactions (additional calls) to other smart contracts. These internal transactions create data structures called traces, and may also emit additional log events during their respective executions. To make this more concrete, let us take a closer look at an example of a transaction to purchase a Bored Ape NFT on the Opensea exchange smart contract In this transaction: The buyer EOA initiates the transaction with a call to the atomicMatch_ function in the Opensea Exchange smart contractThe exchange contract verifies that the order bid matches the ask of the sellers, then emits the OrderMatched event signifying that the order is confirmedThe exchange contract initiates an internal transaction to the Bored Ape NFT contract to transfer the NFT from the seller to the buyer, which in turn emits an Approval and a Transfer event upon completionThe exchange contract then initiates another internal transaction to transfer the funds, paid by the buyer EOA when initiating the original transaction, to the seller EOA The buyer EOA initiates the transaction with a call to the atomicMatch_ function in the Opensea Exchange smart contract The exchange contract verifies that the order bid matches the ask of the sellers, then emits the OrderMatched event signifying that the order is confirmed The exchange contract initiates an internal transaction to the Bored Ape NFT contract to transfer the NFT from the seller to the buyer, which in turn emits an Approval and a Transfer event upon completion The exchange contract then initiates another internal transaction to transfer the funds, paid by the buyer EOA when initiating the original transaction, to the seller EOA At the completion of this sequence, the transaction, traces from internal transactions, and logs from events are all persisted to the blockchain ledger. As this example hopefully made clear, the data exhaust from transactions provide very granular details about the inner workings of the crypto applications and the economic activity they facilitate. Now that we understand the data elements that are created by the crypto applications, and what they represent in reality, let us take a look at what this data looks like. The transaction and trace data structures contain details of the smart contract function call, in particular hash: unique id of the transaction from_address: the initiating EOA address to_address: the target smart contract address input: hexadecimal encoded representation of the target function and arguments for that function value: the transaction value or payment Example transaction hash: 0xfdf4e500eeefa5b12d773fb74d55c4bbfc92a4297cddc8f85b937978a3fc6477nonce: 232transaction_index: 19from_address: 0xfc7396fc573e916dc0d7203b0f087ffc46882c17to_address: 0x7be8076f4ea4a4ad08075c2508e481d6c946d12bvalue: 0E-9gas: 74902gas_price: 52545827339input: 0xa8a41c700000000000000000000000007be8076f4ea4a4ad08075c2508e481d6c946d12b000000000000000000000000fc7396fc573e916dc0d7203b0f087ffc46882c170...receipt_cumulative_gas_used: 1242267receipt_gas_used: 74902receipt_contract_address: Nonereceipt_root: Nonereceipt_status: 1block_timestamp: 2021–08–10 04:18:55block_number: 12995203block_hash: 0x7ca2ff7158d7a40997a5230e39f8d96ad17cf59ced6b27a3288653f9c94ce7a3max_fee_per_gas: Nonemax_priority_fee_per_gas: Nonetransaction_type: Nonereceipt_effective_gas_price: 52545827339 The log data structure contains details of the events that were emitted during the execution of the smart contract function, in particular transaction_hash: ID of the transaction that the event was a part of address: address of the smart contract that emitted the event topics: the function that emitted the event data: event metadata Example log log_index: 260transaction_hash: 0x2ac3648d5a0a7c1dd58685fabb5c5602add36f1555b1001cb900ea0410ab23dbtransaction_index: 131address: 0xff64cb7ba5717a10dabc4be3a41acd2c2f95ee22data: 0x000000000000000000000000000000000000000000054e0ee097e3dbdbde51b2000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000011d65da6b52d881ddtopics: [‘0xd78ad95fa46c994b6551d0da85fc275fe613ce37657fb8d5e3d130840159d822’,‘0x00000000000000000000000003f7724180aa6b939894b5ca4314783b0b36b329’,‘0x000000000000000000000000e83df6e24de6d5d263f78ad281143f184a6c95eb’]block_timestamp: 2021–08–04 06:40:42block_number: 12957113block_hash: 0x3ea06d9b495dffb2804a5f62ee0182949afac9f82d6ba922567fa3a95efc3d86 The astute reader will notice that many fields that are long hexadecimals that are not human friendly. In order to parse out the encoded information, we need to decode these using something called application binary interface. I will discuss this in more detail in the next post. Now that we have a good understanding of what crypto data represents and what it looks like, how do we actually access and work with it? Luckily there is an array of great tools to help us with just that. Block explorers Block explorers are great resources for examining individual transaction details on a given blockchain. The builders of block explorers have extracted and indexed the entire blockchain ledger, and created fast web interfaces to help users easily look up any transaction. See the screenshot below for an example. All major blockchains have explorers — prominent examples include Etherscan, Polygonscan, BSCScan, Solana beach While block explorers are great for interrogating individual records within the blockchain ledger, they are not great for answering questions that require aggregation or transformation of the data. For example if you wanted to know how many NFTs were sold through the Opensea exchange in the last 3 months, it would be very difficult to answer that with just block explorers. For that you will need direct access to the data. Getting the data One way to directly access the data is to query the blockchain yourself. There are various open source utility packages that are available in Python and Javascript to help make this process easier. For example For the Ethereum blockchains, and EVM compatible chains like Polygon and BSC, you can use the Web3 package. For Solana, you can use the Solana Py With these utility libraries, you will be able to programmatically interact with the blockchain of interest, to query for data, submit transactions, and even deploy smart contracts. There are also open source projects that have packaged the above building blocks together into full ETL pipelines to help you download all the granular data into your own environment. Furthermore, the owners of these projects have also published many of the raw datasets into public datasets on Google cloud, which offers a relatively easy-to-use SQL interface to query the data. Last, but not least, Dune analytics is another great resource for accessing and analyzing blockchain data. It has both raw and decoded data for Ethereum, Polygon, Optimism and BSC as of the writing of this post. This is a very differentiated offering compared to the public dataset on Google, because the decoding makes the hexadecimal encoded data fields human readable. It offers a Postgres interface for querying the datasets and a simple point and click interface for creating simple dashboards on top of the query results. The community of users on Dune is also quite active and has generated an extensive library of example queries and dashboards to learn from. Here are a couple of examples analysis that I have created on Dune Opensea transactions and user deep dive Decentralized exchanges transaction and user deep dive Crypto data is the exhaust from the web 3.0 application architecture It contains full history of all the “backend API calls” in a crypto application, in the form of transactions, logs and traces These data structures contain granular details of the user request and application state changes There are a variety of freely available tools to help us access and analyze this treasure trove of data Hopefully this was a useful discussion and I have helped you gain better intuition about what crypto data is, what it looks like and how to work with it. In my next post, I will provide a tutorial on how to decode crypto data and make them more human readable, as a precursor to deeper investigations of popular crypto applications like Opensea and Uniswap. Be sure to hit the email icon to subscribe if you would like to be notified when that posts. Thank you for reading and feel free to reach out if you have questions or comments. Twitter | Linkedin [1] This discussion will be using the Ethereum blockchain as the primary reference architecture. Specifics may vary for other blockchains like Solana, but many of the concepts will generally. [2] This is a simplified illustration of a web 3.0 application that glosses over some implementation details. For a more thorough review, the user is encouraged to study this excellent deep dive.
[ { "code": null, "e": 816, "s": 171, "text": "In my last post, I argued that with an increasing number of consumer crypto applications gaining traction, the growing trove of publicly available crypto data will fundamentally change how the next generation of products compete and operate. Effectively leveraging the data asset will be crucial to realizing this future, and data science will play a key role. In this post, I want to provide more background on crypto data — what they represent in the context of crypto applications, what they look like and how to work with them [1]. If you haven’t read my last post, please consider doing so, as it will provide useful context for this post." }, { "code": null, "e": 1291, "s": 816, "text": "Before diving into the data, it is useful to contextualize what a decentralized crypto (sometimes referred to as web 3.0) application looks like and how it differs from a web 2.0 application. In a traditional web 2.0 application, users interact with the application frontend via a browser. The frontend translates user requests into queries to the backend APIs. The backend performs the necessary computation to fulfill the requests and persist the relevant data to storage." }, { "code": null, "e": 2137, "s": 1291, "text": "In a web 3.0 application, the frontend more or less works in the same way, with the added requirement of a software wallet that helps uniquely identify the user to the blockchain network. The backend servers, however, are replaced by a decentralized blockchain network that functions like a distributed virtual machine. Smart contracts, written in high level languages like Solidity, live on this virtual machine and serve as the backend APIs. With the help of a node on the blockchain network (typically accessed through a node-as-a-service provider), the frontend broadcasts the user requests in the form of transactions to these smart contracts, which executes the invoked logic on the virtual machine. Upon completion, the transaction details and state changes are persisted in the blockchain ledger in a cryptographically verifiable manner." }, { "code": null, "e": 2415, "s": 2137, "text": "In an admittedly simplified view, one can think of the blockchain virtual machine as the backend server, smart contracts as the backend APIs, and the blockchain ledger as the storage [2]. However, there are two key differences in Web 3.0 architecture that are worth emphasizing" }, { "code": null, "e": 3164, "s": 2415, "text": "Unlike traditional backend APIs, smart contracts are decentralized and publicly accessible. Anyone on the network can see the code, and build new smart contracts or frontends on top of them. No one entity controls access to the smart contracts like the way Facebook does with its APIs. This is sometimes referred to as the composability of smart contracts.Every single backend API call (i.e. transaction) is published on the blockchain ledger in a way that is verifiable and effectively immutable. Each transaction record contains detailed metadata on the specific request and the resulting state changes. This level of transparency represents a paradigm shift from web 2.0 applications, and is what makes crypto data such a compelling opportunity." }, { "code": null, "e": 3521, "s": 3164, "text": "Unlike traditional backend APIs, smart contracts are decentralized and publicly accessible. Anyone on the network can see the code, and build new smart contracts or frontends on top of them. No one entity controls access to the smart contracts like the way Facebook does with its APIs. This is sometimes referred to as the composability of smart contracts." }, { "code": null, "e": 3914, "s": 3521, "text": "Every single backend API call (i.e. transaction) is published on the blockchain ledger in a way that is verifiable and effectively immutable. Each transaction record contains detailed metadata on the specific request and the resulting state changes. This level of transparency represents a paradigm shift from web 2.0 applications, and is what makes crypto data such a compelling opportunity." }, { "code": null, "e": 4256, "s": 3914, "text": "Transactions are central to how crypto applications function and the data that is created, therefore it is important to precisely define how they work. In the broader context of blockchain networks, transactions are atomic units of activity that change the state of the blockchain virtual machine. There are 3 distinct types of transactions:" }, { "code": null, "e": 4679, "s": 4256, "text": "Transfer of value in the form of the base currency by one externally owned accounts (EOA) to another, e.g. Emily sends Bob 3 ETH on the Ethereum networkCreation of a smart contract by an EOA, e.g. Emily commits code to an address on the blockchain, creating a smart contract that enable users to exchange of ETH with BTCCall to a smart contract by an EOA, e.g. Bob calls Emily’s smart contract to exchange 15 ETH for 1 BTC" }, { "code": null, "e": 4832, "s": 4679, "text": "Transfer of value in the form of the base currency by one externally owned accounts (EOA) to another, e.g. Emily sends Bob 3 ETH on the Ethereum network" }, { "code": null, "e": 5001, "s": 4832, "text": "Creation of a smart contract by an EOA, e.g. Emily commits code to an address on the blockchain, creating a smart contract that enable users to exchange of ETH with BTC" }, { "code": null, "e": 5104, "s": 5001, "text": "Call to a smart contract by an EOA, e.g. Bob calls Emily’s smart contract to exchange 15 ETH for 1 BTC" }, { "code": null, "e": 5565, "s": 5104, "text": "All transactions must be initiated by an externally owned account (EOA), which is a unique blockchain address, controlled by a private key. This typically represents a human user, but can also sometimes be a bot. Smart contracts, once created, are also just accounts with a unique blockchain address. The only difference between a smart contract account and an EOA is that smart contract accounts are controlled by the contract code, rather than a private key." }, { "code": null, "e": 6405, "s": 5565, "text": "One notable feature of transactions is that they require payments to the network (or miner nodes to be more precise) called gas fees. A useful analogy for gas on a blockchain network is actual gasoline. Just as gasoline is needed to power vehicles, gas is required to run code on a blockchain network. Gasoline quantity is measured in volume metrics like liters, and price per unit is measured in fiat currency like dollars. Ethereum gas is measured in quantity units called gas, and price per unit is measured in wei, which is 1/10^18th of an Ethereum. When initiating a transaction, the EOA must specify the amount of gas it is willing to pay to the network for executing the transaction. If the specified amount is insufficient, then the transaction will fail and all staged state changes are reverted. This serves two primary functions" }, { "code": null, "e": 6667, "s": 6405, "text": "Incentivize miner nodes to participate and run code on the network. The gas prices fluctuate based on supply and demand of computational capacity, similar to the concept of surge pricing in ride sharingDis-incentivize bad actors who may want to spam the network" }, { "code": null, "e": 6870, "s": 6667, "text": "Incentivize miner nodes to participate and run code on the network. The gas prices fluctuate based on supply and demand of computational capacity, similar to the concept of surge pricing in ride sharing" }, { "code": null, "e": 6930, "s": 6870, "text": "Dis-incentivize bad actors who may want to spam the network" }, { "code": null, "e": 7018, "s": 6930, "text": "When user makes a request in a crypto application, what happens underneath the hood is:" }, { "code": null, "e": 7801, "s": 7018, "text": "The EOA associated with the user initiates a transaction that specifies the target smart contract address, the target function, the arguments for that function, the transaction payment (if any), and the gas fee that it is willing to payThe transaction is broadcast to the network and picked up by a willing miner who executes the specified function in the target smart contractIf execution is successful, the smart contract emits events that mark the completion of certain milestones. The resulting event data structure is called logs.The target smart contract may initiate internal transactions (additional calls) to other smart contracts. These internal transactions create data structures called traces, and may also emit additional log events during their respective executions." }, { "code": null, "e": 8038, "s": 7801, "text": "The EOA associated with the user initiates a transaction that specifies the target smart contract address, the target function, the arguments for that function, the transaction payment (if any), and the gas fee that it is willing to pay" }, { "code": null, "e": 8180, "s": 8038, "text": "The transaction is broadcast to the network and picked up by a willing miner who executes the specified function in the target smart contract" }, { "code": null, "e": 8339, "s": 8180, "text": "If execution is successful, the smart contract emits events that mark the completion of certain milestones. The resulting event data structure is called logs." }, { "code": null, "e": 8587, "s": 8339, "text": "The target smart contract may initiate internal transactions (additional calls) to other smart contracts. These internal transactions create data structures called traces, and may also emit additional log events during their respective executions." }, { "code": null, "e": 8739, "s": 8587, "text": "To make this more concrete, let us take a closer look at an example of a transaction to purchase a Bored Ape NFT on the Opensea exchange smart contract" }, { "code": null, "e": 8760, "s": 8739, "text": "In this transaction:" }, { "code": null, "e": 9408, "s": 8760, "text": "The buyer EOA initiates the transaction with a call to the atomicMatch_ function in the Opensea Exchange smart contractThe exchange contract verifies that the order bid matches the ask of the sellers, then emits the OrderMatched event signifying that the order is confirmedThe exchange contract initiates an internal transaction to the Bored Ape NFT contract to transfer the NFT from the seller to the buyer, which in turn emits an Approval and a Transfer event upon completionThe exchange contract then initiates another internal transaction to transfer the funds, paid by the buyer EOA when initiating the original transaction, to the seller EOA" }, { "code": null, "e": 9528, "s": 9408, "text": "The buyer EOA initiates the transaction with a call to the atomicMatch_ function in the Opensea Exchange smart contract" }, { "code": null, "e": 9683, "s": 9528, "text": "The exchange contract verifies that the order bid matches the ask of the sellers, then emits the OrderMatched event signifying that the order is confirmed" }, { "code": null, "e": 9888, "s": 9683, "text": "The exchange contract initiates an internal transaction to the Bored Ape NFT contract to transfer the NFT from the seller to the buyer, which in turn emits an Approval and a Transfer event upon completion" }, { "code": null, "e": 10059, "s": 9888, "text": "The exchange contract then initiates another internal transaction to transfer the funds, paid by the buyer EOA when initiating the original transaction, to the seller EOA" }, { "code": null, "e": 10410, "s": 10059, "text": "At the completion of this sequence, the transaction, traces from internal transactions, and logs from events are all persisted to the blockchain ledger. As this example hopefully made clear, the data exhaust from transactions provide very granular details about the inner workings of the crypto applications and the economic activity they facilitate." }, { "code": null, "e": 10690, "s": 10410, "text": "Now that we understand the data elements that are created by the crypto applications, and what they represent in reality, let us take a look at what this data looks like. The transaction and trace data structures contain details of the smart contract function call, in particular" }, { "code": null, "e": 10725, "s": 10690, "text": "hash: unique id of the transaction" }, { "code": null, "e": 10766, "s": 10725, "text": "from_address: the initiating EOA address" }, { "code": null, "e": 10812, "s": 10766, "text": "to_address: the target smart contract address" }, { "code": null, "e": 10909, "s": 10812, "text": "input: hexadecimal encoded representation of the target function and arguments for that function" }, { "code": null, "e": 10949, "s": 10909, "text": "value: the transaction value or payment" }, { "code": null, "e": 10969, "s": 10949, "text": "Example transaction" }, { "code": null, "e": 11748, "s": 10969, "text": "hash: 0xfdf4e500eeefa5b12d773fb74d55c4bbfc92a4297cddc8f85b937978a3fc6477nonce: 232transaction_index: 19from_address: 0xfc7396fc573e916dc0d7203b0f087ffc46882c17to_address: 0x7be8076f4ea4a4ad08075c2508e481d6c946d12bvalue: 0E-9gas: 74902gas_price: 52545827339input: 0xa8a41c700000000000000000000000007be8076f4ea4a4ad08075c2508e481d6c946d12b000000000000000000000000fc7396fc573e916dc0d7203b0f087ffc46882c170...receipt_cumulative_gas_used: 1242267receipt_gas_used: 74902receipt_contract_address: Nonereceipt_root: Nonereceipt_status: 1block_timestamp: 2021–08–10 04:18:55block_number: 12995203block_hash: 0x7ca2ff7158d7a40997a5230e39f8d96ad17cf59ced6b27a3288653f9c94ce7a3max_fee_per_gas: Nonemax_priority_fee_per_gas: Nonetransaction_type: Nonereceipt_effective_gas_price: 52545827339" }, { "code": null, "e": 11887, "s": 11748, "text": "The log data structure contains details of the events that were emitted during the execution of the smart contract function, in particular" }, { "code": null, "e": 11956, "s": 11887, "text": "transaction_hash: ID of the transaction that the event was a part of" }, { "code": null, "e": 12018, "s": 11956, "text": "address: address of the smart contract that emitted the event" }, { "code": null, "e": 12062, "s": 12018, "text": "topics: the function that emitted the event" }, { "code": null, "e": 12083, "s": 12062, "text": "data: event metadata" }, { "code": null, "e": 12095, "s": 12083, "text": "Example log" }, { "code": null, "e": 12883, "s": 12095, "text": "log_index: 260transaction_hash: 0x2ac3648d5a0a7c1dd58685fabb5c5602add36f1555b1001cb900ea0410ab23dbtransaction_index: 131address: 0xff64cb7ba5717a10dabc4be3a41acd2c2f95ee22data: 0x000000000000000000000000000000000000000000054e0ee097e3dbdbde51b2000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000011d65da6b52d881ddtopics: [‘0xd78ad95fa46c994b6551d0da85fc275fe613ce37657fb8d5e3d130840159d822’,‘0x00000000000000000000000003f7724180aa6b939894b5ca4314783b0b36b329’,‘0x000000000000000000000000e83df6e24de6d5d263f78ad281143f184a6c95eb’]block_timestamp: 2021–08–04 06:40:42block_number: 12957113block_hash: 0x3ea06d9b495dffb2804a5f62ee0182949afac9f82d6ba922567fa3a95efc3d86" }, { "code": null, "e": 13163, "s": 12883, "text": "The astute reader will notice that many fields that are long hexadecimals that are not human friendly. In order to parse out the encoded information, we need to decode these using something called application binary interface. I will discuss this in more detail in the next post." }, { "code": null, "e": 13368, "s": 13163, "text": "Now that we have a good understanding of what crypto data represents and what it looks like, how do we actually access and work with it? Luckily there is an array of great tools to help us with just that." }, { "code": null, "e": 13384, "s": 13368, "text": "Block explorers" }, { "code": null, "e": 13808, "s": 13384, "text": "Block explorers are great resources for examining individual transaction details on a given blockchain. The builders of block explorers have extracted and indexed the entire blockchain ledger, and created fast web interfaces to help users easily look up any transaction. See the screenshot below for an example. All major blockchains have explorers — prominent examples include Etherscan, Polygonscan, BSCScan, Solana beach" }, { "code": null, "e": 14234, "s": 13808, "text": "While block explorers are great for interrogating individual records within the blockchain ledger, they are not great for answering questions that require aggregation or transformation of the data. For example if you wanted to know how many NFTs were sold through the Opensea exchange in the last 3 months, it would be very difficult to answer that with just block explorers. For that you will need direct access to the data." }, { "code": null, "e": 14251, "s": 14234, "text": "Getting the data" }, { "code": null, "e": 14461, "s": 14251, "text": "One way to directly access the data is to query the blockchain yourself. There are various open source utility packages that are available in Python and Javascript to help make this process easier. For example" }, { "code": null, "e": 14569, "s": 14461, "text": "For the Ethereum blockchains, and EVM compatible chains like Polygon and BSC, you can use the Web3 package." }, { "code": null, "e": 14607, "s": 14569, "text": "For Solana, you can use the Solana Py" }, { "code": null, "e": 14789, "s": 14607, "text": "With these utility libraries, you will be able to programmatically interact with the blockchain of interest, to query for data, submit transactions, and even deploy smart contracts." }, { "code": null, "e": 15169, "s": 14789, "text": "There are also open source projects that have packaged the above building blocks together into full ETL pipelines to help you download all the granular data into your own environment. Furthermore, the owners of these projects have also published many of the raw datasets into public datasets on Google cloud, which offers a relatively easy-to-use SQL interface to query the data." }, { "code": null, "e": 15904, "s": 15169, "text": "Last, but not least, Dune analytics is another great resource for accessing and analyzing blockchain data. It has both raw and decoded data for Ethereum, Polygon, Optimism and BSC as of the writing of this post. This is a very differentiated offering compared to the public dataset on Google, because the decoding makes the hexadecimal encoded data fields human readable. It offers a Postgres interface for querying the datasets and a simple point and click interface for creating simple dashboards on top of the query results. The community of users on Dune is also quite active and has generated an extensive library of example queries and dashboards to learn from. Here are a couple of examples analysis that I have created on Dune" }, { "code": null, "e": 15944, "s": 15904, "text": "Opensea transactions and user deep dive" }, { "code": null, "e": 15999, "s": 15944, "text": "Decentralized exchanges transaction and user deep dive" }, { "code": null, "e": 16068, "s": 15999, "text": "Crypto data is the exhaust from the web 3.0 application architecture" }, { "code": null, "e": 16194, "s": 16068, "text": "It contains full history of all the “backend API calls” in a crypto application, in the form of transactions, logs and traces" }, { "code": null, "e": 16291, "s": 16194, "text": "These data structures contain granular details of the user request and application state changes" }, { "code": null, "e": 16395, "s": 16291, "text": "There are a variety of freely available tools to help us access and analyze this treasure trove of data" }, { "code": null, "e": 16846, "s": 16395, "text": "Hopefully this was a useful discussion and I have helped you gain better intuition about what crypto data is, what it looks like and how to work with it. In my next post, I will provide a tutorial on how to decode crypto data and make them more human readable, as a precursor to deeper investigations of popular crypto applications like Opensea and Uniswap. Be sure to hit the email icon to subscribe if you would like to be notified when that posts." }, { "code": null, "e": 16949, "s": 16846, "text": "Thank you for reading and feel free to reach out if you have questions or comments. Twitter | Linkedin" }, { "code": null, "e": 17141, "s": 16949, "text": "[1] This discussion will be using the Ethereum blockchain as the primary reference architecture. Specifics may vary for other blockchains like Solana, but many of the concepts will generally." } ]
Redis - List Lpop Command
Redis LPOP command removes and returns the first element of the list stored at the key. String reply, the value of the first element, or nil when the key does not exist. Following is the basic syntax of Redis LPOP command. redis 127.0.0.1:6379> LPOP KEY_NAME redis 127.0.0.1:6379> RPUSH list1 "foo" (integer) 1 redis 127.0.0.1:6379> RPUSH list1 "bar" (integer) 2 redis 127.0.0.1:6379> LPOP list1 "foo" 22 Lectures 40 mins Skillbakerystudios Print Add Notes Bookmark this page
[ { "code": null, "e": 2133, "s": 2045, "text": "Redis LPOP command removes and returns the first element of the list stored at the key." }, { "code": null, "e": 2215, "s": 2133, "text": "String reply, the value of the first element, or nil when the key does not exist." }, { "code": null, "e": 2268, "s": 2215, "text": "Following is the basic syntax of Redis LPOP command." }, { "code": null, "e": 2305, "s": 2268, "text": "redis 127.0.0.1:6379> LPOP KEY_NAME\n" }, { "code": null, "e": 2454, "s": 2305, "text": "redis 127.0.0.1:6379> RPUSH list1 \"foo\" \n(integer) 1 \nredis 127.0.0.1:6379> RPUSH list1 \"bar\" \n(integer) 2 \nredis 127.0.0.1:6379> LPOP list1\n\"foo\" \n" }, { "code": null, "e": 2486, "s": 2454, "text": "\n 22 Lectures \n 40 mins\n" }, { "code": null, "e": 2506, "s": 2486, "text": " Skillbakerystudios" }, { "code": null, "e": 2513, "s": 2506, "text": " Print" }, { "code": null, "e": 2524, "s": 2513, "text": " Add Notes" } ]
How to trim spaces from field in MongoDB query?
To trim spaces from field, use $trim in MongoDB. Let us create a collection with documents − > db.demo217.insertOne({"FullName":" Chris Brown"}); { "acknowledged" : true, "insertedId" : ObjectId("5e3e5d1e03d395bdc213470f") } > db.demo217.insertOne({"FullName":" David Miller"}); { "acknowledged" : true, "insertedId" : ObjectId("5e3e5d2503d395bdc2134710") } > db.demo217.insertOne({"FullName":" John Doe"}); { "acknowledged" : true, "insertedId" : ObjectId("5e3e5d2b03d395bdc2134711") } Display all documents from a collection with the help of find() method − > db.demo217.find(); This will produce the following output − { "_id" : ObjectId("5e3e5d1e03d395bdc213470f"), "FullName" : " Chris Brown" } { "_id" : ObjectId("5e3e5d2503d395bdc2134710"), "FullName" : " David Miller" } { "_id" : ObjectId("5e3e5d2b03d395bdc2134711"), "FullName" : " John Doe" } Following is the query to trim spaces from field in MongoDB − > db.demo217.aggregate([ ... { $project: { Name: { $trim: { input: "$FullName" } } } } ... ]) This will produce the following output − { "_id" : ObjectId("5e3e5d1e03d395bdc213470f"), "Name" : "Chris Brown" } { "_id" : ObjectId("5e3e5d2503d395bdc2134710"), "Name" : "David Miller" } { "_id" : ObjectId("5e3e5d2b03d395bdc2134711"), "Name" : "John Doe" }
[ { "code": null, "e": 1155, "s": 1062, "text": "To trim spaces from field, use $trim in MongoDB. Let us create a collection with documents −" }, { "code": null, "e": 1573, "s": 1155, "text": "> db.demo217.insertOne({\"FullName\":\" Chris Brown\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e3e5d1e03d395bdc213470f\")\n}\n> db.demo217.insertOne({\"FullName\":\" David Miller\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e3e5d2503d395bdc2134710\")\n}\n> db.demo217.insertOne({\"FullName\":\" John Doe\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e3e5d2b03d395bdc2134711\")\n}" }, { "code": null, "e": 1646, "s": 1573, "text": "Display all documents from a collection with the help of find() method −" }, { "code": null, "e": 1667, "s": 1646, "text": "> db.demo217.find();" }, { "code": null, "e": 1708, "s": 1667, "text": "This will produce the following output −" }, { "code": null, "e": 1946, "s": 1708, "text": "{ \"_id\" : ObjectId(\"5e3e5d1e03d395bdc213470f\"), \"FullName\" : \" Chris Brown\" }\n{ \"_id\" : ObjectId(\"5e3e5d2503d395bdc2134710\"), \"FullName\" : \" David Miller\" }\n{ \"_id\" : ObjectId(\"5e3e5d2b03d395bdc2134711\"), \"FullName\" : \" John Doe\" }" }, { "code": null, "e": 2008, "s": 1946, "text": "Following is the query to trim spaces from field in MongoDB −" }, { "code": null, "e": 2105, "s": 2008, "text": "> db.demo217.aggregate([\n... { $project: { Name: { $trim: { input: \"$FullName\" } } } }\n... ])" }, { "code": null, "e": 2146, "s": 2105, "text": "This will produce the following output −" }, { "code": null, "e": 2363, "s": 2146, "text": "{ \"_id\" : ObjectId(\"5e3e5d1e03d395bdc213470f\"), \"Name\" : \"Chris Brown\" }\n{ \"_id\" : ObjectId(\"5e3e5d2503d395bdc2134710\"), \"Name\" : \"David Miller\" }\n{ \"_id\" : ObjectId(\"5e3e5d2b03d395bdc2134711\"), \"Name\" : \"John Doe\" }" } ]