title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
C Program for Number of elements with odd factors in given range - GeeksforGeeks
05 Dec, 2018 Given a range [n, m], find the number of elements that have odd number of factors in the given range (n and m inclusive). Examples: Input : n = 5, m = 100 Output : 8 The numbers with odd factors are 9, 16, 25, 36, 49, 64, 81 and 100 Input : n = 8, m = 65 Output : 6 Input : n = 10, m = 23500 Output : 150 A Simple Solution is to loop through all numbers starting from n. For every number, check if it has an even number of factors. If it has an even number of factors then increment count of such numbers and finally print the number of such elements. To find all divisors of a natural number efficiently, refer All divisors of a natural number An Efficient Solution is to observe the pattern. Only those numbers, which are perfect Squares have an odd number of factors. Let us analyze this pattern through an example. For example, 9 has odd number of factors, 1, 3 and 9. 16 also has odd number of factors, 1, 2, 4, 8, 16. The reason for this is, for numbers other than perfect squares, all factors are in the form of pairs, but for perfect squares, one factor is single and makes the total as odd. How to find number of perfect squares in a range?The answer is difference between square root of m and n-1 (not n)There is a little caveat. As both n and m are inclusive, if n is a perfect square, we will get an answer which is less than one the actual answer. To understand this, consider range [4, 36]. Answer is 5 i.e., numbers 4, 9, 16, 25 and 36.But if we do (36**0.5) – (4**0.5) we get 4. So to avoid this semantic error, we take n-1. // C++ program to count number of odd squares// in given range [n, m]#include <bits/stdc++.h>using namespace std; int countOddSquares(int n, int m){ return (int)pow(m, 0.5) - (int)pow(n - 1, 0.5);} // Driver codeint main(){ int n = 5, m = 100; cout << "Count is " << countOddSquares(n, m); return 0;} Count is 8 Time Complexity: O(1) Please refer complete article on Number of elements with odd factors in given range for more details! C Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C Program to read contents of Whole File Producer Consumer Problem in C C program to find the length of a string Exit codes in C/C++ with Examples Regular expressions in C C / C++ Program for Dijkstra's shortest path algorithm | Greedy Algo-7 Conditional wait and signal in multi-threading Handling multiple clients on server with multithreading using Socket Programming in C/C++ C Hello World Program Difference between break and continue statement in C
[ { "code": null, "e": 24930, "s": 24902, "text": "\n05 Dec, 2018" }, { "code": null, "e": 25052, "s": 24930, "text": "Given a range [n, m], find the number of elements that have odd number of factors in the given range (n and m inclusive)." }, { "code": null, "e": 25062, "s": 25052, "text": "Examples:" }, { "code": null, "e": 25242, "s": 25062, "text": "Input : n = 5, m = 100\nOutput : 8\nThe numbers with odd factors are 9, 16, 25, \n36, 49, 64, 81 and 100\n\nInput : n = 8, m = 65\nOutput : 6\n\nInput : n = 10, m = 23500\nOutput : 150\n" }, { "code": null, "e": 25582, "s": 25242, "text": "A Simple Solution is to loop through all numbers starting from n. For every number, check if it has an even number of factors. If it has an even number of factors then increment count of such numbers and finally print the number of such elements. To find all divisors of a natural number efficiently, refer All divisors of a natural number" }, { "code": null, "e": 25756, "s": 25582, "text": "An Efficient Solution is to observe the pattern. Only those numbers, which are perfect Squares have an odd number of factors. Let us analyze this pattern through an example." }, { "code": null, "e": 26037, "s": 25756, "text": "For example, 9 has odd number of factors, 1, 3 and 9. 16 also has odd number of factors, 1, 2, 4, 8, 16. The reason for this is, for numbers other than perfect squares, all factors are in the form of pairs, but for perfect squares, one factor is single and makes the total as odd." }, { "code": null, "e": 26478, "s": 26037, "text": "How to find number of perfect squares in a range?The answer is difference between square root of m and n-1 (not n)There is a little caveat. As both n and m are inclusive, if n is a perfect square, we will get an answer which is less than one the actual answer. To understand this, consider range [4, 36]. Answer is 5 i.e., numbers 4, 9, 16, 25 and 36.But if we do (36**0.5) – (4**0.5) we get 4. So to avoid this semantic error, we take n-1." }, { "code": "// C++ program to count number of odd squares// in given range [n, m]#include <bits/stdc++.h>using namespace std; int countOddSquares(int n, int m){ return (int)pow(m, 0.5) - (int)pow(n - 1, 0.5);} // Driver codeint main(){ int n = 5, m = 100; cout << \"Count is \" << countOddSquares(n, m); return 0;}", "e": 26793, "s": 26478, "text": null }, { "code": null, "e": 26805, "s": 26793, "text": "Count is 8\n" }, { "code": null, "e": 26827, "s": 26805, "text": "Time Complexity: O(1)" }, { "code": null, "e": 26929, "s": 26827, "text": "Please refer complete article on Number of elements with odd factors in given range for more details!" }, { "code": null, "e": 26940, "s": 26929, "text": "C Programs" }, { "code": null, "e": 27038, "s": 26940, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27079, "s": 27038, "text": "C Program to read contents of Whole File" }, { "code": null, "e": 27110, "s": 27079, "text": "Producer Consumer Problem in C" }, { "code": null, "e": 27151, "s": 27110, "text": "C program to find the length of a string" }, { "code": null, "e": 27185, "s": 27151, "text": "Exit codes in C/C++ with Examples" }, { "code": null, "e": 27210, "s": 27185, "text": "Regular expressions in C" }, { "code": null, "e": 27281, "s": 27210, "text": "C / C++ Program for Dijkstra's shortest path algorithm | Greedy Algo-7" }, { "code": null, "e": 27328, "s": 27281, "text": "Conditional wait and signal in multi-threading" }, { "code": null, "e": 27418, "s": 27328, "text": "Handling multiple clients on server with multithreading using Socket Programming in C/C++" }, { "code": null, "e": 27440, "s": 27418, "text": "C Hello World Program" } ]
Python | math.floor() function - GeeksforGeeks
11 Mar, 2019 In Python, math module contains a number of mathematical operations, which can be performed with ease using the module. math.floor() function returns the largest integer not greater than x. If number is already integer, same number is returned. Syntax: math.floor(x) Parameter: x: This is a numeric expression. Returns: largest integer not greater than x. Code #1: # Python code to demonstrate the working of floor() # importing "math" for mathematical operations import math x = 33.7 # returning the floor of 33.7print ("The floor of 33.7 is : ", end ="") print (math.floor(x)) The floor of 33.7 is : 33 Code #2: # Python code to demonstrate the working of floor() # importing "math" for mathematical operations import math # prints the floor using floor() method print ("math.floor(-13.1) : ", math.floor(-13.1))print ("math.floor(101.96) : ", math.floor(101.96)) math.floor(-13.1) : -14 math.floor(101.96) : 101 Python math-library-functions Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe Selecting rows in pandas DataFrame based on conditions How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | os.path.join() method Python | Get unique values from a list Defaultdict in Python Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 24292, "s": 24264, "text": "\n11 Mar, 2019" }, { "code": null, "e": 24537, "s": 24292, "text": "In Python, math module contains a number of mathematical operations, which can be performed with ease using the module. math.floor() function returns the largest integer not greater than x. If number is already integer, same number is returned." }, { "code": null, "e": 24651, "s": 24537, "text": "Syntax: math.floor(x)\n\nParameter:\nx: This is a numeric expression.\n\nReturns: largest integer not greater than x." }, { "code": null, "e": 24660, "s": 24651, "text": "Code #1:" }, { "code": "# Python code to demonstrate the working of floor() # importing \"math\" for mathematical operations import math x = 33.7 # returning the floor of 33.7print (\"The floor of 33.7 is : \", end =\"\") print (math.floor(x))", "e": 24884, "s": 24660, "text": null }, { "code": null, "e": 24911, "s": 24884, "text": "The floor of 33.7 is : 33\n" }, { "code": null, "e": 24921, "s": 24911, "text": " Code #2:" }, { "code": "# Python code to demonstrate the working of floor() # importing \"math\" for mathematical operations import math # prints the floor using floor() method print (\"math.floor(-13.1) : \", math.floor(-13.1))print (\"math.floor(101.96) : \", math.floor(101.96))", "e": 25180, "s": 24921, "text": null }, { "code": null, "e": 25232, "s": 25180, "text": "math.floor(-13.1) : -14\nmath.floor(101.96) : 101\n" }, { "code": null, "e": 25262, "s": 25232, "text": "Python math-library-functions" }, { "code": null, "e": 25269, "s": 25262, "text": "Python" }, { "code": null, "e": 25367, "s": 25269, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25376, "s": 25367, "text": "Comments" }, { "code": null, "e": 25389, "s": 25376, "text": "Old Comments" }, { "code": null, "e": 25421, "s": 25389, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 25477, "s": 25421, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 25532, "s": 25477, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 25574, "s": 25532, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 25616, "s": 25574, "text": "Check if element exists in list in Python" }, { "code": null, "e": 25647, "s": 25616, "text": "Python | os.path.join() method" }, { "code": null, "e": 25686, "s": 25647, "text": "Python | Get unique values from a list" }, { "code": null, "e": 25708, "s": 25686, "text": "Defaultdict in Python" }, { "code": null, "e": 25737, "s": 25708, "text": "Create a directory in Python" } ]
VueJS - Binding
In this chapter will learn how to manipulate or assign values to HTML attributes, change the style, and assign classes with the help of binding directive called v-bind available with VueJS. Let’s consider an example to understand why we need and when to use v-bind directive for data binding. <html> <head> <title>VueJs Instance</title> <script type = "text/javascript" src = "js/vue.js"></script> </head> <body> <div id = "databinding"> {{title}}<br/> <a href = "hreflink" target = "_blank"> Click Me </a> <br/> <a href = "{{hreflink}}" target = "_blank">Click Me </a> <br/> <a v-bind:href = "hreflink" target = "_blank">Click Me </a> <br/> </div> <script type = "text/javascript"> var vm = new Vue({ el: '#databinding', data: { title : "DATA BINDING", hreflink : "http://www.google.com" } }); </script> </body> </html> In above example, we have displayed a title variable and three anchor links. We have also assigned a value to the href from the data object. Now, if we check the output in the browser and inspect, we will see the first two anchor links do not have the href correctly as shown in the following screenshot. The first clickme shows the href as hreflink, and the second one shows it in {{hreflink}}, while the last one displays the correct url as we require. Hence, to assign values to HTML attributes, we need to bind it with the directive v-bind as follows. <a v-bind:href = "hreflink" target = "_blank">Click Me </a> VueJS also provides a shorthand for v-bind as follows. <a :href = "hreflink" target = "_blank">Click Me </a> If we see the inspect element in the browser, the anchor tag does not show the v-bind attribute, however, it displays the plain HTML. None of the VueJS properties are seen when we inpsect the DOM. To bind HTML class, we need to use v-bind: class. Let’s consider an example and bind classes in it. <html> <head> <title>VueJs Instance</title> <script type = "text/javascript" src = "js/vue.js"></script> </head> <body> <style> .active { background: red; } </style> <div id = "classbinding"> <div v-bind:class = "{active:isactive}"><b>{{title}}</b></div> </div> <script type = "text/javascript"> var vm = new Vue({ el: '#classbinding', data: { title : "CLASS BINDING", isactive : true } }); </script> </body> </html> There is a div created with v-bind: class=” {active: isactive}”. Here, isactive is a variable which is based on true or false. It will apply the class active to the div. In the data object, we have assigned the isactive variable as true. There is a class defined in the style .active with the background color as red. If the variable isactive is true, the color will be applied otherwise not. Following will be the output in the browser. In above display, we can see the background color is red. The class = ”active” is applied to the div. Now, let’s change the value of the variable to false and see the output. The variable isactive is changed to false as shown in the following code. <html> <head> <title>VueJs Instance</title> <script type = "text/javascript" src = "js/vue.js"></script> </head> <body> <style> .active { background: red; } </style> <div id = "classbinding"> <div v-bind:class = "{active:isactive}"><b>{{title}}</b></div> </div> <script type = "text/javascript"> var vm = new Vue({ el: '#classbinding', data: { title : "CLASS BINDING", isactive : false } }); </script> </body> </html> In the above display, we can see the active class is not applied to the div. We can also assign multiple classes to the HTML tags using v-bind attribute. <html> <head> <title>VueJs Instance</title> <script type = "text/javascript" src = "js/vue.js"></script> </head> <body> <style> .info { color: #00529B; background-color: #BDE5F8; } div { margin: 10px 0; padding: 12px; } .active { color: #4F8A10; background-color: #DFF2BF; } .displayError{ color: #D8000C; background-color: #FFBABA; } </style> <div id = "classbinding"> <div class = "info" v-bind:class = "{ active: isActive, 'displayError': hasError }"> {{title}} </div> </div> <script type = "text/javascript"> var vm = new Vue({ el: '#classbinding', data: { title : "This is class binding example", isActive : false, hasError : false } }); </script> </body> </html> For the div in the above code, we have applied a normal class, example class = ”info”. Based on isActive and hasError variable, the other classes will get applied to the div. This is a normal class applied. Both the variables are false right now. Let’s make isActive variable to true and see the output. In the above display, in the DOM we can see two classes assigned to the div, info and active. Let’s make hasError variable true and isActive as false. Now, when we see in the above display, info and displayError class is applied to the div. This is how we can apply multiple classes based on conditions. We can also pass class as an array. Let us take an example to understand this. <html> <head> <title>VueJs Instance</title> <script type = "text/javascript" src = "js/vue.js"></script> </head> <body> <style> .info { color: #00529B; background-color: #BDE5F8; } div { margin: 10px 0; padding: 12px; font-size : 25px; } .active { color: #4F8A10; background-color: #DFF2BF; } .displayError{ color: #D8000C; background-color: #FFBABA; } </style> <div id = "classbinding"> <div v-bind:class = "[infoclass, errorclass]">{{title}}</div> </div> <script type = "text/javascript"> var vm = new Vue({ el: '#classbinding', data: { title : "This is class binding example", infoclass : 'info', errorclass : 'displayError' } }); </script> </body> </html> As we can see above, both classes get applied to the div. Let’s use a variable and based on the value of the variable, assign the class. <html> <head> <title>VueJs Instance</title> <script type = "text/javascript" src = "js/vue.js"></script> </head> <body> <style> .info { color: #00529B; background-color: #BDE5F8; } div { margin: 10px 0; padding: 12px; font-size : 25px; } .active { color: #4F8A10; background-color: #DFF2BF; } .displayError{ color: #D8000C; background-color: #FFBABA; } </style> <div id = "classbinding"> <div v-bind:class = "[isActive ? infoclass : '', haserror ? errorclass : '']">{{title}}</div> </div> <script type = "text/javascript"> var vm = new Vue({ el: '#classbinding', data: { title : "This is class binding example", infoclass : 'info', errorclass : 'displayError', isActive : true, haserror : false } }); </script> </body> </html> We have used two variables isActive and haserror and the same is used for the div while class binding as shown in the following div tag. <div v-bind:class = "[isActive ? infoclass : '', haserror ? errorclass : '']">{{title}}</div> If isActive is true, then infoclass will be assigned to it. The same goes for haserror, if it is true, then only errorClass will be applied to it. Now, let us make haserror variable as true and isActive variable as false. We will now add v-bind for classes in the components. In the following example, we have added a class to the component template and also to the component. <html> <head> <title>VueJs Instance</title> <script type = "text/javascript" src = "js/vue.js"></script> </head> <body> <style> .info { color: #00529B; background-color: #BDE5F8; } div { margin: 10px 0; padding: 12px; font-size : 25px; } .active { color: #4F8A10; background-color: #DFF2BF; } .displayError{ color: #D8000C; background-color: #FFBABA; } </style> <div id = "classbinding"> <new_component class = "active"></new_component> </div> <script type = "text/javascript"> var vm = new Vue({ el: '#classbinding', data: { title : "This is class binding example", infoclass : 'info', errorclass : 'displayError', isActive : false, haserror : true }, components:{ 'new_component' : { template : '<div class = "info">Class Binding for component</div>' } } }); </script> </body> </html> Following is the output in the browser. It applies both the classes to final div. <div class = ”info active”></div> Add a variable in the component section to display, based on true/false. <html> <head> <title>VueJs Instance</title> <script type = "text/javascript" src = "js/vue.js"></script> </head> <body> <style> .info { color: #00529B; background-color: #BDE5F8; } div { margin: 10px 0; padding: 12px; font-size : 25px; } .active { color: #4F8A10; background-color: #DFF2BF; } .displayError{ color: #D8000C; background-color: #FFBABA; } </style> <div id = "classbinding"> <new_component v-bind:class = "{active:isActive}"></new_component> </div> <script type = "text/javascript"> var vm = new Vue({ el: '#classbinding', data: { title : "This is class binding example", infoclass : 'info', errorclass : 'displayError', isActive : false, haserror : true }, components:{ 'new_component' : { template : '<div class = "info">Class Binding for component</div>' } } }); </script> </body> </html> Since the variable is false, the active class is not applied and the info class is applied as shown in the following screenshot. Example <html> <head> <title>VueJs Instance</title> <script type = "text/javascript" src = "js/vue.js"></script> </head> <body> <div id = "databinding"> <div v-bind:style = "{ color: activeColor, fontSize: fontSize + 'px' }">{{title}}</div> </div> <script type = "text/javascript"> var vm = new Vue({ el: '#databinding', data: { title : "Inline style Binding", activeColor: 'red', fontSize :'30' } }); </script> </body> </html> Output In the above example, for the div, the style is applied and the data is fetched from the data object. <div v-bind:style = "{ color: activeColor, fontSize: fontSize + 'px' }">{{title}}</div> data: { title : "Inline style Binding", activeColor: 'red', fontSize :'30' } We can also do the same thing by assigning all the values to a variable and then assigning the variable to the div. Example <html> <head> <title>VueJs Instance</title> <script type = "text/javascript" src = "js/vue.js"></script> </head> <body> <div id = "databinding"> <div v-bind:style = "styleobj">{{title}}</div> </div> <script type = "text/javascript"> var vm = new Vue({ el: '#databinding', data: { title : "Inline style Binding", styleobj : { color: 'red', fontSize :'40px' } } }); </script> </body> </html> The color and the fontSize is assigned to the object called styleobj and the same is assigned to the div. <div v-bind:style = "styleobj">{{title}}</div> Output So far in the example we have created, we have seen v-model binding the input text element and the value binded to a variable assigned. Let’s learn more about it in this section. <html> <head> <title>VueJs Instance</title> <script type = "text/javascript" src = "js/vue.js"></script> </head> <body> <div id = "databinding"> <h3>TEXTBOX</h3> <input v-model = "name" placeholder = "Enter Name" /> <h3>Name entered is : {{name}}</h3> <hr/> <h3>Textarea</h3> <textarea v-model = "textmessage" placeholder = "Add Details"></textarea> <h1><p>{{textmessage}}</p></h1> <hr/> <h3>Checkbox</h3> <input type = "checkbox" id = "checkbox" v-model = "checked"> {{checked}} </div> <script type = "text/javascript"> var vm = new Vue({ el: '#databinding', data: { name:'', textmessage:'', checked : false } }); </script> </body> </html> Whatever we type in the texbox is displayed below. v-model is assigned the value name and the name is displayed in {{name}}, which displays whatever is typed in the textbox. Let’s checkout out some more examples and how to use it. Example <html> <head> <title>VueJs Instance</title> <script type = "text/javascript" src = "js/vue.js"></script> </head> <body> <div id = "databinding"> <h3>Radio</h3> <input type = "radio" id = "black" value = "Black" v-model = "picked">Black <input type = "radio" id = "white" value = "White" v-model = "picked">White <h3>Radio element clicked : {{picked}} </h3> <hr/> <h3>Select</h3> <select v-model = "languages"> <option disabled value = "">Please select one</option> <option>Java</option> <option>Javascript</option> <option>Php</option> <option>C</option> <option>C++</option> </select> <h3>Languages Selected is : {{ languages }}</h3> <hr/> </div> <script type = "text/javascript"> var vm = new Vue({ el: '#databinding', data: { picked : 'White', languages : "Java" } }); </script> </body> </html> Output We have used three modifiers in the example - trim, number, and lazy. Example <html> <head> <title>VueJs Instance</title> <script type = "text/javascript" src = "js/vue.js"></script> </head> <body> <div id = "databinding"> <span style = "font-size:25px;">Enter Age:</span> <input v-model.number = "age" type = "number"> <br/> <span style = "font-size:25px;">Enter Message:</span> <input v-model.lazy = "msg"> <h3>Display Message : {{msg}}</h3> <br/> <span style = "font-size:25px;">Enter Message : </span><input v-model.trim = "message"> <h3>Display Message : {{message}}</h3> </div> <script type = "text/javascript"> var vm = new Vue({ el: '#databinding', data: { age : 0, msg: '', message : '' } }); </script> </body> </html> Output Number modifier allows to only enter numbers. It will not take any other input besides numbers. <span style = "font-size:25px;">Enter Age:</span> <input v-model.number = "age" type = "number"> Lazy modifier will display the content present in the textbox once it is fully entered and the user leaves the textbox. <span style = "font-size:25px;">Enter Message:</span> <input v-model.lazy = "msg"> Trim modifier will remove any spaces entered at the start and at the end. <span style = "font-size:25px;">Enter Message : </span><input v-model.trim = "message"> Print Add Notes Bookmark this page
[ { "code": null, "e": 2126, "s": 1936, "text": "In this chapter will learn how to manipulate or assign values to HTML attributes, change the style, and assign classes with the help of binding directive called v-bind available with VueJS." }, { "code": null, "e": 2229, "s": 2126, "text": "Let’s consider an example to understand why we need and when to use v-bind directive for data binding." }, { "code": null, "e": 2928, "s": 2229, "text": "<html>\n <head>\n <title>VueJs Instance</title>\n <script type = \"text/javascript\" src = \"js/vue.js\"></script>\n </head>\n <body>\n <div id = \"databinding\">\n {{title}}<br/>\n <a href = \"hreflink\" target = \"_blank\"> Click Me </a> <br/>\n <a href = \"{{hreflink}}\" target = \"_blank\">Click Me </a> <br/>\n <a v-bind:href = \"hreflink\" target = \"_blank\">Click Me </a> <br/>\n </div>\n <script type = \"text/javascript\">\n var vm = new Vue({\n el: '#databinding',\n data: {\n title : \"DATA BINDING\",\n hreflink : \"http://www.google.com\"\n }\n });\n </script>\n </body>\n</html>" }, { "code": null, "e": 3069, "s": 2928, "text": "In above example, we have displayed a title variable and three anchor links. We have also assigned a value to the href from the data object." }, { "code": null, "e": 3233, "s": 3069, "text": "Now, if we check the output in the browser and inspect, we will see the first two anchor links do not have the href correctly as shown in the following screenshot." }, { "code": null, "e": 3383, "s": 3233, "text": "The first clickme shows the href as hreflink, and the second one shows it in {{hreflink}}, while the last one displays the correct url as we require." }, { "code": null, "e": 3484, "s": 3383, "text": "Hence, to assign values to HTML attributes, we need to bind it with the directive v-bind as follows." }, { "code": null, "e": 3544, "s": 3484, "text": "<a v-bind:href = \"hreflink\" target = \"_blank\">Click Me </a>" }, { "code": null, "e": 3599, "s": 3544, "text": "VueJS also provides a shorthand for v-bind as follows." }, { "code": null, "e": 3653, "s": 3599, "text": "<a :href = \"hreflink\" target = \"_blank\">Click Me </a>" }, { "code": null, "e": 3850, "s": 3653, "text": "If we see the inspect element in the browser, the anchor tag does not show the v-bind attribute, however, it displays the plain HTML. None of the VueJS properties are seen when we inpsect the DOM." }, { "code": null, "e": 3950, "s": 3850, "text": "To bind HTML class, we need to use v-bind: class. Let’s consider an example and bind classes in it." }, { "code": null, "e": 4550, "s": 3950, "text": "<html>\n <head>\n <title>VueJs Instance</title>\n <script type = \"text/javascript\" src = \"js/vue.js\"></script>\n </head>\n <body>\n <style>\n .active {\n background: red;\n }\n </style>\n <div id = \"classbinding\">\n <div v-bind:class = \"{active:isactive}\"><b>{{title}}</b></div>\n </div>\n <script type = \"text/javascript\">\n var vm = new Vue({\n el: '#classbinding',\n data: {\n title : \"CLASS BINDING\",\n isactive : true\n }\n });\n </script>\n </body>\n</html>" }, { "code": null, "e": 4615, "s": 4550, "text": "There is a div created with v-bind: class=” {active: isactive}”." }, { "code": null, "e": 4868, "s": 4615, "text": "Here, isactive is a variable which is based on true or false. It will apply the class active to the div. In the data object, we have assigned the isactive variable as true. There is a class defined in the style .active with the background color as red." }, { "code": null, "e": 4988, "s": 4868, "text": "If the variable isactive is true, the color will be applied otherwise not. Following will be the output in the browser." }, { "code": null, "e": 5090, "s": 4988, "text": "In above display, we can see the background color is red. The class = ”active” is applied to the div." }, { "code": null, "e": 5237, "s": 5090, "text": "Now, let’s change the value of the variable to false and see the output. The variable isactive is changed to false as shown in the following code." }, { "code": null, "e": 5838, "s": 5237, "text": "<html>\n <head>\n <title>VueJs Instance</title>\n <script type = \"text/javascript\" src = \"js/vue.js\"></script>\n </head>\n <body>\n <style>\n .active {\n background: red;\n }\n </style>\n <div id = \"classbinding\">\n <div v-bind:class = \"{active:isactive}\"><b>{{title}}</b></div>\n </div>\n <script type = \"text/javascript\">\n var vm = new Vue({\n el: '#classbinding',\n data: {\n title : \"CLASS BINDING\",\n isactive : false\n }\n });\n </script>\n </body>\n</html>" }, { "code": null, "e": 5915, "s": 5838, "text": "In the above display, we can see the active class is not applied to the div." }, { "code": null, "e": 5992, "s": 5915, "text": "We can also assign multiple classes to the HTML tags using v-bind attribute." }, { "code": null, "e": 7019, "s": 5992, "text": "<html>\n <head>\n <title>VueJs Instance</title>\n <script type = \"text/javascript\" src = \"js/vue.js\"></script>\n </head>\n <body>\n <style>\n .info {\n color: #00529B;\n background-color: #BDE5F8;\n }\n div {\n margin: 10px 0;\n padding: 12px;\n }\n .active {\n color: #4F8A10;\n background-color: #DFF2BF;\n }\n .displayError{\n color: #D8000C;\n background-color: #FFBABA;\n }\n </style>\n <div id = \"classbinding\">\n <div class = \"info\" v-bind:class = \"{ active: isActive, 'displayError': hasError }\">\n {{title}}\n </div>\n </div>\n <script type = \"text/javascript\">\n var vm = new Vue({\n el: '#classbinding',\n data: {\n title : \"This is class binding example\",\n isActive : false,\n hasError : false\n }\n });\n </script>\n </body>\n</html>" }, { "code": null, "e": 7194, "s": 7019, "text": "For the div in the above code, we have applied a normal class, example class = ”info”. Based on isActive and hasError variable, the other classes will get applied to the div." }, { "code": null, "e": 7323, "s": 7194, "text": "This is a normal class applied. Both the variables are false right now. Let’s make isActive variable to true and see the output." }, { "code": null, "e": 7474, "s": 7323, "text": "In the above display, in the DOM we can see two classes assigned to the div, info and active. Let’s make hasError variable true and isActive as false." }, { "code": null, "e": 7627, "s": 7474, "text": "Now, when we see in the above display, info and displayError class is applied to the div. This is how we can apply multiple classes based on conditions." }, { "code": null, "e": 7706, "s": 7627, "text": "We can also pass class as an array. Let us take an example to understand this." }, { "code": null, "e": 8714, "s": 7706, "text": "<html>\n <head>\n <title>VueJs Instance</title>\n <script type = \"text/javascript\" src = \"js/vue.js\"></script>\n </head>\n <body>\n <style>\n .info {\n color: #00529B;\n background-color: #BDE5F8;\n }\n div {\n margin: 10px 0;\n padding: 12px;\n font-size : 25px;\n }\n .active {\n color: #4F8A10;\n background-color: #DFF2BF;\n }\n .displayError{\n color: #D8000C;\n background-color: #FFBABA;\n }\n </style>\n <div id = \"classbinding\">\n <div v-bind:class = \"[infoclass, errorclass]\">{{title}}</div>\n </div>\n <script type = \"text/javascript\">\n var vm = new Vue({\n el: '#classbinding',\n data: {\n title : \"This is class binding example\",\n infoclass : 'info',\n errorclass : 'displayError'\n }\n });\n </script>\n </body>\n</html>" }, { "code": null, "e": 8851, "s": 8714, "text": "As we can see above, both classes get applied to the div. Let’s use a variable and based on the value of the variable, assign the class." }, { "code": null, "e": 9956, "s": 8851, "text": "<html>\n <head>\n <title>VueJs Instance</title>\n <script type = \"text/javascript\" src = \"js/vue.js\"></script>\n </head>\n <body>\n <style>\n .info {\n color: #00529B;\n background-color: #BDE5F8;\n }\n div {\n margin: 10px 0;\n padding: 12px;\n font-size : 25px;\n }\n .active {\n color: #4F8A10;\n background-color: #DFF2BF;\n }\n .displayError{\n color: #D8000C;\n background-color: #FFBABA;\n }\n </style>\n <div id = \"classbinding\">\n <div v-bind:class = \"[isActive ? infoclass : '', haserror ? errorclass : '']\">{{title}}</div>\n </div>\n <script type = \"text/javascript\">\n var vm = new Vue({\n el: '#classbinding',\n data: {\n title : \"This is class binding example\",\n infoclass : 'info',\n errorclass : 'displayError',\n isActive : true,\n haserror : false\n }\n });\n </script>\n </body>\n</html>" }, { "code": null, "e": 10093, "s": 9956, "text": "We have used two variables isActive and haserror and the same is used for the div while class binding as shown in the following div tag." }, { "code": null, "e": 10187, "s": 10093, "text": "<div v-bind:class = \"[isActive ? infoclass : '', haserror ? errorclass : '']\">{{title}}</div>" }, { "code": null, "e": 10334, "s": 10187, "text": "If isActive is true, then infoclass will be assigned to it. The same goes for haserror, if it is true, then only errorClass will be applied to it." }, { "code": null, "e": 10409, "s": 10334, "text": "Now, let us make haserror variable as true and isActive variable as false." }, { "code": null, "e": 10564, "s": 10409, "text": "We will now add v-bind for classes in the components. In the following example, we have added a class to the component template and also to the component." }, { "code": null, "e": 11801, "s": 10564, "text": "<html>\n <head>\n <title>VueJs Instance</title>\n <script type = \"text/javascript\" src = \"js/vue.js\"></script>\n </head>\n <body>\n <style>\n .info {\n color: #00529B;\n background-color: #BDE5F8;\n }\n div {\n margin: 10px 0;\n padding: 12px;\n font-size : 25px;\n }\n .active {\n color: #4F8A10;\n background-color: #DFF2BF;\n }\n .displayError{\n color: #D8000C;\n background-color: #FFBABA;\n }\n </style>\n <div id = \"classbinding\">\n <new_component class = \"active\"></new_component>\n </div>\n <script type = \"text/javascript\">\n var vm = new Vue({\n el: '#classbinding',\n data: {\n title : \"This is class binding example\",\n infoclass : 'info',\n errorclass : 'displayError',\n isActive : false,\n haserror : true\n },\n components:{\n 'new_component' : {\n template : '<div class = \"info\">Class Binding for component</div>'\n }\n }\n });\n </script>\n </body>\n</html>" }, { "code": null, "e": 11883, "s": 11801, "text": "Following is the output in the browser. It applies both the classes to final div." }, { "code": null, "e": 11917, "s": 11883, "text": "<div class = ”info active”></div>" }, { "code": null, "e": 11990, "s": 11917, "text": "Add a variable in the component section to display, based on true/false." }, { "code": null, "e": 13245, "s": 11990, "text": "<html>\n <head>\n <title>VueJs Instance</title>\n <script type = \"text/javascript\" src = \"js/vue.js\"></script>\n </head>\n <body>\n <style>\n .info {\n color: #00529B;\n background-color: #BDE5F8;\n }\n div {\n margin: 10px 0;\n padding: 12px;\n font-size : 25px;\n }\n .active {\n color: #4F8A10;\n background-color: #DFF2BF;\n }\n .displayError{\n color: #D8000C;\n background-color: #FFBABA;\n }\n </style>\n <div id = \"classbinding\">\n <new_component v-bind:class = \"{active:isActive}\"></new_component>\n </div>\n <script type = \"text/javascript\">\n var vm = new Vue({\n el: '#classbinding',\n data: {\n title : \"This is class binding example\",\n infoclass : 'info',\n errorclass : 'displayError',\n isActive : false,\n haserror : true\n },\n components:{\n 'new_component' : {\n template : '<div class = \"info\">Class Binding for component</div>'\n }\n }\n });\n </script>\n </body>\n</html>" }, { "code": null, "e": 13374, "s": 13245, "text": "Since the variable is false, the active class is not applied and the info class is applied as shown in the following screenshot." }, { "code": null, "e": 13382, "s": 13374, "text": "Example" }, { "code": null, "e": 13958, "s": 13382, "text": "<html>\n <head>\n <title>VueJs Instance</title>\n <script type = \"text/javascript\" src = \"js/vue.js\"></script>\n </head>\n <body>\n <div id = \"databinding\">\n <div v-bind:style = \"{ color: activeColor, fontSize: fontSize + 'px' }\">{{title}}</div>\n </div>\n <script type = \"text/javascript\">\n var vm = new Vue({\n el: '#databinding',\n data: {\n title : \"Inline style Binding\",\n activeColor: 'red',\n fontSize :'30'\n }\n });\n </script>\n </body>\n</html>" }, { "code": null, "e": 13965, "s": 13958, "text": "Output" }, { "code": null, "e": 14067, "s": 13965, "text": "In the above example, for the div, the style is applied and the data is fetched from the data object." }, { "code": null, "e": 14241, "s": 14067, "text": "<div v-bind:style = \"{ color: activeColor, fontSize: fontSize + 'px' }\">{{title}}</div>\ndata: {\n title : \"Inline style Binding\",\n activeColor: 'red',\n fontSize :'30'\n}" }, { "code": null, "e": 14357, "s": 14241, "text": "We can also do the same thing by assigning all the values to a variable and then assigning the variable to the div." }, { "code": null, "e": 14365, "s": 14357, "text": "Example" }, { "code": null, "e": 14947, "s": 14365, "text": "<html>\n <head>\n <title>VueJs Instance</title>\n <script type = \"text/javascript\" src = \"js/vue.js\"></script>\n </head>\n <body>\n <div id = \"databinding\">\n <div v-bind:style = \"styleobj\">{{title}}</div>\n </div>\n <script type = \"text/javascript\">\n var vm = new Vue({\n el: '#databinding',\n data: {\n title : \"Inline style Binding\",\n styleobj : {\n color: 'red',\n fontSize :'40px'\n }\n }\n });\n </script>\n </body>\n</html>" }, { "code": null, "e": 15053, "s": 14947, "text": "The color and the fontSize is assigned to the object called styleobj and the same is assigned to the div." }, { "code": null, "e": 15100, "s": 15053, "text": "<div v-bind:style = \"styleobj\">{{title}}</div>" }, { "code": null, "e": 15107, "s": 15100, "text": "Output" }, { "code": null, "e": 15286, "s": 15107, "text": "So far in the example we have created, we have seen v-model binding the input text element and the value binded to a variable assigned. Let’s learn more about it in this section." }, { "code": null, "e": 16165, "s": 15286, "text": "<html>\n <head>\n <title>VueJs Instance</title>\n <script type = \"text/javascript\" src = \"js/vue.js\"></script>\n </head>\n <body>\n <div id = \"databinding\">\n <h3>TEXTBOX</h3>\n <input v-model = \"name\" placeholder = \"Enter Name\" />\n <h3>Name entered is : {{name}}</h3>\n <hr/>\n <h3>Textarea</h3>\n <textarea v-model = \"textmessage\" placeholder = \"Add Details\"></textarea>\n <h1><p>{{textmessage}}</p></h1>\n <hr/>\n <h3>Checkbox</h3>\n <input type = \"checkbox\" id = \"checkbox\" v-model = \"checked\"> {{checked}}\n </div>\n <script type = \"text/javascript\">\n var vm = new Vue({\n el: '#databinding',\n data: {\n name:'',\n textmessage:'',\n checked : false\n }\n });\n </script>\n </body>\n</html>" }, { "code": null, "e": 16339, "s": 16165, "text": "Whatever we type in the texbox is displayed below. v-model is assigned the value name and the name is displayed in {{name}}, which displays whatever is typed in the textbox." }, { "code": null, "e": 16396, "s": 16339, "text": "Let’s checkout out some more examples and how to use it." }, { "code": null, "e": 16404, "s": 16396, "text": "Example" }, { "code": null, "e": 17496, "s": 16404, "text": "<html>\n <head>\n <title>VueJs Instance</title>\n <script type = \"text/javascript\" src = \"js/vue.js\"></script>\n </head>\n <body>\n <div id = \"databinding\">\n <h3>Radio</h3>\n <input type = \"radio\" id = \"black\" value = \"Black\" v-model = \"picked\">Black\n <input type = \"radio\" id = \"white\" value = \"White\" v-model = \"picked\">White\n <h3>Radio element clicked : {{picked}} </h3>\n <hr/>\n <h3>Select</h3>\n <select v-model = \"languages\">\n <option disabled value = \"\">Please select one</option>\n <option>Java</option>\n <option>Javascript</option>\n <option>Php</option>\n <option>C</option>\n <option>C++</option>\n </select>\n <h3>Languages Selected is : {{ languages }}</h3>\n <hr/>\n </div>\n <script type = \"text/javascript\">\n var vm = new Vue({\n el: '#databinding',\n data: {\n picked : 'White',\n languages : \"Java\"\n }\n });\n </script>\n </body>\n</html>" }, { "code": null, "e": 17503, "s": 17496, "text": "Output" }, { "code": null, "e": 17573, "s": 17503, "text": "We have used three modifiers in the example - trim, number, and lazy." }, { "code": null, "e": 17581, "s": 17573, "text": "Example" }, { "code": null, "e": 18441, "s": 17581, "text": "<html>\n <head>\n <title>VueJs Instance</title>\n <script type = \"text/javascript\" src = \"js/vue.js\"></script>\n </head>\n <body>\n <div id = \"databinding\">\n <span style = \"font-size:25px;\">Enter Age:</span> <input v-model.number = \"age\" type = \"number\">\n <br/>\n <span style = \"font-size:25px;\">Enter Message:</span> <input v-model.lazy = \"msg\">\n <h3>Display Message : {{msg}}</h3>\n <br/>\n <span style = \"font-size:25px;\">Enter Message : </span><input v-model.trim = \"message\">\n <h3>Display Message : {{message}}</h3>\n </div>\n <script type = \"text/javascript\">\n var vm = new Vue({\n el: '#databinding',\n data: {\n age : 0,\n msg: '',\n message : ''\n }\n });\n </script>\n </body>\n</html>" }, { "code": null, "e": 18448, "s": 18441, "text": "Output" }, { "code": null, "e": 18544, "s": 18448, "text": "Number modifier allows to only enter numbers. It will not take any other input besides numbers." }, { "code": null, "e": 18641, "s": 18544, "text": "<span style = \"font-size:25px;\">Enter Age:</span> <input v-model.number = \"age\" type = \"number\">" }, { "code": null, "e": 18761, "s": 18641, "text": "Lazy modifier will display the content present in the textbox once it is fully entered and the user leaves the textbox." }, { "code": null, "e": 18844, "s": 18761, "text": "<span style = \"font-size:25px;\">Enter Message:</span> <input v-model.lazy = \"msg\">" }, { "code": null, "e": 18918, "s": 18844, "text": "Trim modifier will remove any spaces entered at the start and at the end." }, { "code": null, "e": 19006, "s": 18918, "text": "<span style = \"font-size:25px;\">Enter Message : </span><input v-model.trim = \"message\">" }, { "code": null, "e": 19013, "s": 19006, "text": " Print" }, { "code": null, "e": 19024, "s": 19013, "text": " Add Notes" } ]
Tryit Editor v3.7
Tryit: Keep getting coordinates when you move
[]
3 Different ways to print Fibonacci series in Java - GeeksforGeeks
19 Jul, 2020 Given a number N, we need to find the Fibonacci Series up to the N term. The Fibonacci series is a series of elements where, the previous two elements are added to get the next element, starting with 0 and 1. Examples: Input: N = 10 Output: 0 1 1 2 3 5 8 13 21 34 Here first term of Fibonacci is 0 and second is 1, so that 3rd term = first(o) + second(1) etc and so on. Input: N = 15 Output: 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 Method 1 – Iterative: Initialize the first and second numbers to 0 and 1. Following this, we print the first and second numbers. Then we send the flow to the iterative while loop where we get the next number by adding the previous two number and simultaneously we swap the first number with the second and the second with the third. Below is the implementation of the above approach: Java // Java program for the above approach class GFG { // Function to print N Fibonacci Number static void Fibonacci(int N) { int num1 = 0, num2 = 1; int counter = 0; // Iterate till counter is N while (counter < N) { // Print the number System.out.print(num1 + " "); // Swap int num3 = num2 + num1; num1 = num2; num2 = num3; counter = counter + 1; } } // Driver Code public static void main(String args[]) { // Given Number N int N = 10; // Function Call Fibonacci(N); }} 0 1 1 2 3 5 8 13 21 34 Time Complexity: O(N) Auxiliary Space: O(1) Method 2 – Using Recursion: Since Fibonacci Number is the summation of the two previous numbers. We can use recursion as per the following condition: Get the number whose Fibonacci series needs to be calculated.Recursively iterate from value N to 1:Base case: If the value called recursively is less than 1, the return 1 the function.Recursive call: If the base case is not met, then recursively call for previous two value as:recursive_function(N – 1) + recursive_function(N – 2);Return statement: At each recursive call(except the base case), return the recursive function for the previous two value as:recursive_function(N – 1) + recursive_function(N – 2); Get the number whose Fibonacci series needs to be calculated. Recursively iterate from value N to 1:Base case: If the value called recursively is less than 1, the return 1 the function.Recursive call: If the base case is not met, then recursively call for previous two value as:recursive_function(N – 1) + recursive_function(N – 2);Return statement: At each recursive call(except the base case), return the recursive function for the previous two value as:recursive_function(N – 1) + recursive_function(N – 2); Base case: If the value called recursively is less than 1, the return 1 the function. Recursive call: If the base case is not met, then recursively call for previous two value as:recursive_function(N – 1) + recursive_function(N – 2); recursive_function(N – 1) + recursive_function(N – 2); Return statement: At each recursive call(except the base case), return the recursive function for the previous two value as:recursive_function(N – 1) + recursive_function(N – 2); recursive_function(N – 1) + recursive_function(N – 2); Below is the implementation of the above approach: Java // Recursive implementation of// Fibonacci Series class GFG { // Function to print the fibonacci series static int fib(int n) { // Base Case if (n <= 1) return n; // Recursive call return fib(n - 1) + fib(n - 2); } // Driver Code public static void main(String args[]) { // Given Number N int N = 10; // Print the first N numbers for (int i = 0; i < N; i++) { System.out.print(fib(i) + " "); } }} 0 1 1 2 3 5 8 13 21 34 Time Complexity: O(2N) Auxiliary Space: O(1) Method 3 – Using Dynamic Programming: We can avoid the repeated work done in method 2 by storing the Fibonacci numbers calculated so far. Below are the steps: Create an array arr[] of size N.Initialize arr[0] = 0, arr[1] = 1.Iterate over [2, N] and update the array arr[] as:arr[i] = arr[i – 2] + arr[i – 1]Print the value of arr[N]. Create an array arr[] of size N. Initialize arr[0] = 0, arr[1] = 1. Iterate over [2, N] and update the array arr[] as:arr[i] = arr[i – 2] + arr[i – 1] arr[i] = arr[i – 2] + arr[i – 1] Print the value of arr[N]. Below is the implementation of the above approach: Java // Dynamic Programming approach for// Fibonacci Series class fibonacci { // Function to find the fibonacci Series static int fib(int n) { // Declare an array to store // Fibonacci numbers. // 1 extra to handle case, n = 0 int f[] = new int[n + 2]; int i; // 0th and 1st number of // the series are 0 and 1 f[0] = 0; f[1] = 1; for (i = 2; i <= n; i++) { // Add the previous 2 numbers // in the series and store it f[i] = f[i - 1] + f[i - 2]; } // Nth Fibonacci Number return f[n]; } public static void main(String args[]) { // Given Number N int N = 10; // Print first 10 term for (int i = 0; i < N; i++) System.out.print(fib(i) + " "); }} 0 1 1 2 3 5 8 13 21 34 Time Complexity: O(N) Auxiliary Space: O(N) Fibonacci series Dynamic Programming Greedy Java Programs Mathematical Recursion Searching Searching Dynamic Programming Greedy Mathematical Recursion series Fibonacci Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Bellman–Ford Algorithm | DP-23 Floyd Warshall Algorithm | DP-16 Matrix Chain Multiplication | DP-8 Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Overlapping Subproblems Property in Dynamic Programming | DP-1 Dijkstra's shortest path algorithm | Greedy Algo-7 Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5 Program for array rotation Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2 Huffman Coding | Greedy Algo-3
[ { "code": null, "e": 24221, "s": 24193, "text": "\n19 Jul, 2020" }, { "code": null, "e": 24294, "s": 24221, "text": "Given a number N, we need to find the Fibonacci Series up to the N term." }, { "code": null, "e": 24431, "s": 24294, "text": "The Fibonacci series is a series of elements where, the previous two elements are added to get the next element, starting with 0 and 1. " }, { "code": null, "e": 24442, "s": 24431, "text": "Examples: " }, { "code": null, "e": 24593, "s": 24442, "text": "Input: N = 10 Output: 0 1 1 2 3 5 8 13 21 34 Here first term of Fibonacci is 0 and second is 1, so that 3rd term = first(o) + second(1) etc and so on." }, { "code": null, "e": 24658, "s": 24593, "text": "Input: N = 15 Output: 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 " }, { "code": null, "e": 24991, "s": 24658, "text": "Method 1 – Iterative: Initialize the first and second numbers to 0 and 1. Following this, we print the first and second numbers. Then we send the flow to the iterative while loop where we get the next number by adding the previous two number and simultaneously we swap the first number with the second and the second with the third." }, { "code": null, "e": 25042, "s": 24991, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 25047, "s": 25042, "text": "Java" }, { "code": "// Java program for the above approach class GFG { // Function to print N Fibonacci Number static void Fibonacci(int N) { int num1 = 0, num2 = 1; int counter = 0; // Iterate till counter is N while (counter < N) { // Print the number System.out.print(num1 + \" \"); // Swap int num3 = num2 + num1; num1 = num2; num2 = num3; counter = counter + 1; } } // Driver Code public static void main(String args[]) { // Given Number N int N = 10; // Function Call Fibonacci(N); }}", "e": 25695, "s": 25047, "text": null }, { "code": null, "e": 25719, "s": 25695, "text": "0 1 1 2 3 5 8 13 21 34\n" }, { "code": null, "e": 25763, "s": 25719, "text": "Time Complexity: O(N) Auxiliary Space: O(1)" }, { "code": null, "e": 25913, "s": 25763, "text": "Method 2 – Using Recursion: Since Fibonacci Number is the summation of the two previous numbers. We can use recursion as per the following condition:" }, { "code": null, "e": 26423, "s": 25913, "text": "Get the number whose Fibonacci series needs to be calculated.Recursively iterate from value N to 1:Base case: If the value called recursively is less than 1, the return 1 the function.Recursive call: If the base case is not met, then recursively call for previous two value as:recursive_function(N – 1) + recursive_function(N – 2);Return statement: At each recursive call(except the base case), return the recursive function for the previous two value as:recursive_function(N – 1) + recursive_function(N – 2);" }, { "code": null, "e": 26485, "s": 26423, "text": "Get the number whose Fibonacci series needs to be calculated." }, { "code": null, "e": 26934, "s": 26485, "text": "Recursively iterate from value N to 1:Base case: If the value called recursively is less than 1, the return 1 the function.Recursive call: If the base case is not met, then recursively call for previous two value as:recursive_function(N – 1) + recursive_function(N – 2);Return statement: At each recursive call(except the base case), return the recursive function for the previous two value as:recursive_function(N – 1) + recursive_function(N – 2);" }, { "code": null, "e": 27020, "s": 26934, "text": "Base case: If the value called recursively is less than 1, the return 1 the function." }, { "code": null, "e": 27168, "s": 27020, "text": "Recursive call: If the base case is not met, then recursively call for previous two value as:recursive_function(N – 1) + recursive_function(N – 2);" }, { "code": null, "e": 27223, "s": 27168, "text": "recursive_function(N – 1) + recursive_function(N – 2);" }, { "code": null, "e": 27402, "s": 27223, "text": "Return statement: At each recursive call(except the base case), return the recursive function for the previous two value as:recursive_function(N – 1) + recursive_function(N – 2);" }, { "code": null, "e": 27457, "s": 27402, "text": "recursive_function(N – 1) + recursive_function(N – 2);" }, { "code": null, "e": 27508, "s": 27457, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 27513, "s": 27508, "text": "Java" }, { "code": "// Recursive implementation of// Fibonacci Series class GFG { // Function to print the fibonacci series static int fib(int n) { // Base Case if (n <= 1) return n; // Recursive call return fib(n - 1) + fib(n - 2); } // Driver Code public static void main(String args[]) { // Given Number N int N = 10; // Print the first N numbers for (int i = 0; i < N; i++) { System.out.print(fib(i) + \" \"); } }}", "e": 28044, "s": 27513, "text": null }, { "code": null, "e": 28068, "s": 28044, "text": "0 1 1 2 3 5 8 13 21 34\n" }, { "code": null, "e": 28114, "s": 28068, "text": "Time Complexity: O(2N) Auxiliary Space: O(1)" }, { "code": null, "e": 28273, "s": 28114, "text": "Method 3 – Using Dynamic Programming: We can avoid the repeated work done in method 2 by storing the Fibonacci numbers calculated so far. Below are the steps:" }, { "code": null, "e": 28448, "s": 28273, "text": "Create an array arr[] of size N.Initialize arr[0] = 0, arr[1] = 1.Iterate over [2, N] and update the array arr[] as:arr[i] = arr[i – 2] + arr[i – 1]Print the value of arr[N]." }, { "code": null, "e": 28481, "s": 28448, "text": "Create an array arr[] of size N." }, { "code": null, "e": 28516, "s": 28481, "text": "Initialize arr[0] = 0, arr[1] = 1." }, { "code": null, "e": 28599, "s": 28516, "text": "Iterate over [2, N] and update the array arr[] as:arr[i] = arr[i – 2] + arr[i – 1]" }, { "code": null, "e": 28632, "s": 28599, "text": "arr[i] = arr[i – 2] + arr[i – 1]" }, { "code": null, "e": 28659, "s": 28632, "text": "Print the value of arr[N]." }, { "code": null, "e": 28710, "s": 28659, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 28715, "s": 28710, "text": "Java" }, { "code": "// Dynamic Programming approach for// Fibonacci Series class fibonacci { // Function to find the fibonacci Series static int fib(int n) { // Declare an array to store // Fibonacci numbers. // 1 extra to handle case, n = 0 int f[] = new int[n + 2]; int i; // 0th and 1st number of // the series are 0 and 1 f[0] = 0; f[1] = 1; for (i = 2; i <= n; i++) { // Add the previous 2 numbers // in the series and store it f[i] = f[i - 1] + f[i - 2]; } // Nth Fibonacci Number return f[n]; } public static void main(String args[]) { // Given Number N int N = 10; // Print first 10 term for (int i = 0; i < N; i++) System.out.print(fib(i) + \" \"); }}", "e": 29560, "s": 28715, "text": null }, { "code": null, "e": 29584, "s": 29560, "text": "0 1 1 2 3 5 8 13 21 34\n" }, { "code": null, "e": 29629, "s": 29584, "text": "Time Complexity: O(N) Auxiliary Space: O(N) " }, { "code": null, "e": 29639, "s": 29629, "text": "Fibonacci" }, { "code": null, "e": 29646, "s": 29639, "text": "series" }, { "code": null, "e": 29666, "s": 29646, "text": "Dynamic Programming" }, { "code": null, "e": 29673, "s": 29666, "text": "Greedy" }, { "code": null, "e": 29687, "s": 29673, "text": "Java Programs" }, { "code": null, "e": 29700, "s": 29687, "text": "Mathematical" }, { "code": null, "e": 29710, "s": 29700, "text": "Recursion" }, { "code": null, "e": 29720, "s": 29710, "text": "Searching" }, { "code": null, "e": 29730, "s": 29720, "text": "Searching" }, { "code": null, "e": 29750, "s": 29730, "text": "Dynamic Programming" }, { "code": null, "e": 29757, "s": 29750, "text": "Greedy" }, { "code": null, "e": 29770, "s": 29757, "text": "Mathematical" }, { "code": null, "e": 29780, "s": 29770, "text": "Recursion" }, { "code": null, "e": 29787, "s": 29780, "text": "series" }, { "code": null, "e": 29797, "s": 29787, "text": "Fibonacci" }, { "code": null, "e": 29895, "s": 29797, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29904, "s": 29895, "text": "Comments" }, { "code": null, "e": 29917, "s": 29904, "text": "Old Comments" }, { "code": null, "e": 29948, "s": 29917, "text": "Bellman–Ford Algorithm | DP-23" }, { "code": null, "e": 29981, "s": 29948, "text": "Floyd Warshall Algorithm | DP-16" }, { "code": null, "e": 30016, "s": 29981, "text": "Matrix Chain Multiplication | DP-8" }, { "code": null, "e": 30084, "s": 30016, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" }, { "code": null, "e": 30147, "s": 30084, "text": "Overlapping Subproblems Property in Dynamic Programming | DP-1" }, { "code": null, "e": 30198, "s": 30147, "text": "Dijkstra's shortest path algorithm | Greedy Algo-7" }, { "code": null, "e": 30249, "s": 30198, "text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5" }, { "code": null, "e": 30276, "s": 30249, "text": "Program for array rotation" }, { "code": null, "e": 30334, "s": 30276, "text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2" } ]
Python program to print rangoli pattern using alphabets
Suppose we have a number n. We have to create alphabet rangoli of n x n size. n must be within 1 and 26 and it will start from a and end at z when n is 26. So, if the input is like 5, then the output will be --------e-------- ------e-d-e------ ----e-d-c-d-e---- --e-d-c-b-c-d-e-- e-d-c-b-a-b-c-d-e --e-d-c-b-c-d-e-- ----e-d-c-d-e---- ------e-d-e------ --------e-------- To solve this, we will follow these steps − for i in range n-1 to 0, decrease by 1, dofor j in range 0 to i-1, doprint "--"for j in range n-1 to i+1, decrease by 1, doprint character whose ASCII is j+97 and print extra "-" at the endfor j in range i to n-1, doif j is not same as n-1, thenprint character whose ASCII is j+97 and print extra "-" at the endotherwise,print character whose ASCII is j+97for j in range 0 to 2*i - 1, doprint "-" at the endgo for next line for j in range 0 to i-1, doprint "--" print "--" for j in range n-1 to i+1, decrease by 1, doprint character whose ASCII is j+97 and print extra "-" at the end print character whose ASCII is j+97 and print extra "-" at the end for j in range i to n-1, doif j is not same as n-1, thenprint character whose ASCII is j+97 and print extra "-" at the endotherwise,print character whose ASCII is j+97 if j is not same as n-1, thenprint character whose ASCII is j+97 and print extra "-" at the end print character whose ASCII is j+97 and print extra "-" at the end otherwise,print character whose ASCII is j+97 print character whose ASCII is j+97 for j in range 0 to 2*i - 1, doprint "-" at the end print "-" at the end go for next line for i in range 1 to n-1, dofor j in range 0 to i, doprint "--"for j in range n-1 to i+1, decrease by 1, doprint character whose ASCII is j+97 and print extra "-" at the endfor j in range i to n-1, doif j is not same as n-1, thenprint character whose ASCII is j+97 and print extra "-" at the endotherwise,print character whose ASCII is j+97for j in range 0 to 2*i - 1, doprint "-" at the endgo to the next line for j in range 0 to i, doprint "--" print "--" for j in range n-1 to i+1, decrease by 1, doprint character whose ASCII is j+97 and print extra "-" at the end print character whose ASCII is j+97 and print extra "-" at the end for j in range i to n-1, doif j is not same as n-1, thenprint character whose ASCII is j+97 and print extra "-" at the endotherwise,print character whose ASCII is j+97 if j is not same as n-1, thenprint character whose ASCII is j+97 and print extra "-" at the end print character whose ASCII is j+97 and print extra "-" at the end otherwise,print character whose ASCII is j+97 print character whose ASCII is j+97 for j in range 0 to 2*i - 1, doprint "-" at the end print "-" at the end go to the next line Let us see the following implementation to get better understanding def solve(n): for i in range(n-1,-1,-1): for j in range(i): print(end="--") for j in range(n-1,i,-1): print(chr(j+97),end="-") for j in range(i,n): if j != n-1: print(chr(j+97),end="-") else: print(chr(j+97),end="") for j in range(2*i): print(end="-") print() for i in range(1,n): for j in range(i): print(end="--") for j in range(n-1,i,-1): print(chr(j+97),end="-") for j in range(i,n): if j != n-1: print(chr(j+97),end="-") else: print(chr(j+97),end="") for j in range(2*i): print(end="-") print() n = 8 solve(n) 8 --------------h-------------- ------------h-g-h------------ ----------h-g-f-g-h---------- --------h-g-f-e-f-g-h-------- ------h-g-f-e-d-e-f-g-h------ ----h-g-f-e-d-c-d-e-f-g-h---- --h-g-f-e-d-c-b-c-d-e-f-g-h-- h-g-f-e-d-c-b-a-b-c-d-e-f-g-h --h-g-f-e-d-c-b-c-d-e-f-g-h-- ----h-g-f-e-d-c-d-e-f-g-h---- ------h-g-f-e-d-e-f-g-h------ --------h-g-f-e-f-g-h-------- ----------h-g-f-g-h---------- ------------h-g-h------------ --------------h--------------
[ { "code": null, "e": 1218, "s": 1062, "text": "Suppose we have a number n. We have to create alphabet rangoli of n x n size. n must be within 1 and 26 and it will start from a and end at z when n is 26." }, { "code": null, "e": 1270, "s": 1218, "text": "So, if the input is like 5, then the output will be" }, { "code": null, "e": 1432, "s": 1270, "text": "--------e--------\n------e-d-e------\n----e-d-c-d-e----\n--e-d-c-b-c-d-e--\ne-d-c-b-a-b-c-d-e\n--e-d-c-b-c-d-e--\n----e-d-c-d-e----\n------e-d-e------\n--------e--------" }, { "code": null, "e": 1476, "s": 1432, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1900, "s": 1476, "text": "for i in range n-1 to 0, decrease by 1, dofor j in range 0 to i-1, doprint \"--\"for j in range n-1 to i+1, decrease by 1, doprint character whose ASCII is j+97 and print extra \"-\" at the endfor j in range i to n-1, doif j is not same as n-1, thenprint character whose ASCII is j+97 and print extra \"-\" at the endotherwise,print character whose ASCII is j+97for j in range 0 to 2*i - 1, doprint \"-\" at the endgo for next line" }, { "code": null, "e": 1938, "s": 1900, "text": "for j in range 0 to i-1, doprint \"--\"" }, { "code": null, "e": 1949, "s": 1938, "text": "print \"--\"" }, { "code": null, "e": 2060, "s": 1949, "text": "for j in range n-1 to i+1, decrease by 1, doprint character whose ASCII is j+97 and print extra \"-\" at the end" }, { "code": null, "e": 2127, "s": 2060, "text": "print character whose ASCII is j+97 and print extra \"-\" at the end" }, { "code": null, "e": 2295, "s": 2127, "text": "for j in range i to n-1, doif j is not same as n-1, thenprint character whose ASCII is j+97 and print extra \"-\" at the endotherwise,print character whose ASCII is j+97" }, { "code": null, "e": 2391, "s": 2295, "text": "if j is not same as n-1, thenprint character whose ASCII is j+97 and print extra \"-\" at the end" }, { "code": null, "e": 2458, "s": 2391, "text": "print character whose ASCII is j+97 and print extra \"-\" at the end" }, { "code": null, "e": 2504, "s": 2458, "text": "otherwise,print character whose ASCII is j+97" }, { "code": null, "e": 2540, "s": 2504, "text": "print character whose ASCII is j+97" }, { "code": null, "e": 2592, "s": 2540, "text": "for j in range 0 to 2*i - 1, doprint \"-\" at the end" }, { "code": null, "e": 2613, "s": 2592, "text": "print \"-\" at the end" }, { "code": null, "e": 2630, "s": 2613, "text": "go for next line" }, { "code": null, "e": 3040, "s": 2630, "text": "for i in range 1 to n-1, dofor j in range 0 to i, doprint \"--\"for j in range n-1 to i+1, decrease by 1, doprint character whose ASCII is j+97 and print extra \"-\" at the endfor j in range i to n-1, doif j is not same as n-1, thenprint character whose ASCII is j+97 and print extra \"-\" at the endotherwise,print character whose ASCII is j+97for j in range 0 to 2*i - 1, doprint \"-\" at the endgo to the next line" }, { "code": null, "e": 3076, "s": 3040, "text": "for j in range 0 to i, doprint \"--\"" }, { "code": null, "e": 3087, "s": 3076, "text": "print \"--\"" }, { "code": null, "e": 3198, "s": 3087, "text": "for j in range n-1 to i+1, decrease by 1, doprint character whose ASCII is j+97 and print extra \"-\" at the end" }, { "code": null, "e": 3265, "s": 3198, "text": "print character whose ASCII is j+97 and print extra \"-\" at the end" }, { "code": null, "e": 3433, "s": 3265, "text": "for j in range i to n-1, doif j is not same as n-1, thenprint character whose ASCII is j+97 and print extra \"-\" at the endotherwise,print character whose ASCII is j+97" }, { "code": null, "e": 3529, "s": 3433, "text": "if j is not same as n-1, thenprint character whose ASCII is j+97 and print extra \"-\" at the end" }, { "code": null, "e": 3596, "s": 3529, "text": "print character whose ASCII is j+97 and print extra \"-\" at the end" }, { "code": null, "e": 3642, "s": 3596, "text": "otherwise,print character whose ASCII is j+97" }, { "code": null, "e": 3678, "s": 3642, "text": "print character whose ASCII is j+97" }, { "code": null, "e": 3730, "s": 3678, "text": "for j in range 0 to 2*i - 1, doprint \"-\" at the end" }, { "code": null, "e": 3751, "s": 3730, "text": "print \"-\" at the end" }, { "code": null, "e": 3771, "s": 3751, "text": "go to the next line" }, { "code": null, "e": 3839, "s": 3771, "text": "Let us see the following implementation to get better understanding" }, { "code": null, "e": 4556, "s": 3839, "text": "def solve(n):\n for i in range(n-1,-1,-1):\n for j in range(i):\n print(end=\"--\")\n for j in range(n-1,i,-1):\n print(chr(j+97),end=\"-\")\n for j in range(i,n):\n if j != n-1:\n print(chr(j+97),end=\"-\")\n else:\n print(chr(j+97),end=\"\")\n for j in range(2*i):\n print(end=\"-\")\n print()\n for i in range(1,n):\n for j in range(i):\n print(end=\"--\")\n for j in range(n-1,i,-1):\n print(chr(j+97),end=\"-\")\n for j in range(i,n):\n if j != n-1:\n print(chr(j+97),end=\"-\")\n else:\n print(chr(j+97),end=\"\")\n for j in range(2*i):\n print(end=\"-\")\n print()\n\nn = 8\nsolve(n)" }, { "code": null, "e": 4558, "s": 4556, "text": "8" }, { "code": null, "e": 5008, "s": 4558, "text": "--------------h--------------\n------------h-g-h------------\n----------h-g-f-g-h----------\n--------h-g-f-e-f-g-h--------\n------h-g-f-e-d-e-f-g-h------\n----h-g-f-e-d-c-d-e-f-g-h----\n--h-g-f-e-d-c-b-c-d-e-f-g-h--\nh-g-f-e-d-c-b-a-b-c-d-e-f-g-h\n--h-g-f-e-d-c-b-c-d-e-f-g-h--\n----h-g-f-e-d-c-d-e-f-g-h----\n------h-g-f-e-d-e-f-g-h------\n--------h-g-f-e-f-g-h--------\n----------h-g-f-g-h----------\n------------h-g-h------------\n--------------h--------------" } ]
Python : __delete__ vs __del__
27 Dec, 2019 Both __delete__ and __del__ are dunder or magic methods in Python. Dunder or magic methods in Python are the methods having two prefix and suffix underscores in the method name. Dunder here means “Double Under (Underscores)”. These are commonly used for operator overloading. __del__ is a destructor method which is called as soon as all references of the object are deleted i.e when an object is garbage collected. Syntax: def __del__(self): body of destructor . . Example: Here is the simple example of destructor. By using del keyword we deleted the all references of object ‘obj’, therefore destructor invoked automatically. # Python program to demonstrate# __del__ class Example: # Initializing def __init__(self): print("Example Instance.") # Calling destructor def __del__(self): print("Destructor called, Example deleted.") obj = Example() del obj Example Instance. Destructor called, Example deleted. Note : The destructor was called after the program ended or when all the references to object are deleted i.e when the reference count becomes zero, not when object went out of scope. __delete__ is used to delete the attribute of an instance i.e removing the value of attribute present in the owner class for an instance. Note: This method only deletes the attribute which is a descriptor. Syntax: def __delete__(self, instance): body of delete . . Example: # Python program to demonstrate# __delete__ class Example(object): # Initializing def __init__(self): print("Example Instance.") # Calling __delete__ def __delete__(self, instance): print ("Deleted in Example object.") # Creating object of Example# class as an descriptor attribute# of this classclass Foo(object): exp = Example() # Driver's codef = Foo()del f.exp Example Instance. Deleted in Example object. Example: A combine example of __del__ and __delete__. # Python program to demonstrate# __del__ and __delete__ class Example(object): # Initializing def __init__(self): self.value = '' # deletes an attribute def __delete__(self, instance): print ("Inside __delete__") # Destructor def __del__(self): print("Inside __del__") class Foo(object): exp = Example() # Driver's codef = Foo()del f.exp Output: Inside __delete__ Inside __del__ python-oop-concepts Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON Python | os.path.join() method How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 28, "s": 0, "text": "\n27 Dec, 2019" }, { "code": null, "e": 304, "s": 28, "text": "Both __delete__ and __del__ are dunder or magic methods in Python. Dunder or magic methods in Python are the methods having two prefix and suffix underscores in the method name. Dunder here means “Double Under (Underscores)”. These are commonly used for operator overloading." }, { "code": null, "e": 444, "s": 304, "text": "__del__ is a destructor method which is called as soon as all references of the object are deleted i.e when an object is garbage collected." }, { "code": null, "e": 452, "s": 444, "text": "Syntax:" }, { "code": null, "e": 507, "s": 452, "text": "def __del__(self):\n body of destructor\n .\n .\n" }, { "code": null, "e": 670, "s": 507, "text": "Example: Here is the simple example of destructor. By using del keyword we deleted the all references of object ‘obj’, therefore destructor invoked automatically." }, { "code": "# Python program to demonstrate# __del__ class Example: # Initializing def __init__(self): print(\"Example Instance.\") # Calling destructor def __del__(self): print(\"Destructor called, Example deleted.\") obj = Example() del obj ", "e": 940, "s": 670, "text": null }, { "code": null, "e": 995, "s": 940, "text": "Example Instance.\nDestructor called, Example deleted.\n" }, { "code": null, "e": 1179, "s": 995, "text": "Note : The destructor was called after the program ended or when all the references to object are deleted i.e when the reference count becomes zero, not when object went out of scope." }, { "code": null, "e": 1317, "s": 1179, "text": "__delete__ is used to delete the attribute of an instance i.e removing the value of attribute present in the owner class for an instance." }, { "code": null, "e": 1385, "s": 1317, "text": "Note: This method only deletes the attribute which is a descriptor." }, { "code": null, "e": 1393, "s": 1385, "text": "Syntax:" }, { "code": null, "e": 1457, "s": 1393, "text": "def __delete__(self, instance):\n body of delete\n .\n .\n" }, { "code": null, "e": 1466, "s": 1457, "text": "Example:" }, { "code": "# Python program to demonstrate# __delete__ class Example(object): # Initializing def __init__(self): print(\"Example Instance.\") # Calling __delete__ def __delete__(self, instance): print (\"Deleted in Example object.\") # Creating object of Example# class as an descriptor attribute# of this classclass Foo(object): exp = Example() # Driver's codef = Foo()del f.exp", "e": 1871, "s": 1466, "text": null }, { "code": null, "e": 1917, "s": 1871, "text": "Example Instance.\nDeleted in Example object.\n" }, { "code": null, "e": 1971, "s": 1917, "text": "Example: A combine example of __del__ and __delete__." }, { "code": "# Python program to demonstrate# __del__ and __delete__ class Example(object): # Initializing def __init__(self): self.value = '' # deletes an attribute def __delete__(self, instance): print (\"Inside __delete__\") # Destructor def __del__(self): print(\"Inside __del__\") class Foo(object): exp = Example() # Driver's codef = Foo()del f.exp", "e": 2380, "s": 1971, "text": null }, { "code": null, "e": 2388, "s": 2380, "text": "Output:" }, { "code": null, "e": 2422, "s": 2388, "text": "Inside __delete__\nInside __del__\n" }, { "code": null, "e": 2442, "s": 2422, "text": "python-oop-concepts" }, { "code": null, "e": 2449, "s": 2442, "text": "Python" }, { "code": null, "e": 2468, "s": 2449, "text": "Technical Scripter" }, { "code": null, "e": 2566, "s": 2468, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2598, "s": 2566, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2625, "s": 2598, "text": "Python Classes and Objects" }, { "code": null, "e": 2646, "s": 2625, "text": "Python OOPs Concepts" }, { "code": null, "e": 2669, "s": 2646, "text": "Introduction To PYTHON" }, { "code": null, "e": 2700, "s": 2669, "text": "Python | os.path.join() method" }, { "code": null, "e": 2756, "s": 2700, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2798, "s": 2756, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2840, "s": 2798, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2879, "s": 2840, "text": "Python | Get unique values from a list" } ]
Lodash _.keyBy() Method
07 Sep, 2020 Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, collection, strings, objects, numbers etc. The _.keyBy() method creates an object that composed of keys generated from the results of running an each element of collection through iteratee. Corresponding value of each key is the last element that responsible for generating the key. Syntax: _.keyBy( collection, iteratee ) Parameters: This method accepts two parameters as mentioned above and described below: collection: This parameter holds the collection to iterate over. iteratee: This parameter holds the iteratee to transform keys. Return Value: This method returns the composed aggregate object. Example 1: // Requiring the lodash library const _ = require("lodash"); // Original array var array = [ { 'dir': 'left', 'code': 89 }, { 'dir': 'right', 'code': 71 }]; // Use of _.keyBy() methodlet keyby_array = _.keyBy(array, 'dir'); // Printing the output console.log(keyby_array); Output: { 'left': { 'dir': 'left', 'code': 89 }, 'right': { 'dir': 'right', 'code': 71 } } Example 2: // Requiring the lodash library const _ = require("lodash"); // Original array var array = [ { 'dir': 'left', 'code': 89 }, { 'dir': 'right', 'code': 71 }]; // Use of _.keyBy() methodlet keyby_array = _.keyBy(array, function(o) { return String.fromCharCode(o.code);}); // Printing the output console.log(keyby_array); Output: { 'Y': { 'dir': 'left', 'code': 89 }, 'G': { 'dir': 'right', 'code': 71 } } JavaScript-Lodash JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array Hide or show elements in HTML using display property Roadmap to Learn JavaScript For Beginners 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": "\n07 Sep, 2020" }, { "code": null, "e": 179, "s": 28, "text": "Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, collection, strings, objects, numbers etc." }, { "code": null, "e": 419, "s": 179, "text": "The _.keyBy() method creates an object that composed of keys generated from the results of running an each element of collection through iteratee. Corresponding value of each key is the last element that responsible for generating the key." }, { "code": null, "e": 427, "s": 419, "text": "Syntax:" }, { "code": null, "e": 459, "s": 427, "text": "_.keyBy( collection, iteratee )" }, { "code": null, "e": 546, "s": 459, "text": "Parameters: This method accepts two parameters as mentioned above and described below:" }, { "code": null, "e": 611, "s": 546, "text": "collection: This parameter holds the collection to iterate over." }, { "code": null, "e": 674, "s": 611, "text": "iteratee: This parameter holds the iteratee to transform keys." }, { "code": null, "e": 739, "s": 674, "text": "Return Value: This method returns the composed aggregate object." }, { "code": null, "e": 750, "s": 739, "text": "Example 1:" }, { "code": "// Requiring the lodash library const _ = require(\"lodash\"); // Original array var array = [ { 'dir': 'left', 'code': 89 }, { 'dir': 'right', 'code': 71 }]; // Use of _.keyBy() methodlet keyby_array = _.keyBy(array, 'dir'); // Printing the output console.log(keyby_array);", "e": 1035, "s": 750, "text": null }, { "code": null, "e": 1043, "s": 1035, "text": "Output:" }, { "code": null, "e": 1127, "s": 1043, "text": "{ 'left': { 'dir': 'left', 'code': 89 }, \n'right': { 'dir': 'right', 'code': 71 } }" }, { "code": null, "e": 1138, "s": 1127, "text": "Example 2:" }, { "code": "// Requiring the lodash library const _ = require(\"lodash\"); // Original array var array = [ { 'dir': 'left', 'code': 89 }, { 'dir': 'right', 'code': 71 }]; // Use of _.keyBy() methodlet keyby_array = _.keyBy(array, function(o) { return String.fromCharCode(o.code);}); // Printing the output console.log(keyby_array);", "e": 1469, "s": 1138, "text": null }, { "code": null, "e": 1477, "s": 1469, "text": "Output:" }, { "code": null, "e": 1554, "s": 1477, "text": "{ 'Y': { 'dir': 'left', 'code': 89 }, \n'G': { 'dir': 'right', 'code': 71 } }" }, { "code": null, "e": 1572, "s": 1554, "text": "JavaScript-Lodash" }, { "code": null, "e": 1583, "s": 1572, "text": "JavaScript" }, { "code": null, "e": 1600, "s": 1583, "text": "Web Technologies" }, { "code": null, "e": 1698, "s": 1600, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1759, "s": 1698, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 1831, "s": 1759, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 1871, "s": 1831, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 1924, "s": 1871, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 1966, "s": 1924, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 1999, "s": 1966, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2061, "s": 1999, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2122, "s": 2061, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2172, "s": 2122, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Representation of Boolean Functions
15 Jun, 2022 A Boolean function is described by an algebraic expression consisting of binary variables, the constants 0 and 1, and the logic operation symbols For a given set of values of the binary variables involved, the boolean function can have a value of 0 or 1. For example, the boolean function is defined in terms of three binary variables . The function is equal to 1 if and simultaneously or .Every boolean function can be expressed by an algebraic expression, such as one mentioned above, or in terms of a Truth Table. A function may be expressed through several algebraic expressions, on account of them being logically equivalent, but there is only one unique truth table for every function.A Boolean function can be transformed from an algebraic expression into a circuit diagram composed of logic gates connected in a particular structure. Circuit diagram for – Canonical and Standard Forms –Any binary variable can take one of two forms, or . A boolean function can be expressed in terms of binary variables. If all the binary variables are combined together using the AND operation, then there are a total of combinations since each variable can take two forms.Each of the combinations is called a minterm or standard product. A minterm is represented by where is the decimal equivalent of the binary number the minterm is designated.Important Note – In a minterm, the binary variable is un-primed if the variable is 1 and it is primed if the variable is 0 i.e. if the minterm is then that means and .For example, for a boolean function in two variables the minterms are – In a similar way, if the variables are combined together with OR operation, then the term obtained is called a maxterm or standard sum. A maxterm is represented by where is the decimal equivalent of the binary number the maxterm is designated. Important Note – In a maxterm, the binary variable is un-primed if the variable is 0 and it is primed if the variable is 1 i.e. if the maxterm is then that means and .For example, for a boolean function in two variables the maxterms are – Minterms and Maxterms for function in 3 variables – Relation between Minterms and Maxterms – Each minterm is the complement of it’s corresponding maxterm.For example, for a boolean function in two variables – In general or Constructing Boolean Functions – Now that we know what minterms and maxterms are, we can use them to construct boolean expressions. “A Boolean function can be expressed algebraically from a given truth table by forming a minterm for each combination of the variables that produces a 1 in the function and then taking the OR of all those terms.” For example, consider two functions and with the following truth tables – “Boolean functions expressed as a sum of minterms or product of maxterms are said to be in canonical form. Example 1 – Express the following boolean expression in SOP and POS forms- Solution – The expression can be transformed into SOP form by adding missing variables in each term by multiplying by where is the missing variable.It follows from the fact that – On rearranging the minterms in ascending orderIf we want the POS form, we can double negate the SOP form as stated above to get-The SOP and POS forms have a short notation of representation- Standard Forms –Canonical forms are basic forms obtained from the truth table of the function. These forms are usually not used to represent the function as they are cumbersome to write and it is preferable to represent the function in the least number of literals possible.There are two types of standard forms – Sum of Products(SOP)- A boolean expression involving AND terms with one or more literals each, OR’ed together.Product of Sums(POS) A boolean expression involving OR terms with one or more literals each, AND’ed together, e.g.SOP- POS- Note – The above expressions are not equivalent, they are just examples. Sum of Products(SOP)- A boolean expression involving AND terms with one or more literals each, OR’ed together. Product of Sums(POS) A boolean expression involving OR terms with one or more literals each, AND’ed together, e.g.SOP- POS- Note – The above expressions are not equivalent, they are just examples. SOP- POS- Note – The above expressions are not equivalent, they are just examples. GATE CS Corner Questions Practicing the following questions will help you test your knowledge. All questions have been asked in GATE in previous years or in GATE Mock Tests. It is highly recommended that you practice them. 1. GATE CS 2010, Question 62. GATE CS 2008, Question 73. GATE CS 2014 Set-1, Question 17 References- Digital Design 5th Edition, by Morris Mano and Michael Ciletti This article is contributed by Chirag Manwani. 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. AdityaPoddar ManasChhabra2 meetdoshi193 aayushi2402 Discrete Mathematics Digital Electronics & Logic Design Engineering Mathematics GATE CS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. IEEE Standard 754 Floating Point Numbers Difference between RAM and ROM Introduction to memory and memory units Analog to Digital Conversion Difference between Half adder and full adder Relationship between number of nodes and height of binary tree Inequalities in LaTeX Difference between Propositional Logic and Predicate Logic Mathematics | Introduction to Propositional Logic | Set 1 Arrow Symbols in LaTeX
[ { "code": null, "e": 52, "s": 24, "text": "\n15 Jun, 2022" }, { "code": null, "e": 919, "s": 52, "text": "A Boolean function is described by an algebraic expression consisting of binary variables, the constants 0 and 1, and the logic operation symbols For a given set of values of the binary variables involved, the boolean function can have a value of 0 or 1. For example, the boolean function is defined in terms of three binary variables . The function is equal to 1 if and simultaneously or .Every boolean function can be expressed by an algebraic expression, such as one mentioned above, or in terms of a Truth Table. A function may be expressed through several algebraic expressions, on account of them being logically equivalent, but there is only one unique truth table for every function.A Boolean function can be transformed from an algebraic expression into a circuit diagram composed of logic gates connected in a particular structure. Circuit diagram for –" }, { "code": null, "e": 1639, "s": 919, "text": "Canonical and Standard Forms –Any binary variable can take one of two forms, or . A boolean function can be expressed in terms of binary variables. If all the binary variables are combined together using the AND operation, then there are a total of combinations since each variable can take two forms.Each of the combinations is called a minterm or standard product. A minterm is represented by where is the decimal equivalent of the binary number the minterm is designated.Important Note – In a minterm, the binary variable is un-primed if the variable is 1 and it is primed if the variable is 0 i.e. if the minterm is then that means and .For example, for a boolean function in two variables the minterms are –" }, { "code": null, "e": 1885, "s": 1639, "text": "In a similar way, if the variables are combined together with OR operation, then the term obtained is called a maxterm or standard sum. A maxterm is represented by where is the decimal equivalent of the binary number the maxterm is designated." }, { "code": null, "e": 2126, "s": 1885, "text": "Important Note – In a maxterm, the binary variable is un-primed if the variable is 0 and it is primed if the variable is 1 i.e. if the maxterm is then that means and .For example, for a boolean function in two variables the maxterms are –" }, { "code": null, "e": 2178, "s": 2126, "text": "Minterms and Maxterms for function in 3 variables –" }, { "code": null, "e": 2335, "s": 2178, "text": "Relation between Minterms and Maxterms – Each minterm is the complement of it’s corresponding maxterm.For example, for a boolean function in two variables –" }, { "code": null, "e": 2356, "s": 2335, "text": "\n\n\n\nIn general or \n" }, { "code": null, "e": 2488, "s": 2356, "text": "Constructing Boolean Functions – Now that we know what minterms and maxterms are, we can use them to construct boolean expressions." }, { "code": null, "e": 2701, "s": 2488, "text": "“A Boolean function can be expressed algebraically from a given truth table by forming a minterm for each combination of the variables that produces a 1 in the function and then taking the OR of all those terms.”" }, { "code": null, "e": 2777, "s": 2701, "text": "For example, consider two functions and with the following truth tables –" }, { "code": null, "e": 2884, "s": 2777, "text": "“Boolean functions expressed as a sum of minterms or product of maxterms are said to be in canonical form." }, { "code": null, "e": 2959, "s": 2884, "text": "Example 1 – Express the following boolean expression in SOP and POS forms-" }, { "code": null, "e": 3332, "s": 2959, "text": "Solution – The expression can be transformed into SOP form by adding missing variables in each term by multiplying by where is the missing variable.It follows from the fact that – On rearranging the minterms in ascending orderIf we want the POS form, we can double negate the SOP form as stated above to get-The SOP and POS forms have a short notation of representation-" }, { "code": null, "e": 3646, "s": 3332, "text": "Standard Forms –Canonical forms are basic forms obtained from the truth table of the function. These forms are usually not used to represent the function as they are cumbersome to write and it is preferable to represent the function in the least number of literals possible.There are two types of standard forms –" }, { "code": null, "e": 3955, "s": 3646, "text": "Sum of Products(SOP)- A boolean expression involving AND terms with one or more literals each, OR’ed together.Product of Sums(POS) A boolean expression involving OR terms with one or more literals each, AND’ed together, e.g.SOP- \nPOS- \nNote – The above expressions are not equivalent, they are just examples." }, { "code": null, "e": 4066, "s": 3955, "text": "Sum of Products(SOP)- A boolean expression involving AND terms with one or more literals each, OR’ed together." }, { "code": null, "e": 4265, "s": 4066, "text": "Product of Sums(POS) A boolean expression involving OR terms with one or more literals each, AND’ed together, e.g.SOP- \nPOS- \nNote – The above expressions are not equivalent, they are just examples." }, { "code": null, "e": 4278, "s": 4265, "text": "SOP- \nPOS- \n" }, { "code": null, "e": 4351, "s": 4278, "text": "Note – The above expressions are not equivalent, they are just examples." }, { "code": null, "e": 4376, "s": 4351, "text": "GATE CS Corner Questions" }, { "code": null, "e": 4574, "s": 4376, "text": "Practicing the following questions will help you test your knowledge. All questions have been asked in GATE in previous years or in GATE Mock Tests. It is highly recommended that you practice them." }, { "code": null, "e": 4663, "s": 4574, "text": "1. GATE CS 2010, Question 62. GATE CS 2008, Question 73. GATE CS 2014 Set-1, Question 17" }, { "code": null, "e": 4675, "s": 4663, "text": "References-" }, { "code": null, "e": 4738, "s": 4675, "text": "Digital Design 5th Edition, by Morris Mano and Michael Ciletti" }, { "code": null, "e": 5036, "s": 4738, "text": "This article is contributed by Chirag Manwani. 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": 5161, "s": 5036, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 5174, "s": 5161, "text": "AdityaPoddar" }, { "code": null, "e": 5188, "s": 5174, "text": "ManasChhabra2" }, { "code": null, "e": 5201, "s": 5188, "text": "meetdoshi193" }, { "code": null, "e": 5213, "s": 5201, "text": "aayushi2402" }, { "code": null, "e": 5234, "s": 5213, "text": "Discrete Mathematics" }, { "code": null, "e": 5269, "s": 5234, "text": "Digital Electronics & Logic Design" }, { "code": null, "e": 5293, "s": 5269, "text": "Engineering Mathematics" }, { "code": null, "e": 5301, "s": 5293, "text": "GATE CS" }, { "code": null, "e": 5399, "s": 5301, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5440, "s": 5399, "text": "IEEE Standard 754 Floating Point Numbers" }, { "code": null, "e": 5471, "s": 5440, "text": "Difference between RAM and ROM" }, { "code": null, "e": 5511, "s": 5471, "text": "Introduction to memory and memory units" }, { "code": null, "e": 5540, "s": 5511, "text": "Analog to Digital Conversion" }, { "code": null, "e": 5585, "s": 5540, "text": "Difference between Half adder and full adder" }, { "code": null, "e": 5648, "s": 5585, "text": "Relationship between number of nodes and height of binary tree" }, { "code": null, "e": 5670, "s": 5648, "text": "Inequalities in LaTeX" }, { "code": null, "e": 5729, "s": 5670, "text": "Difference between Propositional Logic and Predicate Logic" }, { "code": null, "e": 5787, "s": 5729, "text": "Mathematics | Introduction to Propositional Logic | Set 1" } ]
Pandas – GroupBy One Column and Get Mean, Min, and Max values
25 Aug, 2020 We can use Groupby function to split dataframe into groups and apply different operations on it. One of them is Aggregation. Aggregation i.e. computing statistical parameters for each group created example – mean, min, max, or sums. Let’s have a look at how we can group a dataframe by one column and get their mean, min, and max values. Example 1: import pandas as pd # creating a dataframedf = pd.DataFrame([('Bike', 'Kawasaki', 186), ('Bike', 'Ducati Panigale', 202), ('Car', 'Bugatti Chiron', 304), ('Car', 'Jaguar XJ220', 210), ('Bike', 'Lightning LS-218', 218), ('Car', 'Hennessey Venom GT', 270), ('Bike', 'BMW S1000RR', 188)], columns =('Type', 'Name', 'top_speed(mph)')) df Output : Finding mean, min and max values. # using groupby function with aggregation# to get mean, min and max valuesresult = df.groupby('Type').agg({'top_speed(mph)': ['mean', 'min', 'max']}) print("Mean, min, and max values of Top Speed grouped by Vehicle Type")print(result) Output : Example 2: import pandas as pd # creating a dataframesales_data = pd.DataFrame({'customer_id':[3005, 3001, 3002, 3009, 3005, 3007, 3002, 3004, 3009, 3008, 3003, 3002], 'salesman_id': [102, 105, 101, 103, 102, 101, 101, 106, 103, 102, 107, 101], 'purchase_amt':[1500, 2700, 1525, 1100, 948, 2400, 5700, 2000, 1280, 2500, 750, 5050]}) sales_data Output : Finding mean, min and max values. # using groupby function with aggregation # to get mean, min and max valuesresult = sales_data.groupby('salesman_id').agg({'purchase_amt': ['mean', 'min', 'max']}) print("Mean, min, and max values of Purchase Amount grouped by Salesman id")print(result) Output : Example 3: import pandas as pd # creating a dataframedf = pd.DataFrame({"Team": ["Radisson", "Radisson", "Gladiators", "Blues", "Gladiators", "Blues", "Gladiators", "Gladiators", "Blues", "Blues", "Radisson", "Radisson"], "Position": ["Player", "Extras", "Player", "Extras", "Extras", "Player", "Player", "Player", "Extras", "Player", "Player", "Extras"], "Age": [22, 24, 21, 29, 32, 20, 21, 23, 30, 26, 20, 31]})df Output : Finding mean, min and max values. # using groupby function with aggregation # to get mean, min and max valuesresult = df.groupby('Team').agg({'Age': ['mean', 'min', 'max']}) print("Mean, min, and max values of Age grouped by Team")print(result) Output : Python Pandas-exercise Python pandas-groupby Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n25 Aug, 2020" }, { "code": null, "e": 261, "s": 28, "text": "We can use Groupby function to split dataframe into groups and apply different operations on it. One of them is Aggregation. Aggregation i.e. computing statistical parameters for each group created example – mean, min, max, or sums." }, { "code": null, "e": 366, "s": 261, "text": "Let’s have a look at how we can group a dataframe by one column and get their mean, min, and max values." }, { "code": null, "e": 377, "s": 366, "text": "Example 1:" }, { "code": "import pandas as pd # creating a dataframedf = pd.DataFrame([('Bike', 'Kawasaki', 186), ('Bike', 'Ducati Panigale', 202), ('Car', 'Bugatti Chiron', 304), ('Car', 'Jaguar XJ220', 210), ('Bike', 'Lightning LS-218', 218), ('Car', 'Hennessey Venom GT', 270), ('Bike', 'BMW S1000RR', 188)], columns =('Type', 'Name', 'top_speed(mph)')) df", "e": 842, "s": 377, "text": null }, { "code": null, "e": 851, "s": 842, "text": "Output :" }, { "code": null, "e": 885, "s": 851, "text": "Finding mean, min and max values." }, { "code": "# using groupby function with aggregation# to get mean, min and max valuesresult = df.groupby('Type').agg({'top_speed(mph)': ['mean', 'min', 'max']}) print(\"Mean, min, and max values of Top Speed grouped by Vehicle Type\")print(result)", "e": 1121, "s": 885, "text": null }, { "code": null, "e": 1130, "s": 1121, "text": "Output :" }, { "code": null, "e": 1141, "s": 1130, "text": "Example 2:" }, { "code": "import pandas as pd # creating a dataframesales_data = pd.DataFrame({'customer_id':[3005, 3001, 3002, 3009, 3005, 3007, 3002, 3004, 3009, 3008, 3003, 3002], 'salesman_id': [102, 105, 101, 103, 102, 101, 101, 106, 103, 102, 107, 101], 'purchase_amt':[1500, 2700, 1525, 1100, 948, 2400, 5700, 2000, 1280, 2500, 750, 5050]}) sales_data", "e": 1528, "s": 1141, "text": null }, { "code": null, "e": 1537, "s": 1528, "text": "Output :" }, { "code": null, "e": 1571, "s": 1537, "text": "Finding mean, min and max values." }, { "code": "# using groupby function with aggregation # to get mean, min and max valuesresult = sales_data.groupby('salesman_id').agg({'purchase_amt': ['mean', 'min', 'max']}) print(\"Mean, min, and max values of Purchase Amount grouped by Salesman id\")print(result)", "e": 1826, "s": 1571, "text": null }, { "code": null, "e": 1835, "s": 1826, "text": "Output :" }, { "code": null, "e": 1846, "s": 1835, "text": "Example 3:" }, { "code": "import pandas as pd # creating a dataframedf = pd.DataFrame({\"Team\": [\"Radisson\", \"Radisson\", \"Gladiators\", \"Blues\", \"Gladiators\", \"Blues\", \"Gladiators\", \"Gladiators\", \"Blues\", \"Blues\", \"Radisson\", \"Radisson\"], \"Position\": [\"Player\", \"Extras\", \"Player\", \"Extras\", \"Extras\", \"Player\", \"Player\", \"Player\", \"Extras\", \"Player\", \"Player\", \"Extras\"], \"Age\": [22, 24, 21, 29, 32, 20, 21, 23, 30, 26, 20, 31]})df", "e": 2433, "s": 1846, "text": null }, { "code": null, "e": 2442, "s": 2433, "text": "Output :" }, { "code": null, "e": 2476, "s": 2442, "text": "Finding mean, min and max values." }, { "code": "# using groupby function with aggregation # to get mean, min and max valuesresult = df.groupby('Team').agg({'Age': ['mean', 'min', 'max']}) print(\"Mean, min, and max values of Age grouped by Team\")print(result)", "e": 2688, "s": 2476, "text": null }, { "code": null, "e": 2697, "s": 2688, "text": "Output :" }, { "code": null, "e": 2720, "s": 2697, "text": "Python Pandas-exercise" }, { "code": null, "e": 2742, "s": 2720, "text": "Python pandas-groupby" }, { "code": null, "e": 2756, "s": 2742, "text": "Python-pandas" }, { "code": null, "e": 2763, "s": 2756, "text": "Python" } ]
Count of n digit numbers whose sum of digits equals to given sum
25 Jun, 2021 Given two integers ‘n’ and ‘sum’, find count of all n digit numbers with sum of digits as ‘sum’. Leading 0’s are not counted as digits. 1 <= n <= 100 and 1 <= sum <= 500 Example: Input: n = 2, sum = 2 Output: 2 Explanation: Numbers are 11 and 20 Input: n = 2, sum = 5 Output: 5 Explanation: Numbers are 14, 23, 32, 41 and 50 Input: n = 3, sum = 6 Output: 21 The idea is simple, we subtract all values from 0 to 9 from given sum and recur for sum minus that digit. Below is recursive formula. countRec(n, sum) = ∑countRec(n-1, sum-x) where 0 =< x = 0 One important observation is, leading 0's must be handled explicitly as they are not counted as digits. So our final count can be written as below. finalCount(n, sum) = ∑countRec(n-1, sum-x) where 1 =< x = 0 Below is a simple recursive solution based on above recursive formula. C++ Java Python3 C# PHP Javascript // A C++ program using recursive to count numbers// with sum of digits as given 'sum'#include<bits/stdc++.h>using namespace std; // Recursive function to count 'n' digit numbers// with sum of digits as 'sum'. This function// considers leading 0's also as digits, that is// why not directly calledunsigned long long int countRec(int n, int sum){ // Base case if (n == 0) return sum == 0; if (sum == 0) return 1; // Initialize answer unsigned long long int ans = 0; // Traverse through every digit and count // numbers beginning with it using recursion for (int i=0; i<=9; i++) if (sum-i >= 0) ans += countRec(n-1, sum-i); return ans;} // This is mainly a wrapper over countRec. It// explicitly handles leading digit and calls// countRec() for remaining digits.unsigned long long int finalCount(int n, int sum){ // Initialize final answer unsigned long long int ans = 0; // Traverse through every digit from 1 to // 9 and count numbers beginning with it for (int i = 1; i <= 9; i++) if (sum-i >= 0) ans += countRec(n-1, sum-i); return ans;} // Driver programint main(){ int n = 2, sum = 5; cout << finalCount(n, sum); return 0;} // A Java program using recursive to count numbers// with sum of digits as given 'sum'class sum_dig{ // Recursive function to count 'n' digit numbers // with sum of digits as 'sum'. This function // considers leading 0's also as digits, that is // why not directly called static int countRec(int n, int sum) { // Base case if (n == 0) return sum == 0 ?1:0; if (sum == 0) return 1; // Initialize answer int ans = 0; // Traverse through every digit and count // numbers beginning with it using recursion for (int i=0; i<=9; i++) if (sum-i >= 0) ans += countRec(n-1, sum-i); return ans; } // This is mainly a wrapper over countRec. It // explicitly handles leading digit and calls // countRec() for remaining digits. static int finalCount(int n, int sum) { // Initialize final answer int ans = 0; // Traverse through every digit from 1 to // 9 and count numbers beginning with it for (int i = 1; i <= 9; i++) if (sum-i >= 0) ans += countRec(n-1, sum-i); return ans; } /* Driver program to test above function */ public static void main (String args[]) { int n = 2, sum = 5; System.out.println(finalCount(n, sum)); }}/* This code is contributed by Rajat Mishra */ # A python 3 program using recursive to count numbers# with sum of digits as given 'sum' # Recursive function to count 'n' digit# numbers with sum of digits as 'sum'# This function considers leading 0's# also as digits, that is why not# directly calleddef countRec(n, sum) : # Base case if (n == 0) : return (sum == 0) if (sum == 0) : return 1 # Initialize answer ans = 0 # Traverse through every digit and # count numbers beginning with it # using recursion for i in range(0, 10) : if (sum-i >= 0) : ans = ans + countRec(n-1, sum-i) return ans # This is mainly a wrapper over countRec. It# explicitly handles leading digit and calls# countRec() for remaining digits.def finalCount(n, sum) : # Initialize final answer ans = 0 # Traverse through every digit from 1 to # 9 and count numbers beginning with it for i in range(1, 10) : if (sum-i >= 0) : ans = ans + countRec(n-1, sum-i) return ans # Driver programn = 2sum = 5print(finalCount(n, sum)) # This code is contributed by Nikita tiwari. // A C# program using recursive to count numbers// with sum of digits as given 'sum'using System;class GFG { // Recursive function to // count 'n' digit numbers // with sum of digits as // 'sum'. This function // considers leading 0's // also as digits, that is // why not directly called static int countRec(int n, int sum) { // Base case if (n == 0) return sum == 0 ? 1 : 0; if (sum == 0) return 1; // Initialize answer int ans = 0; // Traverse through every // digit and count numbers // beginning with it using // recursion for (int i = 0; i <= 9; i++) if (sum - i >= 0) ans += countRec(n - 1, sum - i); return ans; } // This is mainly a // wrapper over countRec. It // explicitly handles leading // digit and calls countRec() // for remaining digits. static int finalCount(int n, int sum) { // Initialize final answer int ans = 0; // Traverse through every // digit from 1 to 9 and // count numbers beginning // with it for (int i = 1; i <= 9; i++) if (sum - i >= 0) ans += countRec(n - 1, sum - i); return ans; } // Driver Code public static void Main () { int n = 2, sum = 5; Console.Write(finalCount(n, sum)); }} // This code is contributed by nitin mittal. <?php// A PHP program using recursive to count numbers// with sum of digits as given 'sum' // Recursive function to count 'n' digit numbers// with sum of digits as 'sum'. This function// considers leading 0's also as digits, that is// why not directly calledfunction countRec($n, $sum){ // Base case if ($n == 0) return $sum == 0; if ($sum == 0) return 1; // Initialize answer $ans = 0; // Traverse through every // digit and count // numbers beginning with // it using recursion for ($i = 0; $i <= 9; $i++) if ($sum-$i >= 0) $ans += countRec($n-1, $sum-$i); return $ans;} // This is mainly a wrapper// over countRec. It// explicitly handles leading// digit and calls// countRec() for remaining digits.function finalCount($n, $sum){ // Initialize final answer $ans = 0; // Traverse through every // digit from 1 to // 9 and count numbers // beginning with it for ($i = 1; $i <= 9; $i++) if ($sum - $i >= 0) $ans += countRec($n - 1, $sum - $i); return $ans;} // Driver Code $n = 2; $sum = 5; echo finalCount($n, $sum); // This code is contributed by ajit?> <script>// A JavaScript program using// recursive to count numbers // with sum of digits as given 'sum' // Recursive function to // count 'n' digit numbers // with sum of digits as 'sum'. //This function // considers leading 0's also as digits, //that is why not directly called function countRec(n, sum) { // Base case if (n == 0) return sum == 0; if (sum == 0) return 1; // Initialize answer let ans = 0; // Traverse through every // digit and count // numbers beginning with // it using recursion for (let i = 0; i <= 9; i++) { if (sum - i >= 0) ans += countRec(n - 1, sum - i); } return ans; } // This is mainly a wrapper over countRec. // It explicitly handles leading digit // and calls countRec() for remaining digits. function finalCount(n, sum) { // Initialize final answer let ans = 0; // Traverse through every digit from 1 to // 9 and count numbers beginning with it for (let i = 1; i <= 9; i++) { if (sum - i >= 0) ans += countRec(n - 1, sum - i); } return ans; } // Driver program let n = 2, sum = 5; document.write(finalCount(n, sum)); //This code is contributed by Surbhi Tyagi</script> Output: 5 The time complexity of above solution is exponential. If we draw the complete recursion tree, we can observer that many subproblems are solved again and again. For example, if we start with n = 3 and sum = 10, we can reach n = 1, sum = 8, by considering digit sequences 1,1 or 2, 0. Since same subproblems are called again, this problem has Overlapping Subproblems property. So min square sum problem has both properties (see this and this) of a dynamic programming problem. Below is Memoization based the implementation. C++ Java Python3 C# PHP Javascript // A C++ memoization based recursive program to count// numbers with sum of n as given 'sum'#include<bits/stdc++.h>using namespace std; // A lookup table used for memoizationunsigned long long int lookup[101][501]; // Memoization based implementation of recursive// functionunsigned long long int countRec(int n, int sum){ // Base case if (n == 0) return sum == 0; // If this subproblem is already evaluated, // return the evaluated value if (lookup[n][sum] != -1) return lookup[n][sum]; // Initialize answer unsigned long long int ans = 0; // Traverse through every digit and // recursively count numbers beginning // with it for (int i=0; i<10; i++) if (sum-i >= 0) ans += countRec(n-1, sum-i); return lookup[n][sum] = ans;} // This is mainly a wrapper over countRec. It// explicitly handles leading digit and calls// countRec() for remaining n.unsigned long long int finalCount(int n, int sum){ // Initialize all entries of lookup table memset(lookup, -1, sizeof lookup); // Initialize final answer unsigned long long int ans = 0; // Traverse through every digit from 1 to // 9 and count numbers beginning with it for (int i = 1; i <= 9; i++) if (sum-i >= 0) ans += countRec(n-1, sum-i); return ans;} // Driver programint main(){ int n = 3, sum = 5; cout << finalCount(n, sum); return 0;} // A Java memoization based recursive program to count// numbers with sum of n as given 'sum'class sum_dig{ // A lookup table used for memoization static int lookup[][] = new int[101][501]; // Memoization based implementation of recursive // function static int countRec(int n, int sum) { // Base case if (n == 0) return sum == 0 ? 1 : 0; // If this subproblem is already evaluated, // return the evaluated value if (lookup[n][sum] != -1) return lookup[n][sum]; // Initialize answer int ans = 0; // Traverse through every digit and // recursively count numbers beginning // with it for (int i=0; i<10; i++) if (sum-i >= 0) ans += countRec(n-1, sum-i); return lookup[n][sum] = ans; } // This is mainly a wrapper over countRec. It // explicitly handles leading digit and calls // countRec() for remaining n. static int finalCount(int n, int sum) { // Initialize all entries of lookup table for(int i = 0; i <= 100; ++i){ for(int j = 0; j <= 500; ++j){ lookup[i][j] = -1; } } // Initialize final answer int ans = 0; // Traverse through every digit from 1 to // 9 and count numbers beginning with it for (int i = 1; i <= 9; i++) if (sum-i >= 0) ans += countRec(n-1, sum-i); return ans; } /* Driver program to test above function */ public static void main (String args[]) { int n = 3, sum = 5; System.out.println(finalCount(n, sum)); }}/* This code is contributed by Rajat Mishra */ # A Python3 memoization based recursive# program to count numbers with Sum of n# as given 'Sum' # A lookup table used for memoizationlookup = [[-1 for i in range(501)] for i in range(101)] # Memoization based implementation# of recursive functiondef countRec(n, Sum): # Base case if (n == 0): return Sum == 0 # If this subproblem is already evaluated, # return the evaluated value if (lookup[n][Sum] != -1): return lookup[n][Sum] # Initialize answer ans = 0 # Traverse through every digit and # recursively count numbers beginning # with it for i in range(10): if (Sum-i >= 0): ans += countRec(n - 1, Sum-i) lookup[n][Sum] = ans return lookup[n][Sum] # This is mainly a wrapper over countRec. It# explicitly handles leading digit and calls# countRec() for remaining n.def finalCount(n, Sum): # Initialize final answer ans = 0 # Traverse through every digit from 1 to # 9 and count numbers beginning with it for i in range(1, 10): if (Sum - i >= 0): ans += countRec(n - 1, Sum - i) return ans # Driver Coden, Sum = 3, 5print(finalCount(n, Sum)) # This code is contributed by mohit kumar 29 // A C# memoization based recursive program to count// numbers with sum of n as given 'sum' using System;class sum_dig{ // A lookup table used for memoization static int [,]lookup = new int[101,501]; // Memoization based implementation of recursive // function static int countRec(int n, int sum) { // Base case if (n == 0) return sum == 0 ? 1 : 0; // If this subproblem is already evaluated, // return the evaluated value if (lookup[n,sum] != -1) return lookup[n,sum]; // Initialize answer int ans = 0; // Traverse through every digit and // recursively count numbers beginning // with it for (int i=0; i<10; i++) if (sum-i >= 0) ans += countRec(n-1, sum-i); return lookup[n,sum] = ans; } // This is mainly a wrapper over countRec. It // explicitly handles leading digit and calls // countRec() for remaining n. static int finalCount(int n, int sum) { // Initialize all entries of lookup table for(int i = 0; i <= 100; ++i){ for(int j = 0; j <= 500; ++j){ lookup[i,j] = -1; } } // Initialize final answer int ans = 0; // Traverse through every digit from 1 to // 9 and count numbers beginning with it for (int i = 1; i <= 9; i++) if (sum-i >= 0) ans += countRec(n-1, sum-i); return ans; } /* Driver program to test above function */ public static void Main () { int n = 3, sum = 5; Console.Write(finalCount(n, sum)); }} <?php// A PHP memoization based recursive program// to count numbers with sum of n as given 'sum' // A lookup table used for memoization$lookup = array_fill(0, 101, array_fill(0, 501, -1)); // Memoization based implementation// of recursive functionfunction countRec($n, $sum){ global $lookup; // Base case if ($n == 0) return $sum == 0; // If this subproblem is already evaluated, // return the evaluated value if ($lookup[$n][$sum] != -1) return $lookup[$n][$sum]; // Initialize answer $ans = 0; // Traverse through every digit and // recursively count numbers beginning // with it for ($i = 0; $i < 10; $i++) if ($sum - $i >= 0) $ans += countRec($n - 1, $sum - $i); return $lookup[$n][$sum] = $ans;} // This is mainly a wrapper over countRec. It// explicitly handles leading digit and calls// countRec() for remaining n.function finalCount($n, $sum){ // Initialize all entries of lookup table // Initialize final answer $ans = 0; // Traverse through every digit from 1 to // 9 and count numbers beginning with it for ($i = 1; $i <= 9; $i++) if ($sum-$i >= 0) $ans += countRec($n - 1, $sum - $i); return $ans;} // Driver Code$n = 3;$sum = 5;echo finalCount($n, $sum); // This code is contributed by mits?> <script> // A Javascript memoization based// recursive program to count numbers// with sum of n as given 'sum' // A lookup table used for memoizationlet lookup = new Array(101); // Memoization based implementation// of recursive functionfunction countRec(n, sum){ // Base case if (n == 0) return sum == 0 ? 1 : 0; // If this subproblem is already evaluated, // return the evaluated value if (lookup[n][sum] != -1) return lookup[n][sum]; // Initialize answer let ans = 0; // Traverse through every digit and // recursively count numbers beginning // with it for(let i = 0; i < 10; i++) if (sum - i >= 0) ans += countRec(n - 1, sum - i); return lookup[n][sum] = ans;} // This is mainly a wrapper over countRec. It// explicitly handles leading digit and calls// countRec() for remaining n.function finalCount(n, sum){ // Initialize all entries of lookup table for(let i = 0; i < 101; i++) { lookup[i] = new Array(501); for(let j = 0; j < 501; j++) { lookup[i][j] = -1; } } // Initialize final answer let ans = 0; // Traverse through every digit from 1 to // 9 and count numbers beginning with it for(let i = 1; i <= 9; i++) if (sum - i >= 0) ans += countRec(n - 1, sum - i); return ans;} // Driver codelet n = 3, sum = 5; document.write(finalCount(n, sum)); // This code is contributed by avanitrachhadiya2155 </script> Output: 15 Thanks to Gaurav Ahirwar for suggesting above solution. Another Method We can easily count n digit numbers whose sum of digit equals to given sum by iterating all n digits and checking if current n digit number’s sum is equal to given sum, if it is then we will start increment number by 9 until it reaches to number whose sum of digit’s is greater than given sum, then again we will increment by 1 until we found another number with given sum. C++ Java Python3 C# PHP Javascript // C++ program to Count of n digit numbers// whose sum of digits equals to given sum#include <bits/stdc++.h>#include <iostream>using namespace std; void findCount(int n, int sum) { //in case n = 2 start is 10 and end is (100-1) = 99 int start = pow(10, n-1); int end = pow(10, n)-1; int count = 0; int i = start; while(i <= end) { int cur = 0; int temp = i; while( temp != 0) { cur += temp % 10; temp = temp / 10; } if(cur == sum) { count++; i += 9; }else i++; } cout << count; /* This code is contributed by Anshuman */ }int main() { int n = 3; int sum = 5; findCount(n,sum); return 0;} // Java program to Count of n digit numbers// whose sum of digits equals to given sum public class GFG { public static void main(String[] args) { int n = 3; int sum = 5; findCount(n,sum); } private static void findCount(int n, int sum) { //in case n = 2 start is 10 and end is (100-1) = 99 int start = (int) Math.pow(10, n-1); int end = (int) Math.pow(10, n)-1; int count = 0; int i = start; while(i < end) { int cur = 0; int temp = i; while( temp != 0) { cur += temp % 10; temp = temp / 10; } if(cur == sum) { count++; i += 9; }else i++; } System.out.println(count); /* This code is contributed by Anshuman */ }} # Python3 program to Count of n digit numbers# whose sum of digits equals to given sumimport math def findCount(n, sum): # in case n = 2 start is 10 and # end is (100-1) = 99 start = math.pow(10, n - 1); end = math.pow(10, n) - 1; count = 0; i = start; while(i <= end): cur = 0; temp = i; while(temp != 0): cur += temp % 10; temp = temp // 10; if(cur == sum): count = count + 1; i += 9; else: i = i + 1; print(count); # Driver Coden = 3;sum = 5; findCount(n, sum); # This code is contributed# by Akanksha Rai // C# program to Count of n digit numbers// whose sum of digits equals to given sumusing System; class GFG{private static void findCount(int n, int sum){ // in case n = 2 start is 10 and // end is (100-1) = 99 int start = (int) Math.Pow(10, n - 1); int end = (int) Math.Pow(10, n) - 1; int count = 0; int i = start; while(i < end) { int cur = 0; int temp = i; while( temp != 0) { cur += temp % 10; temp = temp / 10; } if(cur == sum) { count++; i += 9; } else i++; } Console.WriteLine(count);} // Driver Codepublic static void Main(){ int n = 3; int sum = 5; findCount(n,sum);}} // This code is contributed// by Akanksha Rai <?php// PHP program to Count of n digit numbers// whose sum of digits equals to given sum function findCount($n, $sum){ // In case n = 2 start is 10 and// end is (100-1) = 99$start = (int)pow(10, $n - 1);$end = (int)pow(10, $n) - 1; $count = 0;$i = $start; while($i < $end){ $cur = 0; $temp = $i; while( $temp != 0) { $cur += $temp % 10; $temp = (int) $temp / 10; } if($cur == $sum) { $count++; $i += 9; } else $i++; }echo ($count);} // Driver Code$n = 3;$sum = 5;findCount($n,$sum); // This code is contributed// by jit_t?> <script> // Javascript program to Count of n digit numbers// whose sum of digits equals to given sum function findCount(n, sum) { // in case n = 2 start is 10 and end is (100-1) = 99 let start = Math.pow(10, n-1); let end = Math.pow(10, n)-1; let count = 0; let i = start; while(i <= end) { let cur = 0; let temp = i; while( temp != 0) { cur += temp % 10; temp = parseInt(temp / 10); } if(cur == sum) { count++; i += 9; }else i++; } document.write(count); } let n = 3; let sum = 5; findCount(n,sum); // This code is contributed by souravmahato348.</script> Output: 15 Time Complexity: O(sum) Space Complexity: O(1)Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above jit_t nitin mittal Anshuman Kaushik ukasp Akanksha_Rai puruiiit mohit kumar 29 Mithun Kumar atishayjainece17 surbhityagi15 avanitrachhadiya2155 souravmahato348 anikakapoor Amazon number-digits Dynamic Programming Mathematical Amazon Dynamic Programming Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n25 Jun, 2021" }, { "code": null, "e": 224, "s": 54, "text": "Given two integers ‘n’ and ‘sum’, find count of all n digit numbers with sum of digits as ‘sum’. Leading 0’s are not counted as digits. 1 <= n <= 100 and 1 <= sum <= 500" }, { "code": null, "e": 234, "s": 224, "text": "Example: " }, { "code": null, "e": 418, "s": 234, "text": "Input: n = 2, sum = 2\nOutput: 2\nExplanation: Numbers are 11 and 20\n\nInput: n = 2, sum = 5\nOutput: 5\nExplanation: Numbers are 14, 23, 32, 41 and 50\n\nInput: n = 3, sum = 6\nOutput: 21" }, { "code": null, "e": 554, "s": 418, "text": "The idea is simple, we subtract all values from 0 to 9 from given sum and recur for sum minus that digit. Below is recursive formula. " }, { "code": null, "e": 896, "s": 554, "text": " countRec(n, sum) = ∑countRec(n-1, sum-x)\n where 0 =< x = 0\n\n One important observation is, leading 0's must be\n handled explicitly as they are not counted as digits.\n So our final count can be written as below.\n finalCount(n, sum) = ∑countRec(n-1, sum-x)\n where 1 =< x = 0" }, { "code": null, "e": 969, "s": 896, "text": "Below is a simple recursive solution based on above recursive formula. " }, { "code": null, "e": 973, "s": 969, "text": "C++" }, { "code": null, "e": 978, "s": 973, "text": "Java" }, { "code": null, "e": 986, "s": 978, "text": "Python3" }, { "code": null, "e": 989, "s": 986, "text": "C#" }, { "code": null, "e": 993, "s": 989, "text": "PHP" }, { "code": null, "e": 1004, "s": 993, "text": "Javascript" }, { "code": "// A C++ program using recursive to count numbers// with sum of digits as given 'sum'#include<bits/stdc++.h>using namespace std; // Recursive function to count 'n' digit numbers// with sum of digits as 'sum'. This function// considers leading 0's also as digits, that is// why not directly calledunsigned long long int countRec(int n, int sum){ // Base case if (n == 0) return sum == 0; if (sum == 0) return 1; // Initialize answer unsigned long long int ans = 0; // Traverse through every digit and count // numbers beginning with it using recursion for (int i=0; i<=9; i++) if (sum-i >= 0) ans += countRec(n-1, sum-i); return ans;} // This is mainly a wrapper over countRec. It// explicitly handles leading digit and calls// countRec() for remaining digits.unsigned long long int finalCount(int n, int sum){ // Initialize final answer unsigned long long int ans = 0; // Traverse through every digit from 1 to // 9 and count numbers beginning with it for (int i = 1; i <= 9; i++) if (sum-i >= 0) ans += countRec(n-1, sum-i); return ans;} // Driver programint main(){ int n = 2, sum = 5; cout << finalCount(n, sum); return 0;}", "e": 2217, "s": 1004, "text": null }, { "code": "// A Java program using recursive to count numbers// with sum of digits as given 'sum'class sum_dig{ // Recursive function to count 'n' digit numbers // with sum of digits as 'sum'. This function // considers leading 0's also as digits, that is // why not directly called static int countRec(int n, int sum) { // Base case if (n == 0) return sum == 0 ?1:0; if (sum == 0) return 1; // Initialize answer int ans = 0; // Traverse through every digit and count // numbers beginning with it using recursion for (int i=0; i<=9; i++) if (sum-i >= 0) ans += countRec(n-1, sum-i); return ans; } // This is mainly a wrapper over countRec. It // explicitly handles leading digit and calls // countRec() for remaining digits. static int finalCount(int n, int sum) { // Initialize final answer int ans = 0; // Traverse through every digit from 1 to // 9 and count numbers beginning with it for (int i = 1; i <= 9; i++) if (sum-i >= 0) ans += countRec(n-1, sum-i); return ans; } /* Driver program to test above function */ public static void main (String args[]) { int n = 2, sum = 5; System.out.println(finalCount(n, sum)); }}/* This code is contributed by Rajat Mishra */", "e": 3637, "s": 2217, "text": null }, { "code": "# A python 3 program using recursive to count numbers# with sum of digits as given 'sum' # Recursive function to count 'n' digit# numbers with sum of digits as 'sum'# This function considers leading 0's# also as digits, that is why not# directly calleddef countRec(n, sum) : # Base case if (n == 0) : return (sum == 0) if (sum == 0) : return 1 # Initialize answer ans = 0 # Traverse through every digit and # count numbers beginning with it # using recursion for i in range(0, 10) : if (sum-i >= 0) : ans = ans + countRec(n-1, sum-i) return ans # This is mainly a wrapper over countRec. It# explicitly handles leading digit and calls# countRec() for remaining digits.def finalCount(n, sum) : # Initialize final answer ans = 0 # Traverse through every digit from 1 to # 9 and count numbers beginning with it for i in range(1, 10) : if (sum-i >= 0) : ans = ans + countRec(n-1, sum-i) return ans # Driver programn = 2sum = 5print(finalCount(n, sum)) # This code is contributed by Nikita tiwari.", "e": 4754, "s": 3637, "text": null }, { "code": "// A C# program using recursive to count numbers// with sum of digits as given 'sum'using System;class GFG { // Recursive function to // count 'n' digit numbers // with sum of digits as // 'sum'. This function // considers leading 0's // also as digits, that is // why not directly called static int countRec(int n, int sum) { // Base case if (n == 0) return sum == 0 ? 1 : 0; if (sum == 0) return 1; // Initialize answer int ans = 0; // Traverse through every // digit and count numbers // beginning with it using // recursion for (int i = 0; i <= 9; i++) if (sum - i >= 0) ans += countRec(n - 1, sum - i); return ans; } // This is mainly a // wrapper over countRec. It // explicitly handles leading // digit and calls countRec() // for remaining digits. static int finalCount(int n, int sum) { // Initialize final answer int ans = 0; // Traverse through every // digit from 1 to 9 and // count numbers beginning // with it for (int i = 1; i <= 9; i++) if (sum - i >= 0) ans += countRec(n - 1, sum - i); return ans; } // Driver Code public static void Main () { int n = 2, sum = 5; Console.Write(finalCount(n, sum)); }} // This code is contributed by nitin mittal.", "e": 6246, "s": 4754, "text": null }, { "code": "<?php// A PHP program using recursive to count numbers// with sum of digits as given 'sum' // Recursive function to count 'n' digit numbers// with sum of digits as 'sum'. This function// considers leading 0's also as digits, that is// why not directly calledfunction countRec($n, $sum){ // Base case if ($n == 0) return $sum == 0; if ($sum == 0) return 1; // Initialize answer $ans = 0; // Traverse through every // digit and count // numbers beginning with // it using recursion for ($i = 0; $i <= 9; $i++) if ($sum-$i >= 0) $ans += countRec($n-1, $sum-$i); return $ans;} // This is mainly a wrapper// over countRec. It// explicitly handles leading// digit and calls// countRec() for remaining digits.function finalCount($n, $sum){ // Initialize final answer $ans = 0; // Traverse through every // digit from 1 to // 9 and count numbers // beginning with it for ($i = 1; $i <= 9; $i++) if ($sum - $i >= 0) $ans += countRec($n - 1, $sum - $i); return $ans;} // Driver Code $n = 2; $sum = 5; echo finalCount($n, $sum); // This code is contributed by ajit?>", "e": 7418, "s": 6246, "text": null }, { "code": "<script>// A JavaScript program using// recursive to count numbers // with sum of digits as given 'sum' // Recursive function to // count 'n' digit numbers // with sum of digits as 'sum'. //This function // considers leading 0's also as digits, //that is why not directly called function countRec(n, sum) { // Base case if (n == 0) return sum == 0; if (sum == 0) return 1; // Initialize answer let ans = 0; // Traverse through every // digit and count // numbers beginning with // it using recursion for (let i = 0; i <= 9; i++) { if (sum - i >= 0) ans += countRec(n - 1, sum - i); } return ans; } // This is mainly a wrapper over countRec. // It explicitly handles leading digit // and calls countRec() for remaining digits. function finalCount(n, sum) { // Initialize final answer let ans = 0; // Traverse through every digit from 1 to // 9 and count numbers beginning with it for (let i = 1; i <= 9; i++) { if (sum - i >= 0) ans += countRec(n - 1, sum - i); } return ans; } // Driver program let n = 2, sum = 5; document.write(finalCount(n, sum)); //This code is contributed by Surbhi Tyagi</script>", "e": 8797, "s": 7418, "text": null }, { "code": null, "e": 8806, "s": 8797, "text": "Output: " }, { "code": null, "e": 8808, "s": 8806, "text": "5" }, { "code": null, "e": 9284, "s": 8808, "text": "The time complexity of above solution is exponential. If we draw the complete recursion tree, we can observer that many subproblems are solved again and again. For example, if we start with n = 3 and sum = 10, we can reach n = 1, sum = 8, by considering digit sequences 1,1 or 2, 0. Since same subproblems are called again, this problem has Overlapping Subproblems property. So min square sum problem has both properties (see this and this) of a dynamic programming problem. " }, { "code": null, "e": 9333, "s": 9284, "text": "Below is Memoization based the implementation. " }, { "code": null, "e": 9337, "s": 9333, "text": "C++" }, { "code": null, "e": 9342, "s": 9337, "text": "Java" }, { "code": null, "e": 9350, "s": 9342, "text": "Python3" }, { "code": null, "e": 9353, "s": 9350, "text": "C#" }, { "code": null, "e": 9357, "s": 9353, "text": "PHP" }, { "code": null, "e": 9368, "s": 9357, "text": "Javascript" }, { "code": "// A C++ memoization based recursive program to count// numbers with sum of n as given 'sum'#include<bits/stdc++.h>using namespace std; // A lookup table used for memoizationunsigned long long int lookup[101][501]; // Memoization based implementation of recursive// functionunsigned long long int countRec(int n, int sum){ // Base case if (n == 0) return sum == 0; // If this subproblem is already evaluated, // return the evaluated value if (lookup[n][sum] != -1) return lookup[n][sum]; // Initialize answer unsigned long long int ans = 0; // Traverse through every digit and // recursively count numbers beginning // with it for (int i=0; i<10; i++) if (sum-i >= 0) ans += countRec(n-1, sum-i); return lookup[n][sum] = ans;} // This is mainly a wrapper over countRec. It// explicitly handles leading digit and calls// countRec() for remaining n.unsigned long long int finalCount(int n, int sum){ // Initialize all entries of lookup table memset(lookup, -1, sizeof lookup); // Initialize final answer unsigned long long int ans = 0; // Traverse through every digit from 1 to // 9 and count numbers beginning with it for (int i = 1; i <= 9; i++) if (sum-i >= 0) ans += countRec(n-1, sum-i); return ans;} // Driver programint main(){ int n = 3, sum = 5; cout << finalCount(n, sum); return 0;}", "e": 10761, "s": 9368, "text": null }, { "code": "// A Java memoization based recursive program to count// numbers with sum of n as given 'sum'class sum_dig{ // A lookup table used for memoization static int lookup[][] = new int[101][501]; // Memoization based implementation of recursive // function static int countRec(int n, int sum) { // Base case if (n == 0) return sum == 0 ? 1 : 0; // If this subproblem is already evaluated, // return the evaluated value if (lookup[n][sum] != -1) return lookup[n][sum]; // Initialize answer int ans = 0; // Traverse through every digit and // recursively count numbers beginning // with it for (int i=0; i<10; i++) if (sum-i >= 0) ans += countRec(n-1, sum-i); return lookup[n][sum] = ans; } // This is mainly a wrapper over countRec. It // explicitly handles leading digit and calls // countRec() for remaining n. static int finalCount(int n, int sum) { // Initialize all entries of lookup table for(int i = 0; i <= 100; ++i){ for(int j = 0; j <= 500; ++j){ lookup[i][j] = -1; } } // Initialize final answer int ans = 0; // Traverse through every digit from 1 to // 9 and count numbers beginning with it for (int i = 1; i <= 9; i++) if (sum-i >= 0) ans += countRec(n-1, sum-i); return ans; } /* Driver program to test above function */ public static void main (String args[]) { int n = 3, sum = 5; System.out.println(finalCount(n, sum)); }}/* This code is contributed by Rajat Mishra */", "e": 12480, "s": 10761, "text": null }, { "code": "# A Python3 memoization based recursive# program to count numbers with Sum of n# as given 'Sum' # A lookup table used for memoizationlookup = [[-1 for i in range(501)] for i in range(101)] # Memoization based implementation# of recursive functiondef countRec(n, Sum): # Base case if (n == 0): return Sum == 0 # If this subproblem is already evaluated, # return the evaluated value if (lookup[n][Sum] != -1): return lookup[n][Sum] # Initialize answer ans = 0 # Traverse through every digit and # recursively count numbers beginning # with it for i in range(10): if (Sum-i >= 0): ans += countRec(n - 1, Sum-i) lookup[n][Sum] = ans return lookup[n][Sum] # This is mainly a wrapper over countRec. It# explicitly handles leading digit and calls# countRec() for remaining n.def finalCount(n, Sum): # Initialize final answer ans = 0 # Traverse through every digit from 1 to # 9 and count numbers beginning with it for i in range(1, 10): if (Sum - i >= 0): ans += countRec(n - 1, Sum - i) return ans # Driver Coden, Sum = 3, 5print(finalCount(n, Sum)) # This code is contributed by mohit kumar 29", "e": 13700, "s": 12480, "text": null }, { "code": "// A C# memoization based recursive program to count// numbers with sum of n as given 'sum' using System;class sum_dig{ // A lookup table used for memoization static int [,]lookup = new int[101,501]; // Memoization based implementation of recursive // function static int countRec(int n, int sum) { // Base case if (n == 0) return sum == 0 ? 1 : 0; // If this subproblem is already evaluated, // return the evaluated value if (lookup[n,sum] != -1) return lookup[n,sum]; // Initialize answer int ans = 0; // Traverse through every digit and // recursively count numbers beginning // with it for (int i=0; i<10; i++) if (sum-i >= 0) ans += countRec(n-1, sum-i); return lookup[n,sum] = ans; } // This is mainly a wrapper over countRec. It // explicitly handles leading digit and calls // countRec() for remaining n. static int finalCount(int n, int sum) { // Initialize all entries of lookup table for(int i = 0; i <= 100; ++i){ for(int j = 0; j <= 500; ++j){ lookup[i,j] = -1; } } // Initialize final answer int ans = 0; // Traverse through every digit from 1 to // 9 and count numbers beginning with it for (int i = 1; i <= 9; i++) if (sum-i >= 0) ans += countRec(n-1, sum-i); return ans; } /* Driver program to test above function */ public static void Main () { int n = 3, sum = 5; Console.Write(finalCount(n, sum)); }}", "e": 15370, "s": 13700, "text": null }, { "code": "<?php// A PHP memoization based recursive program// to count numbers with sum of n as given 'sum' // A lookup table used for memoization$lookup = array_fill(0, 101, array_fill(0, 501, -1)); // Memoization based implementation// of recursive functionfunction countRec($n, $sum){ global $lookup; // Base case if ($n == 0) return $sum == 0; // If this subproblem is already evaluated, // return the evaluated value if ($lookup[$n][$sum] != -1) return $lookup[$n][$sum]; // Initialize answer $ans = 0; // Traverse through every digit and // recursively count numbers beginning // with it for ($i = 0; $i < 10; $i++) if ($sum - $i >= 0) $ans += countRec($n - 1, $sum - $i); return $lookup[$n][$sum] = $ans;} // This is mainly a wrapper over countRec. It// explicitly handles leading digit and calls// countRec() for remaining n.function finalCount($n, $sum){ // Initialize all entries of lookup table // Initialize final answer $ans = 0; // Traverse through every digit from 1 to // 9 and count numbers beginning with it for ($i = 1; $i <= 9; $i++) if ($sum-$i >= 0) $ans += countRec($n - 1, $sum - $i); return $ans;} // Driver Code$n = 3;$sum = 5;echo finalCount($n, $sum); // This code is contributed by mits?>", "e": 16684, "s": 15370, "text": null }, { "code": "<script> // A Javascript memoization based// recursive program to count numbers// with sum of n as given 'sum' // A lookup table used for memoizationlet lookup = new Array(101); // Memoization based implementation// of recursive functionfunction countRec(n, sum){ // Base case if (n == 0) return sum == 0 ? 1 : 0; // If this subproblem is already evaluated, // return the evaluated value if (lookup[n][sum] != -1) return lookup[n][sum]; // Initialize answer let ans = 0; // Traverse through every digit and // recursively count numbers beginning // with it for(let i = 0; i < 10; i++) if (sum - i >= 0) ans += countRec(n - 1, sum - i); return lookup[n][sum] = ans;} // This is mainly a wrapper over countRec. It// explicitly handles leading digit and calls// countRec() for remaining n.function finalCount(n, sum){ // Initialize all entries of lookup table for(let i = 0; i < 101; i++) { lookup[i] = new Array(501); for(let j = 0; j < 501; j++) { lookup[i][j] = -1; } } // Initialize final answer let ans = 0; // Traverse through every digit from 1 to // 9 and count numbers beginning with it for(let i = 1; i <= 9; i++) if (sum - i >= 0) ans += countRec(n - 1, sum - i); return ans;} // Driver codelet n = 3, sum = 5; document.write(finalCount(n, sum)); // This code is contributed by avanitrachhadiya2155 </script>", "e": 18197, "s": 16684, "text": null }, { "code": null, "e": 18206, "s": 18197, "text": "Output: " }, { "code": null, "e": 18209, "s": 18206, "text": "15" }, { "code": null, "e": 18265, "s": 18209, "text": "Thanks to Gaurav Ahirwar for suggesting above solution." }, { "code": null, "e": 18655, "s": 18265, "text": "Another Method We can easily count n digit numbers whose sum of digit equals to given sum by iterating all n digits and checking if current n digit number’s sum is equal to given sum, if it is then we will start increment number by 9 until it reaches to number whose sum of digit’s is greater than given sum, then again we will increment by 1 until we found another number with given sum. " }, { "code": null, "e": 18659, "s": 18655, "text": "C++" }, { "code": null, "e": 18664, "s": 18659, "text": "Java" }, { "code": null, "e": 18672, "s": 18664, "text": "Python3" }, { "code": null, "e": 18675, "s": 18672, "text": "C#" }, { "code": null, "e": 18679, "s": 18675, "text": "PHP" }, { "code": null, "e": 18690, "s": 18679, "text": "Javascript" }, { "code": "// C++ program to Count of n digit numbers// whose sum of digits equals to given sum#include <bits/stdc++.h>#include <iostream>using namespace std; void findCount(int n, int sum) { //in case n = 2 start is 10 and end is (100-1) = 99 int start = pow(10, n-1); int end = pow(10, n)-1; int count = 0; int i = start; while(i <= end) { int cur = 0; int temp = i; while( temp != 0) { cur += temp % 10; temp = temp / 10; } if(cur == sum) { count++; i += 9; }else i++; } cout << count; /* This code is contributed by Anshuman */ }int main() { int n = 3; int sum = 5; findCount(n,sum); return 0;}", "e": 19651, "s": 18690, "text": null }, { "code": "// Java program to Count of n digit numbers// whose sum of digits equals to given sum public class GFG { public static void main(String[] args) { int n = 3; int sum = 5; findCount(n,sum); } private static void findCount(int n, int sum) { //in case n = 2 start is 10 and end is (100-1) = 99 int start = (int) Math.pow(10, n-1); int end = (int) Math.pow(10, n)-1; int count = 0; int i = start; while(i < end) { int cur = 0; int temp = i; while( temp != 0) { cur += temp % 10; temp = temp / 10; } if(cur == sum) { count++; i += 9; }else i++; } System.out.println(count); /* This code is contributed by Anshuman */ }}", "e": 20650, "s": 19651, "text": null }, { "code": "# Python3 program to Count of n digit numbers# whose sum of digits equals to given sumimport math def findCount(n, sum): # in case n = 2 start is 10 and # end is (100-1) = 99 start = math.pow(10, n - 1); end = math.pow(10, n) - 1; count = 0; i = start; while(i <= end): cur = 0; temp = i; while(temp != 0): cur += temp % 10; temp = temp // 10; if(cur == sum): count = count + 1; i += 9; else: i = i + 1; print(count); # Driver Coden = 3;sum = 5; findCount(n, sum); # This code is contributed# by Akanksha Rai", "e": 21339, "s": 20650, "text": null }, { "code": "// C# program to Count of n digit numbers// whose sum of digits equals to given sumusing System; class GFG{private static void findCount(int n, int sum){ // in case n = 2 start is 10 and // end is (100-1) = 99 int start = (int) Math.Pow(10, n - 1); int end = (int) Math.Pow(10, n) - 1; int count = 0; int i = start; while(i < end) { int cur = 0; int temp = i; while( temp != 0) { cur += temp % 10; temp = temp / 10; } if(cur == sum) { count++; i += 9; } else i++; } Console.WriteLine(count);} // Driver Codepublic static void Main(){ int n = 3; int sum = 5; findCount(n,sum);}} // This code is contributed// by Akanksha Rai", "e": 22224, "s": 21339, "text": null }, { "code": "<?php// PHP program to Count of n digit numbers// whose sum of digits equals to given sum function findCount($n, $sum){ // In case n = 2 start is 10 and// end is (100-1) = 99$start = (int)pow(10, $n - 1);$end = (int)pow(10, $n) - 1; $count = 0;$i = $start; while($i < $end){ $cur = 0; $temp = $i; while( $temp != 0) { $cur += $temp % 10; $temp = (int) $temp / 10; } if($cur == $sum) { $count++; $i += 9; } else $i++; }echo ($count);} // Driver Code$n = 3;$sum = 5;findCount($n,$sum); // This code is contributed// by jit_t?>", "e": 22850, "s": 22224, "text": null }, { "code": "<script> // Javascript program to Count of n digit numbers// whose sum of digits equals to given sum function findCount(n, sum) { // in case n = 2 start is 10 and end is (100-1) = 99 let start = Math.pow(10, n-1); let end = Math.pow(10, n)-1; let count = 0; let i = start; while(i <= end) { let cur = 0; let temp = i; while( temp != 0) { cur += temp % 10; temp = parseInt(temp / 10); } if(cur == sum) { count++; i += 9; }else i++; } document.write(count); } let n = 3; let sum = 5; findCount(n,sum); // This code is contributed by souravmahato348.</script>", "e": 23776, "s": 22850, "text": null }, { "code": null, "e": 23785, "s": 23776, "text": "Output: " }, { "code": null, "e": 23788, "s": 23785, "text": "15" }, { "code": null, "e": 23959, "s": 23788, "text": "Time Complexity: O(sum) Space Complexity: O(1)Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 23965, "s": 23959, "text": "jit_t" }, { "code": null, "e": 23978, "s": 23965, "text": "nitin mittal" }, { "code": null, "e": 23995, "s": 23978, "text": "Anshuman Kaushik" }, { "code": null, "e": 24001, "s": 23995, "text": "ukasp" }, { "code": null, "e": 24014, "s": 24001, "text": "Akanksha_Rai" }, { "code": null, "e": 24023, "s": 24014, "text": "puruiiit" }, { "code": null, "e": 24038, "s": 24023, "text": "mohit kumar 29" }, { "code": null, "e": 24051, "s": 24038, "text": "Mithun Kumar" }, { "code": null, "e": 24068, "s": 24051, "text": "atishayjainece17" }, { "code": null, "e": 24082, "s": 24068, "text": "surbhityagi15" }, { "code": null, "e": 24103, "s": 24082, "text": "avanitrachhadiya2155" }, { "code": null, "e": 24119, "s": 24103, "text": "souravmahato348" }, { "code": null, "e": 24131, "s": 24119, "text": "anikakapoor" }, { "code": null, "e": 24138, "s": 24131, "text": "Amazon" }, { "code": null, "e": 24152, "s": 24138, "text": "number-digits" }, { "code": null, "e": 24172, "s": 24152, "text": "Dynamic Programming" }, { "code": null, "e": 24185, "s": 24172, "text": "Mathematical" }, { "code": null, "e": 24192, "s": 24185, "text": "Amazon" }, { "code": null, "e": 24212, "s": 24192, "text": "Dynamic Programming" }, { "code": null, "e": 24225, "s": 24212, "text": "Mathematical" } ]
Opening | Morphological Transformations in OpenCV in C++
10 Feb, 2021 In this article, a Morphological operation called Opening is discussed. Opening operation is similar to erosion in the sense that it also removes foreground pixels from the edges of the image. Opening operation is erosion operation followed by dilation. It is usually used for removing internal noise present inside an image. This operator safeguards the foreground region that has similarity with the structuring component or the one that fits inside the structuring element while removing everything else. Syntax: morphologyEx (src, dst, op, kernel, anchor, iterations, borderType, borderValue) Parameters: src: It is the input image. dst: It is the output image. op: Type of morphological operation. kernel: Structuring element used for Closing. anchor: Anchor position inside the structuring element. The default value is [-1, -1} signifying position as the center of the structuring element. iterations: Number of times Closing is applied. borderType: Type of border ( BORDER_CONSTANT, BORDER_REPLICATE, etc.) borderValue: Border value Return: Output Image (Mat Object) The opening operator is given by the expression: The expression represents that AoB is a subset (sub-image of A). The opening operator removes internal noise and thin protrusions present inside an image. Below is the C++ program to demonstrate the Opening Morphological Operation: C++ // C++ program to demonstrate the// opening morphological transformation#include <iostream>#include <opencv2/core/core.hpp> // Library include for drawing shapes#include <opencv2/highgui/highgui.hpp>#include <opencv2/imgproc.hpp>using namespace cv;using namespace std; // Function to demonstrate the// opening morphological operatorint openingMorphological(){ // Reading the Image Mat image = imread( "C:/Users/harsh/Downloads/geeks.png", IMREAD_GRAYSCALE); // Check if the image is // created successfully or not if (!image.data) { cout << "Could not open or" << " find the image\n"; return 0; } // Create a structuring element int morph_size = 2; Mat element = getStructuringElement( MORPH_RECT, Size(2 * morph_size + 1, 2 * morph_size + 1), Point(morph_size, morph_size)); Mat output; // Opening morphologyEx(image, output, MORPH_OPEN, element, Point(-1, -1), 2); // Display the image imshow("source", image); imshow("Opening", output); waitKey(); return 0;} // Driver Codeint main(){ openingMorphological(); return 0;} Output: OpenCV Advanced Computer Subject C++ C++ Programs CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. System Design Tutorial ML | Linear Regression Reinforcement learning Docker - COPY Instruction Supervised and Unsupervised learning Vector in C++ STL Map in C++ Standard Template Library (STL) Initialize a vector in C++ (7 different ways) std::sort() in C++ STL Bitwise Operators in C/C++
[ { "code": null, "e": 28, "s": 0, "text": "\n10 Feb, 2021" }, { "code": null, "e": 100, "s": 28, "text": "In this article, a Morphological operation called Opening is discussed." }, { "code": null, "e": 536, "s": 100, "text": "Opening operation is similar to erosion in the sense that it also removes foreground pixels from the edges of the image. Opening operation is erosion operation followed by dilation. It is usually used for removing internal noise present inside an image. This operator safeguards the foreground region that has similarity with the structuring component or the one that fits inside the structuring element while removing everything else." }, { "code": null, "e": 544, "s": 536, "text": "Syntax:" }, { "code": null, "e": 625, "s": 544, "text": "morphologyEx (src, dst, op, kernel, anchor, iterations, borderType, borderValue)" }, { "code": null, "e": 637, "s": 625, "text": "Parameters:" }, { "code": null, "e": 665, "s": 637, "text": "src: It is the input image." }, { "code": null, "e": 694, "s": 665, "text": "dst: It is the output image." }, { "code": null, "e": 731, "s": 694, "text": "op: Type of morphological operation." }, { "code": null, "e": 777, "s": 731, "text": "kernel: Structuring element used for Closing." }, { "code": null, "e": 925, "s": 777, "text": "anchor: Anchor position inside the structuring element. The default value is [-1, -1} signifying position as the center of the structuring element." }, { "code": null, "e": 973, "s": 925, "text": "iterations: Number of times Closing is applied." }, { "code": null, "e": 1043, "s": 973, "text": "borderType: Type of border ( BORDER_CONSTANT, BORDER_REPLICATE, etc.)" }, { "code": null, "e": 1069, "s": 1043, "text": "borderValue: Border value" }, { "code": null, "e": 1103, "s": 1069, "text": "Return: Output Image (Mat Object)" }, { "code": null, "e": 1152, "s": 1103, "text": "The opening operator is given by the expression:" }, { "code": null, "e": 1307, "s": 1152, "text": "The expression represents that AoB is a subset (sub-image of A). The opening operator removes internal noise and thin protrusions present inside an image." }, { "code": null, "e": 1384, "s": 1307, "text": "Below is the C++ program to demonstrate the Opening Morphological Operation:" }, { "code": null, "e": 1388, "s": 1384, "text": "C++" }, { "code": "// C++ program to demonstrate the// opening morphological transformation#include <iostream>#include <opencv2/core/core.hpp> // Library include for drawing shapes#include <opencv2/highgui/highgui.hpp>#include <opencv2/imgproc.hpp>using namespace cv;using namespace std; // Function to demonstrate the// opening morphological operatorint openingMorphological(){ // Reading the Image Mat image = imread( \"C:/Users/harsh/Downloads/geeks.png\", IMREAD_GRAYSCALE); // Check if the image is // created successfully or not if (!image.data) { cout << \"Could not open or\" << \" find the image\\n\"; return 0; } // Create a structuring element int morph_size = 2; Mat element = getStructuringElement( MORPH_RECT, Size(2 * morph_size + 1, 2 * morph_size + 1), Point(morph_size, morph_size)); Mat output; // Opening morphologyEx(image, output, MORPH_OPEN, element, Point(-1, -1), 2); // Display the image imshow(\"source\", image); imshow(\"Opening\", output); waitKey(); return 0;} // Driver Codeint main(){ openingMorphological(); return 0;}", "e": 2605, "s": 1388, "text": null }, { "code": null, "e": 2613, "s": 2605, "text": "Output:" }, { "code": null, "e": 2620, "s": 2613, "text": "OpenCV" }, { "code": null, "e": 2646, "s": 2620, "text": "Advanced Computer Subject" }, { "code": null, "e": 2650, "s": 2646, "text": "C++" }, { "code": null, "e": 2663, "s": 2650, "text": "C++ Programs" }, { "code": null, "e": 2667, "s": 2663, "text": "CPP" }, { "code": null, "e": 2765, "s": 2667, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2788, "s": 2765, "text": "System Design Tutorial" }, { "code": null, "e": 2811, "s": 2788, "text": "ML | Linear Regression" }, { "code": null, "e": 2834, "s": 2811, "text": "Reinforcement learning" }, { "code": null, "e": 2860, "s": 2834, "text": "Docker - COPY Instruction" }, { "code": null, "e": 2897, "s": 2860, "text": "Supervised and Unsupervised learning" }, { "code": null, "e": 2915, "s": 2897, "text": "Vector in C++ STL" }, { "code": null, "e": 2958, "s": 2915, "text": "Map in C++ Standard Template Library (STL)" }, { "code": null, "e": 3004, "s": 2958, "text": "Initialize a vector in C++ (7 different ways)" }, { "code": null, "e": 3027, "s": 3004, "text": "std::sort() in C++ STL" } ]
Python - Tkinter Menubutton
A menubutton is the part of a drop-down menu that stays on the screen all the time. Every menubutton is associated with a Menu widget that can display the choices for that menubutton when the user clicks on it. Here is the simple syntax to create this widget − w = Menubutton ( master, option, ... ) master − This represents the parent window. master − This represents the parent window. options − Here is the list of most commonly used options for this widget. These options can be used as key-value pairs separated by commas. options − Here is the list of most commonly used options for this widget. These options can be used as key-value pairs separated by commas. activebackground The background color when the mouse is over the menubutton. activeforeground The foreground color when the mouse is over the menubutton. anchor This options controls where the text is positioned if the widget has more space than the text needs. The default is anchor=CENTER, which centers the text. bg The normal background color displayed behind the label and indicator. bitmap To display a bitmap on the menubutton, set this option to a bitmap name. bd The size of the border around the indicator. Default is 2 pixels. cursor The cursor that appears when the mouse is over this menubutton. direction Set direction=LEFT to display the menu to the left of the button; use direction=RIGHT to display the menu to the right of the button; or use direction='above' to place the menu above the button. disabledforeground The foreground color shown on this menubutton when it is disabled. fg The foreground color when the mouse is not over the menubutton. height The height of the menubutton in lines of text (not pixels!). The default is to fit the menubutton's size to its contents. highlightcolor Color shown in the focus highlight when the widget has the focus. image To display an image on this menubutton, justify This option controls where the text is located when the text doesn't fill the menubutton: use justify=LEFT to left-justify the text (this is the default); use justify=CENTER to center it, or justify=RIGHT to right-justify. menu To associate the menubutton with a set of choices, set this option to the Menu object containing those choices. That menu object must have been created by passing the associated menubutton to the constructor as its first argument. padx How much space to leave to the left and right of the text of the menubutton. Default is 1. pady How much space to leave above and below the text of the menubutton. Default is 1. relief Selects three-dimensional border shading effects. The default is RAISED. state Normally, menubuttons respond to the mouse. Set state=DISABLED to gray out the menubutton and make it unresponsive. text To display text on the menubutton, set this option to the string containing the desired text. Newlines ("\n") within the string will cause line breaks. textvariable You can associate a control variable of class StringVar with this menubutton. Setting that control variable will change the displayed text. underline Normally, no underline appears under the text on the menubutton. To underline one of the characters, set this option to the index of that character. width The width of the widget in characters. The default is 20. wraplength Normally, lines are not wrapped. You can set this option to a number of characters and all lines will be broken into pieces no longer than that number. Try the following example yourself − from Tkinter import * import tkMessageBox import Tkinter top = Tk() mb= Menubutton ( top, text="condiments", relief=RAISED ) mb.grid() mb.menu = Menu ( mb, tearoff = 0 ) mb["menu"] = mb.menu mayoVar = IntVar() ketchVar = IntVar() mb.menu.add_checkbutton ( label="mayo", variable=mayoVar ) mb.menu.add_checkbutton ( label="ketchup", variable=ketchVar ) mb.pack() top.mainloop() When the above code is executed, it produces the following result −
[ { "code": null, "e": 2589, "s": 2378, "text": "A menubutton is the part of a drop-down menu that stays on the screen all the time. Every menubutton is associated with a Menu widget that can display the choices for that menubutton when the user clicks on it." }, { "code": null, "e": 2639, "s": 2589, "text": "Here is the simple syntax to create this widget −" }, { "code": null, "e": 2679, "s": 2639, "text": "w = Menubutton ( master, option, ... )\n" }, { "code": null, "e": 2723, "s": 2679, "text": "master − This represents the parent window." }, { "code": null, "e": 2767, "s": 2723, "text": "master − This represents the parent window." }, { "code": null, "e": 2907, "s": 2767, "text": "options − Here is the list of most commonly used options for this widget. These options can be used as key-value pairs separated by commas." }, { "code": null, "e": 3047, "s": 2907, "text": "options − Here is the list of most commonly used options for this widget. These options can be used as key-value pairs separated by commas." }, { "code": null, "e": 3064, "s": 3047, "text": "activebackground" }, { "code": null, "e": 3124, "s": 3064, "text": "The background color when the mouse is over the menubutton." }, { "code": null, "e": 3141, "s": 3124, "text": "activeforeground" }, { "code": null, "e": 3201, "s": 3141, "text": "The foreground color when the mouse is over the menubutton." }, { "code": null, "e": 3208, "s": 3201, "text": "anchor" }, { "code": null, "e": 3364, "s": 3208, "text": "This options controls where the text is positioned if the widget has more space than the text needs. The default is anchor=CENTER, which centers the text. " }, { "code": null, "e": 3367, "s": 3364, "text": "bg" }, { "code": null, "e": 3437, "s": 3367, "text": "The normal background color displayed behind the label and indicator." }, { "code": null, "e": 3444, "s": 3437, "text": "bitmap" }, { "code": null, "e": 3517, "s": 3444, "text": "To display a bitmap on the menubutton, set this option to a bitmap name." }, { "code": null, "e": 3521, "s": 3517, "text": "bd " }, { "code": null, "e": 3587, "s": 3521, "text": "The size of the border around the indicator. Default is 2 pixels." }, { "code": null, "e": 3594, "s": 3587, "text": "cursor" }, { "code": null, "e": 3659, "s": 3594, "text": "The cursor that appears when the mouse is over this menubutton. " }, { "code": null, "e": 3669, "s": 3659, "text": "direction" }, { "code": null, "e": 3864, "s": 3669, "text": "Set direction=LEFT to display the menu to the left of the button; use direction=RIGHT to display the menu to the right of the button; or use direction='above' to place the menu above the button." }, { "code": null, "e": 3883, "s": 3864, "text": "disabledforeground" }, { "code": null, "e": 3950, "s": 3883, "text": "The foreground color shown on this menubutton when it is disabled." }, { "code": null, "e": 3953, "s": 3950, "text": "fg" }, { "code": null, "e": 4017, "s": 3953, "text": "The foreground color when the mouse is not over the menubutton." }, { "code": null, "e": 4024, "s": 4017, "text": "height" }, { "code": null, "e": 4146, "s": 4024, "text": "The height of the menubutton in lines of text (not pixels!). The default is to fit the menubutton's size to its contents." }, { "code": null, "e": 4161, "s": 4146, "text": "highlightcolor" }, { "code": null, "e": 4227, "s": 4161, "text": "Color shown in the focus highlight when the widget has the focus." }, { "code": null, "e": 4233, "s": 4227, "text": "image" }, { "code": null, "e": 4274, "s": 4233, "text": "To display an image on this menubutton, " }, { "code": null, "e": 4282, "s": 4274, "text": "justify" }, { "code": null, "e": 4505, "s": 4282, "text": "This option controls where the text is located when the text doesn't fill the menubutton: use justify=LEFT to left-justify the text (this is the default); use justify=CENTER to center it, or justify=RIGHT to right-justify." }, { "code": null, "e": 4510, "s": 4505, "text": "menu" }, { "code": null, "e": 4741, "s": 4510, "text": "To associate the menubutton with a set of choices, set this option to the Menu object containing those choices. That menu object must have been created by passing the associated menubutton to the constructor as its first argument." }, { "code": null, "e": 4746, "s": 4741, "text": "padx" }, { "code": null, "e": 4837, "s": 4746, "text": "How much space to leave to the left and right of the text of the menubutton. Default is 1." }, { "code": null, "e": 4842, "s": 4837, "text": "pady" }, { "code": null, "e": 4924, "s": 4842, "text": "How much space to leave above and below the text of the menubutton. Default is 1." }, { "code": null, "e": 4931, "s": 4924, "text": "relief" }, { "code": null, "e": 5004, "s": 4931, "text": "Selects three-dimensional border shading effects. The default is RAISED." }, { "code": null, "e": 5010, "s": 5004, "text": "state" }, { "code": null, "e": 5126, "s": 5010, "text": "Normally, menubuttons respond to the mouse. Set state=DISABLED to gray out the menubutton and make it unresponsive." }, { "code": null, "e": 5131, "s": 5126, "text": "text" }, { "code": null, "e": 5283, "s": 5131, "text": "To display text on the menubutton, set this option to the string containing the desired text. Newlines (\"\\n\") within the string will cause line breaks." }, { "code": null, "e": 5296, "s": 5283, "text": "textvariable" }, { "code": null, "e": 5436, "s": 5296, "text": "You can associate a control variable of class StringVar with this menubutton. Setting that control variable will change the displayed text." }, { "code": null, "e": 5446, "s": 5436, "text": "underline" }, { "code": null, "e": 5595, "s": 5446, "text": "Normally, no underline appears under the text on the menubutton. To underline one of the characters, set this option to the index of that character." }, { "code": null, "e": 5601, "s": 5595, "text": "width" }, { "code": null, "e": 5659, "s": 5601, "text": "The width of the widget in characters. The default is 20." }, { "code": null, "e": 5670, "s": 5659, "text": "wraplength" }, { "code": null, "e": 5822, "s": 5670, "text": "Normally, lines are not wrapped. You can set this option to a number of characters and all lines will be broken into pieces no longer than that number." }, { "code": null, "e": 5859, "s": 5822, "text": "Try the following example yourself −" }, { "code": null, "e": 6296, "s": 5859, "text": "from Tkinter import *\nimport tkMessageBox\nimport Tkinter\n\ntop = Tk()\n\nmb= Menubutton ( top, text=\"condiments\", relief=RAISED )\nmb.grid()\nmb.menu = Menu ( mb, tearoff = 0 )\nmb[\"menu\"] = mb.menu\n\nmayoVar = IntVar()\nketchVar = IntVar()\n\nmb.menu.add_checkbutton ( label=\"mayo\",\n variable=mayoVar )\nmb.menu.add_checkbutton ( label=\"ketchup\",\n variable=ketchVar )\n\nmb.pack()\ntop.mainloop()" } ]
Java.lang.String.replace() in Java
03 Oct, 2021 This method searches for a specified string or a specified value, or a regex expression by virtue of which has the same suggests returns a new string with related characters. replace() method of strings contains three variants here are three variants of replace() method. There are 3 types that are frequently used for String.replace() and is also aid in problem solving capabilities. replace() replaceAll() replaceFirst() #1: String.replace() This method returns a new string resulting from replacing all occurrences of old characters in the string with new characters. Syntax: public String replace(char oldch, char newch) Parameters: The old character The new character Return Type: It returns a string derived from this string by replacing every occurrence of oldch with newch. Example Java // Java code to demonstrate the// Working of replace() method // Main classpublic class GFG { // Main driver method public static void main(String args[]) { // Declaring and initialising custom input string String Str = new String("Welcome to geeksforgeeks"); // Using replace to replace characters System.out.print("After replacing all o with T : "); System.out.println(Str.replace('o', 'T')); // Using replace to replace characters System.out.print("After replacing all e with D : "); System.out.println(Str.replace('e', 'D')); }} After replacing all o with T : WelcTme tT geeksfTrgeeks After replacing all e with D : WDlcomD to gDDksforgDDks #2: String replaceAll() This method replaces each substring of the string that matches the given regular expression with the given replace_str. Syntax: public String replaceAll(String regex, String replace_str) Parameters: The regular expression to which this string is to be matched. The string which would replace found expression Return Value This method returns the resulting String Example Java // Java Program to demonstrate the// working of replaceAll() // Main classpublic class rep2 { // Main driver method public static void main(String args[]) { // Declaring and initialising String String Str = new String("Welcome to geeksforgeeks"); // Display message System.out.print("Original String : "); // Printing original string System.out.println(Str); // Display message System.out.print( "After replacing regex with replace_str : "); // Using replaceAll to replace regex // with replace_str System.out.println( Str.replaceAll("(.*)geeks(.*)", "ASTHA TYAGI")); }} Original String : Welcome to geeksforgeeks After replacing regex with replace_str : ASTHA TYAGI #3: String replaceFirst() This method replaces the first substring of this string that matches the given regular expression with the given replace_str. Syntax: public String replaceFirst(String regex, String replace_str) Parameters The regular expression to which this string is to be matched. The string which would replace found expression. Return Type: A resulting string Example: Java // Java code to demonstrate the// working of replaceFirst()public class rep3 { public static void main(String args[]) { // Initialising String String Str = new String("Welcome to geeksforgeeks"); // original string System.out.print("Original String : " ); System.out.println(Str); // Using replaceFirst to replace regex with replace_str // Replaces 1st occurrence of geeks with ASTHA System.out.print("After replacing 1st occurrence of regex with replace_str : " ); System.out.println(Str.replaceFirst("geeks", "ASTHA")); }} Output: Original String : Welcome to geeksforgeeks After replacing 1st occurrence of regex with replace_str : Welcome to ASTHAforgeeks This article is contributed by Astha Tyagi. 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. solankimayank Java-lang package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java How to iterate any Map in Java Interfaces in Java HashMap in Java with Examples ArrayList in Java Stream In Java Collections in Java Multidimensional Arrays in Java Singleton Class in Java Stack Class in Java
[ { "code": null, "e": 52, "s": 24, "text": "\n03 Oct, 2021" }, { "code": null, "e": 324, "s": 52, "text": "This method searches for a specified string or a specified value, or a regex expression by virtue of which has the same suggests returns a new string with related characters. replace() method of strings contains three variants here are three variants of replace() method." }, { "code": null, "e": 437, "s": 324, "text": "There are 3 types that are frequently used for String.replace() and is also aid in problem solving capabilities." }, { "code": null, "e": 447, "s": 437, "text": "replace()" }, { "code": null, "e": 460, "s": 447, "text": "replaceAll()" }, { "code": null, "e": 475, "s": 460, "text": "replaceFirst()" }, { "code": null, "e": 496, "s": 475, "text": "#1: String.replace()" }, { "code": null, "e": 624, "s": 496, "text": "This method returns a new string resulting from replacing all occurrences of old characters in the string with new characters. " }, { "code": null, "e": 632, "s": 624, "text": "Syntax:" }, { "code": null, "e": 678, "s": 632, "text": "public String replace(char oldch, char newch)" }, { "code": null, "e": 691, "s": 678, "text": "Parameters: " }, { "code": null, "e": 709, "s": 691, "text": "The old character" }, { "code": null, "e": 727, "s": 709, "text": "The new character" }, { "code": null, "e": 740, "s": 727, "text": "Return Type:" }, { "code": null, "e": 836, "s": 740, "text": "It returns a string derived from this string by replacing every occurrence of oldch with newch." }, { "code": null, "e": 844, "s": 836, "text": "Example" }, { "code": null, "e": 849, "s": 844, "text": "Java" }, { "code": "// Java code to demonstrate the// Working of replace() method // Main classpublic class GFG { // Main driver method public static void main(String args[]) { // Declaring and initialising custom input string String Str = new String(\"Welcome to geeksforgeeks\"); // Using replace to replace characters System.out.print(\"After replacing all o with T : \"); System.out.println(Str.replace('o', 'T')); // Using replace to replace characters System.out.print(\"After replacing all e with D : \"); System.out.println(Str.replace('e', 'D')); }}", "e": 1455, "s": 849, "text": null }, { "code": null, "e": 1567, "s": 1455, "text": "After replacing all o with T : WelcTme tT geeksfTrgeeks\nAfter replacing all e with D : WDlcomD to gDDksforgDDks" }, { "code": null, "e": 1591, "s": 1567, "text": "#2: String replaceAll()" }, { "code": null, "e": 1711, "s": 1591, "text": "This method replaces each substring of the string that matches the given regular expression with the given replace_str." }, { "code": null, "e": 1719, "s": 1711, "text": "Syntax:" }, { "code": null, "e": 1778, "s": 1719, "text": "public String replaceAll(String regex, String replace_str)" }, { "code": null, "e": 1790, "s": 1778, "text": "Parameters:" }, { "code": null, "e": 1852, "s": 1790, "text": "The regular expression to which this string is to be matched." }, { "code": null, "e": 1900, "s": 1852, "text": "The string which would replace found expression" }, { "code": null, "e": 1954, "s": 1900, "text": "Return Value\nThis method returns the resulting String" }, { "code": null, "e": 1962, "s": 1954, "text": "Example" }, { "code": null, "e": 1967, "s": 1962, "text": "Java" }, { "code": "// Java Program to demonstrate the// working of replaceAll() // Main classpublic class rep2 { // Main driver method public static void main(String args[]) { // Declaring and initialising String String Str = new String(\"Welcome to geeksforgeeks\"); // Display message System.out.print(\"Original String : \"); // Printing original string System.out.println(Str); // Display message System.out.print( \"After replacing regex with replace_str : \"); // Using replaceAll to replace regex // with replace_str System.out.println( Str.replaceAll(\"(.*)geeks(.*)\", \"ASTHA TYAGI\")); }}", "e": 2656, "s": 1967, "text": null }, { "code": null, "e": 2752, "s": 2656, "text": "Original String : Welcome to geeksforgeeks\nAfter replacing regex with replace_str : ASTHA TYAGI" }, { "code": null, "e": 2778, "s": 2752, "text": "#3: String replaceFirst()" }, { "code": null, "e": 2905, "s": 2778, "text": "This method replaces the first substring of this string that matches the given regular expression with the given replace_str. " }, { "code": null, "e": 2913, "s": 2905, "text": "Syntax:" }, { "code": null, "e": 2974, "s": 2913, "text": "public String replaceFirst(String regex, String replace_str)" }, { "code": null, "e": 2985, "s": 2974, "text": "Parameters" }, { "code": null, "e": 3047, "s": 2985, "text": "The regular expression to which this string is to be matched." }, { "code": null, "e": 3096, "s": 3047, "text": "The string which would replace found expression." }, { "code": null, "e": 3128, "s": 3096, "text": "Return Type: A resulting string" }, { "code": null, "e": 3137, "s": 3128, "text": "Example:" }, { "code": null, "e": 3142, "s": 3137, "text": "Java" }, { "code": "// Java code to demonstrate the// working of replaceFirst()public class rep3 { public static void main(String args[]) { // Initialising String String Str = new String(\"Welcome to geeksforgeeks\"); // original string System.out.print(\"Original String : \" ); System.out.println(Str); // Using replaceFirst to replace regex with replace_str // Replaces 1st occurrence of geeks with ASTHA System.out.print(\"After replacing 1st occurrence of regex with replace_str : \" ); System.out.println(Str.replaceFirst(\"geeks\", \"ASTHA\")); }}", "e": 3747, "s": 3142, "text": null }, { "code": null, "e": 3756, "s": 3747, "text": "Output: " }, { "code": null, "e": 3884, "s": 3756, "text": "Original String : Welcome to geeksforgeeks\nAfter replacing 1st occurrence of regex with replace_str : Welcome to ASTHAforgeeks" }, { "code": null, "e": 4304, "s": 3884, "text": "This article is contributed by Astha Tyagi. 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": 4318, "s": 4304, "text": "solankimayank" }, { "code": null, "e": 4336, "s": 4318, "text": "Java-lang package" }, { "code": null, "e": 4341, "s": 4336, "text": "Java" }, { "code": null, "e": 4346, "s": 4341, "text": "Java" }, { "code": null, "e": 4444, "s": 4346, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4495, "s": 4444, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 4526, "s": 4495, "text": "How to iterate any Map in Java" }, { "code": null, "e": 4545, "s": 4526, "text": "Interfaces in Java" }, { "code": null, "e": 4575, "s": 4545, "text": "HashMap in Java with Examples" }, { "code": null, "e": 4593, "s": 4575, "text": "ArrayList in Java" }, { "code": null, "e": 4608, "s": 4593, "text": "Stream In Java" }, { "code": null, "e": 4628, "s": 4608, "text": "Collections in Java" }, { "code": null, "e": 4660, "s": 4628, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 4684, "s": 4660, "text": "Singleton Class in Java" } ]
Python | Find all triplets in a list with given sum
30 Jul, 2019 Given a list of integers, write a Python program to find all triplets that sum up to given integer ‘k’. Examples: Input : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], k = 10 Output : [(1, 5, 4), (1, 6, 3), (1, 7, 2), (2, 5, 3)] Input : [12, 3, 6, 1, 6, 9], k = 24 Output : [(12, 6, 6), (12, 9, 3)] Approach #1 : Naive (Using set)In this approach, we use two for loops. The first loop sets first element, another to check whether other two elements including first sums up to k or not. This approach takes O(n2) time complexity. # Python3 program to Find total number # of triplets in a temp_list with given k def findTriplets(lst, k): triplet_count = 0 final_temp_list =[] for i in range(0, len(lst)-1): s = set() temp_list = [] # Adding first element temp_list.append(lst[i]) curr_k = k - lst[i] for j in range(i + 1, len(lst)): if (curr_k - lst[j]) in s: triplet_count += 1 # Adding second element temp_list.append(lst[j]) # Adding third element temp_list.append(curr_k - lst[j]) # Appending tuple to the final list final_temp_list.append(tuple(temp_list)) temp_list.pop(2) temp_list.pop(1) s.add(lst[j]) return final_temp_list # Driver Codelst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]k = 10print(findTriplets(lst, k)) [(1, 5, 4), (1, 6, 3), (1, 7, 2), (2, 5, 3)] Approach #2 : Using itertoolsPython itertools module provide combination(iterable, r) function. This tool returns the r length subsequences of elements from the input iterable. Every time we make a combination of 3 elements and check if they sums up to k or not. # Python3 program to Find total number # of triplets in a list with given sumfrom itertools import combinations def findTriplets(lst, key): def valid(val): return sum(val) == key return list(filter(valid, list(combinations(lst, 3)))) # Driver Codelst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]print(findTriplets(lst, 10)) [(1, 2, 7), (1, 3, 6), (1, 4, 5), (2, 3, 5)] ManasChhabra2 Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python | Convert string dictionary to dictionary
[ { "code": null, "e": 54, "s": 26, "text": "\n30 Jul, 2019" }, { "code": null, "e": 158, "s": 54, "text": "Given a list of integers, write a Python program to find all triplets that sum up to given integer ‘k’." }, { "code": null, "e": 168, "s": 158, "text": "Examples:" }, { "code": null, "e": 342, "s": 168, "text": "Input : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], k = 10\nOutput : [(1, 5, 4), (1, 6, 3), (1, 7, 2), (2, 5, 3)]\n\nInput : [12, 3, 6, 1, 6, 9], k = 24\nOutput : [(12, 6, 6), (12, 9, 3)]\n" }, { "code": null, "e": 572, "s": 342, "text": "Approach #1 : Naive (Using set)In this approach, we use two for loops. The first loop sets first element, another to check whether other two elements including first sums up to k or not. This approach takes O(n2) time complexity." }, { "code": "# Python3 program to Find total number # of triplets in a temp_list with given k def findTriplets(lst, k): triplet_count = 0 final_temp_list =[] for i in range(0, len(lst)-1): s = set() temp_list = [] # Adding first element temp_list.append(lst[i]) curr_k = k - lst[i] for j in range(i + 1, len(lst)): if (curr_k - lst[j]) in s: triplet_count += 1 # Adding second element temp_list.append(lst[j]) # Adding third element temp_list.append(curr_k - lst[j]) # Appending tuple to the final list final_temp_list.append(tuple(temp_list)) temp_list.pop(2) temp_list.pop(1) s.add(lst[j]) return final_temp_list # Driver Codelst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]k = 10print(findTriplets(lst, k))", "e": 1576, "s": 572, "text": null }, { "code": null, "e": 1622, "s": 1576, "text": "[(1, 5, 4), (1, 6, 3), (1, 7, 2), (2, 5, 3)]\n" }, { "code": null, "e": 1886, "s": 1622, "text": " Approach #2 : Using itertoolsPython itertools module provide combination(iterable, r) function. This tool returns the r length subsequences of elements from the input iterable. Every time we make a combination of 3 elements and check if they sums up to k or not." }, { "code": "# Python3 program to Find total number # of triplets in a list with given sumfrom itertools import combinations def findTriplets(lst, key): def valid(val): return sum(val) == key return list(filter(valid, list(combinations(lst, 3)))) # Driver Codelst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]print(findTriplets(lst, 10))", "e": 2231, "s": 1886, "text": null }, { "code": null, "e": 2277, "s": 2231, "text": "[(1, 2, 7), (1, 3, 6), (1, 4, 5), (2, 3, 5)]\n" }, { "code": null, "e": 2291, "s": 2277, "text": "ManasChhabra2" }, { "code": null, "e": 2312, "s": 2291, "text": "Python list-programs" }, { "code": null, "e": 2319, "s": 2312, "text": "Python" }, { "code": null, "e": 2335, "s": 2319, "text": "Python Programs" }, { "code": null, "e": 2433, "s": 2335, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2451, "s": 2433, "text": "Python Dictionary" }, { "code": null, "e": 2493, "s": 2451, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2515, "s": 2493, "text": "Enumerate() in Python" }, { "code": null, "e": 2550, "s": 2515, "text": "Read a file line by line in Python" }, { "code": null, "e": 2576, "s": 2550, "text": "Python String | replace()" }, { "code": null, "e": 2619, "s": 2576, "text": "Python program to convert a list to string" }, { "code": null, "e": 2641, "s": 2619, "text": "Defaultdict in Python" }, { "code": null, "e": 2680, "s": 2641, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 2718, "s": 2680, "text": "Python | Convert a list to dictionary" } ]
What are the differences between get() and navigate() method?
The differences between get() and navigate() methods are listed below. With get(). import org.openqa.selenium.By; import org.openqa.selenium.Keys; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import java.util.concurrent.TimeUnit; import java.util.List; public class LaunchBrw { 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); driver.close(); } } With navigate(). import org.openqa.selenium.By; import org.openqa.selenium.Keys; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import java.util.concurrent.TimeUnit; import java.util.List; public class BrowserNavigation { 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"; // new browser will launch and navigate to the URL driver.navigate().to(url); driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS); // refresh the current browser driver.navigate().refresh(); //Using id tagname attribute combination for css expression driver.findElement(By.cssSelector("input[name=’search’]")). sendKeys("Selenium"); //browser will go back to the previous page driver.navigate().back(); //browser will go move to the next page driver.navigate().forward(); driver.close(); } }
[ { "code": null, "e": 1258, "s": 1187, "text": "The differences between get() and navigate() methods are listed below." }, { "code": null, "e": 1270, "s": 1258, "text": "With get()." }, { "code": null, "e": 1928, "s": 1270, "text": "import org.openqa.selenium.By;\nimport org.openqa.selenium.Keys;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.chrome.ChromeDriver;\nimport java.util.concurrent.TimeUnit;\nimport java.util.List;\npublic class LaunchBrw {\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 driver.close();\n }\n}" }, { "code": null, "e": 1945, "s": 1928, "text": "With navigate()." }, { "code": null, "e": 3067, "s": 1945, "text": "import org.openqa.selenium.By;\nimport org.openqa.selenium.Keys;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.chrome.ChromeDriver;\nimport java.util.concurrent.TimeUnit;\nimport java.util.List;\npublic class BrowserNavigation {\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 // new browser will launch and navigate to the URL\n driver.navigate().to(url);\n driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS);\n // refresh the current browser\n driver.navigate().refresh();\n //Using id tagname attribute combination for css expression\n driver.findElement(By.cssSelector(\"input[name=’search’]\")). sendKeys(\"Selenium\");\n //browser will go back to the previous page\n driver.navigate().back();\n //browser will go move to the next page\n driver.navigate().forward();\n driver.close();\n }\n}" } ]
Python math function | copysign()
01 Jan, 2019 math.copysign() is a function exists in Standard math Library of Python. This function returns a float value consisting of magnitude from parameter x and the sign (+ve or -ve) from parameter y. Syntax : math.copysign(x, y) Parameters :x : Integer value to be convertedy : Integer whose sign is required Returns : float value consisting of magnitude from parameter x and the sign from parameter y. Code #1: # Python code to demonstrate copy.sign() functionimport math def func(): a = 5 b = -7 # implementation of copysign c = math.copysign(a, b) return c print (func()) Output : -5.0 Code #2: # Python code to demonstrate copy.sign() functionimport math def func(): a = 10 b = 10 # implementation of copysign c = math.copysign(a, b) return c print (func()) Output : 10 Python math-library-functions Python-Built-in-functions 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 Iterate over a list in Python Python Classes and Objects Convert integer to string in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Jan, 2019" }, { "code": null, "e": 222, "s": 28, "text": "math.copysign() is a function exists in Standard math Library of Python. This function returns a float value consisting of magnitude from parameter x and the sign (+ve or -ve) from parameter y." }, { "code": null, "e": 251, "s": 222, "text": "Syntax : math.copysign(x, y)" }, { "code": null, "e": 331, "s": 251, "text": "Parameters :x : Integer value to be convertedy : Integer whose sign is required" }, { "code": null, "e": 425, "s": 331, "text": "Returns : float value consisting of magnitude from parameter x and the sign from parameter y." }, { "code": null, "e": 434, "s": 425, "text": "Code #1:" }, { "code": "# Python code to demonstrate copy.sign() functionimport math def func(): a = 5 b = -7 # implementation of copysign c = math.copysign(a, b) return c print (func())", "e": 632, "s": 434, "text": null }, { "code": null, "e": 641, "s": 632, "text": "Output :" }, { "code": null, "e": 646, "s": 641, "text": "-5.0" }, { "code": null, "e": 656, "s": 646, "text": " Code #2:" }, { "code": "# Python code to demonstrate copy.sign() functionimport math def func(): a = 10 b = 10 # implementation of copysign c = math.copysign(a, b) return c print (func())", "e": 855, "s": 656, "text": null }, { "code": null, "e": 864, "s": 855, "text": "Output :" }, { "code": null, "e": 867, "s": 864, "text": "10" }, { "code": null, "e": 897, "s": 867, "text": "Python math-library-functions" }, { "code": null, "e": 923, "s": 897, "text": "Python-Built-in-functions" }, { "code": null, "e": 930, "s": 923, "text": "Python" }, { "code": null, "e": 1028, "s": 930, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1046, "s": 1028, "text": "Python Dictionary" }, { "code": null, "e": 1088, "s": 1046, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1110, "s": 1088, "text": "Enumerate() in Python" }, { "code": null, "e": 1145, "s": 1110, "text": "Read a file line by line in Python" }, { "code": null, "e": 1171, "s": 1145, "text": "Python String | replace()" }, { "code": null, "e": 1203, "s": 1171, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1232, "s": 1203, "text": "*args and **kwargs in Python" }, { "code": null, "e": 1262, "s": 1232, "text": "Iterate over a list in Python" }, { "code": null, "e": 1289, "s": 1262, "text": "Python Classes and Objects" } ]
Detect Cycle in a Directed Graph
Using a Depth First Search (DFS) traversal algorithm we can detect cycles in a directed graph. If there is any self-loop in any node, it will be considered as a cycle, otherwise, when the child node has another edge to connect its parent, it will also a cycle. For the disconnected graph, there may different trees present, we can call them a forest. Now we have to detect cycle for all trees of the forest. In this approach, we will use different sets to assign nodes to perform the DFS traversal. There are three different sets, the White, Grey and the Black. Initially, all nodes will be stored inside the white set. When one new node is traversed, it will be stored in the gray set and removed from the white one. And after completing backtracking, when that task for that node is completed, it will be swapped from gray to black set. Input: The Adjacency matrix. 0 1 0 0 0 0 0 0 0 0 1 0 0 1 0 0 0 0 0 1 0 0 1 0 0 Output: The graph has cycle. dfs(curr, wSet, gSet, bSet) Input: Current node, the white, the grey and the black set. Output: True if there is a cycle. Begin delete curr from the while set and add it to the grey set for all nodes v connected with curr in the graph, do if v is in the black set, then skip next part, and go for next iteration if v is in the grey set, then return true if dfs(v, wSet, gSet, bSet) is true, then return true done delete curr from grey set and add to black set return fasle End hasCycle(graph) Input − Given Graph. Output: True when the graph has cycled. Begin initially insert all nodes into the white set while white set has some elements, do for all nodes v in the graph, do if v is not in the white set, then if dfs(v, wSet, gSet, bSet), then return true done done return false End #include<iostream> #include<set> #define NODE 5 using namespace std; int graph[NODE][NODE] = { {0, 1, 0, 0, 0}, {0, 0, 0, 0, 0}, {1, 0, 0, 1, 0}, {0, 0, 0, 0, 1}, {0, 0, 1, 0, 0} }; bool dfs(int curr, set<int>&wSet, set<int>&gSet, set<int>&bSet) { //moving curr to white set to grey set. wSet.erase(wSet.find(curr)); gSet.insert(curr); for(int v = 0; v < NODE; v++) { if(graph[curr][v] != 0) { //for all neighbour vertices if(bSet.find(v) != bSet.end()) continue; //if the vertices are in the black set if(gSet.find(v) != gSet.end()) return true; //it is a cycle if(dfs(v, wSet, gSet, bSet)) return true; //cycle found } } //moving v to grey set to black set. gSet.erase(gSet.find(curr)); bSet.insert(curr); return false; } bool hasCycle() { set<int> wSet, gSet, bSet; //three set as white, grey and black for(int i = 0; i<NODE; i++) wSet.insert(i); //initially add all node into the white set while(wSet.size() > 0) { for(int current = 0; current < NODE; current++) { if(wSet.find(current) != wSet.end()) if(dfs(current, wSet, gSet, bSet)) return true; } } return false; } int main() { bool res; res = hasCycle(); if(res) cout << "The graph has cycle." << endl; else cout << "The graph has no cycle." << endl; } The graph has cycle.
[ { "code": null, "e": 1448, "s": 1187, "text": "Using a Depth First Search (DFS) traversal algorithm we can detect cycles in a directed graph. If there is any self-loop in any node, it will be considered as a cycle, otherwise, when the child node has another edge to connect its parent, it will also a cycle." }, { "code": null, "e": 1595, "s": 1448, "text": "For the disconnected graph, there may different trees present, we can call them a forest. Now we have to detect cycle for all trees of the forest." }, { "code": null, "e": 2026, "s": 1595, "text": "In this approach, we will use different sets to assign nodes to perform the DFS traversal. There are three different sets, the White, Grey and the Black. Initially, all nodes will be stored inside the white set. When one new node is traversed, it will be stored in the gray set and removed from the white one. And after completing backtracking, when that task for that node is completed, it will be swapped from gray to black set." }, { "code": null, "e": 2137, "s": 2026, "text": "Input:\nThe Adjacency matrix.\n\n0 1 0 0 0\n0 0 0 0 0\n1 0 0 1 0\n0 0 0 0 1\n0 0 1 0 0\n\nOutput:\nThe graph has cycle. " }, { "code": null, "e": 2165, "s": 2137, "text": "dfs(curr, wSet, gSet, bSet)" }, { "code": null, "e": 2225, "s": 2165, "text": "Input: Current node, the white, the grey and the black set." }, { "code": null, "e": 2259, "s": 2225, "text": "Output: True if there is a cycle." }, { "code": null, "e": 2674, "s": 2259, "text": "Begin\n delete curr from the while set and add it to the grey set\n for all nodes v connected with curr in the graph, do\n if v is in the black set, then\n skip next part, and go for next iteration\n if v is in the grey set, then\n return true\n if dfs(v, wSet, gSet, bSet) is true, then\n return true\n done\n delete curr from grey set and add to black set\n return fasle\nEnd" }, { "code": null, "e": 2690, "s": 2674, "text": "hasCycle(graph)" }, { "code": null, "e": 2711, "s": 2690, "text": "Input − Given Graph." }, { "code": null, "e": 2751, "s": 2711, "text": "Output: True when the graph has cycled." }, { "code": null, "e": 3042, "s": 2751, "text": "Begin\n initially insert all nodes into the white set\n while white set has some elements, do\n for all nodes v in the graph, do\n if v is not in the white set, then\n if dfs(v, wSet, gSet, bSet), then\n return true\n done\n done\n return false\nEnd" }, { "code": null, "e": 4490, "s": 3042, "text": "#include<iostream>\n#include<set>\n#define NODE 5\nusing namespace std;\n\nint graph[NODE][NODE] = {\n {0, 1, 0, 0, 0},\n {0, 0, 0, 0, 0},\n {1, 0, 0, 1, 0},\n {0, 0, 0, 0, 1},\n {0, 0, 1, 0, 0}\n};\n\nbool dfs(int curr, set<int>&wSet, set<int>&gSet, set<int>&bSet) {\n //moving curr to white set to grey set.\n wSet.erase(wSet.find(curr));\n gSet.insert(curr);\n\n for(int v = 0; v < NODE; v++) {\n if(graph[curr][v] != 0) { //for all neighbour vertices\n if(bSet.find(v) != bSet.end())\n continue; //if the vertices are in the black set\n if(gSet.find(v) != gSet.end())\n return true; //it is a cycle\n if(dfs(v, wSet, gSet, bSet))\n return true; //cycle found\n }\n }\n\n //moving v to grey set to black set.\n gSet.erase(gSet.find(curr));\n bSet.insert(curr);\n return false;\n}\n\nbool hasCycle() {\n set<int> wSet, gSet, bSet; //three set as white, grey and black\n for(int i = 0; i<NODE; i++)\n wSet.insert(i); //initially add all node into the white set\n\n while(wSet.size() > 0) {\n for(int current = 0; current < NODE; current++) {\n if(wSet.find(current) != wSet.end())\n if(dfs(current, wSet, gSet, bSet))\n return true;\n }\n }\n return false;\n}\n\nint main() {\n bool res;\n res = hasCycle();\n if(res)\n cout << \"The graph has cycle.\" << endl;\n else\n cout << \"The graph has no cycle.\" << endl;\n}" }, { "code": null, "e": 4511, "s": 4490, "text": "The graph has cycle." } ]
Python Program to Convert Binary to Hexadecimal
14 Sep, 2021 Given a binary number, the task is to write a Python program to convert the given binary number into an equivalent hexadecimal number. i.e convert the number with base value 2 to base value 16. In hexadecimal representation we 16 values to represent a number. Numbers 0-9 are expressed by digits 0-9 and 10-15 are represented by characters from A – F. Example: Input: 1111 Output: F Input: 110101 Output: 35 Input: 100001111 Output: 10F Step 1: Input binary number. Input: 111101111011 Step 2: Divide your binary number into groups of four, starting from right. 111101111011 = (1111)(0111)(1011) Step 3: Convert one 4-digit group of a binary number to one hexadecimal digit. (1111)(0111)(1011) = F7B Below is the Python implementation of the above approach: Python3 # Python code to convert binary number# into hexadecimal number # function to convert# binary to hexadecimal def binToHexa(n): bnum = int(n) temp = 0 mul = 1 # counter to check group of 4 count = 1 # char array to store hexadecimal number hexaDeciNum = ['0'] * 100 # counter for hexadecimal number array i = 0 while bnum != 0: rem = bnum % 10 temp = temp + (rem*mul) # check if group of 4 completed if count % 4 == 0: # check if temp < 10 if temp < 10: hexaDeciNum[i] = chr(temp+48) else: hexaDeciNum[i] = chr(temp+55) mul = 1 temp = 0 count = 1 i = i+1 # group of 4 is not completed else: mul = mul*2 count = count+1 bnum = int(bnum/10) # check if at end the group of 4 is not # completed if count != 1: hexaDeciNum[i] = chr(temp+48) # check at end the group of 4 is completed if count == 1: i = i-1 # printing hexadecimal number # array in reverse order print("\n Hexadecimal equivalent of {}: ".format(n), end="") while i >= 0: print(end=hexaDeciNum[i]) i = i-1 # Driver codeif __name__ == '__main__': binToHexa('1111') binToHexa('110101') binToHexa('100001111') binToHexa('111101111011') Output: Hexadecimal equivalent of 1111: F Hexadecimal equivalent of 110101: 35 Hexadecimal equivalent of 100001111: 10F Hexadecimal equivalent of 111101111011: F7B Step 1: Input binary number. Input: 111101111011 = (111101111011)2 Step 2: Convert binary number to decimal number. (111101111011)2 = (3963)10 Step 3: Convert the above decimal number to a hexadecimal number. (3963)10 = (F7B)16 Below is the Python implementation of the above approach: Python3 # Python program to convert binary number# into hexadecimal number # Function calculates the decimal equivalent# to given binary numberdef binaryToDecimal(binary): binary1 = int(binary) decimal, i, n = 0, 0, 0 while(binary1 != 0): dec = binary1 % 10 decimal = decimal + dec * pow(2, i) binary1 = binary1//10 i += 1 return(decimal) # function to convert# decimal to hexadecimaldef decToHexa(n): # char array to store # hexadecimal number hexaDeciNum = ['0'] * 100 # counter for hexadecimal # number array i = 0 while(n != 0): # temporary variable # to store remainder temp = 0 # storing remainder # in temp variable. temp = n % 16 # check if temp < 10 if(temp < 10): hexaDeciNum[i] = chr(temp + 48) i = i + 1 else: hexaDeciNum[i] = chr(temp + 55) i = i + 1 n = int(n / 16) # printing hexadecimal number # array in reverse order j = i - 1 while(j >= 0): print((hexaDeciNum[j]), end="") j = j - 1 print() # function to convert binary to# hexadecimaldef binToHexa(n): decimal = binaryToDecimal(n) print("Hexadecimal equivalent of {}: ".format(n)) decToHexa(decimal) # Driver codeif __name__ == '__main__': binToHexa('1111') binToHexa('110101') binToHexa('100001111') binToHexa('111101111011') Output: Hexadecimal equivalent of 1111: F Hexadecimal equivalent of 110101: 35 Hexadecimal equivalent of 100001111: 10F Hexadecimal equivalent of 111101111011: F7B We use int() and hex() to convert a binary number to its equivalent hexadecimal number. Below is the Python implementation using int() and hex(). Python3 # Python code to convert from Binary# to Hexadecimal using int() and hex()def binToHexa(n): # convert binary to int num = int(n, 2) # convert int to hexadecimal hex_num = hex(num) return(hex_num) # Driver codeif __name__ == '__main__': print(binToHexa('1111')) print(binToHexa('110101')) print(binToHexa('100001111')) print(binToHexa('111101111011')) Output: 0xf 0x35 0x10f 0xf7b We use int() and format() to convert a binary number to its equivalent hexadecimal number. Below is the Python implementation using int() and format(). Python3 # Python code to convert from Binary# to hexadecimal using format()def binToHexa(n): # convert binary to int num = int(n, 2) # convert int to hexadecimal hex_num = format(num, 'x') return(hex_num) # Driver codeif __name__ == '__main__': print(binToHexa('1111')) print(binToHexa('110101')) print(binToHexa('100001111')) print(binToHexa('111101111011')) Output: f 35 10f f7b Blogathon-2021 Picked Blogathon Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Import JSON Data into SQL Server? SQL Query to Convert Datetime to Date Python program to convert XML to Dictionary Scrape LinkedIn Using Selenium And Beautiful Soup in Python How to toggle password visibility in forms using Bootstrap-icons ? Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe
[ { "code": null, "e": 53, "s": 25, "text": "\n14 Sep, 2021" }, { "code": null, "e": 405, "s": 53, "text": "Given a binary number, the task is to write a Python program to convert the given binary number into an equivalent hexadecimal number. i.e convert the number with base value 2 to base value 16. In hexadecimal representation we 16 values to represent a number. Numbers 0-9 are expressed by digits 0-9 and 10-15 are represented by characters from A – F." }, { "code": null, "e": 414, "s": 405, "text": "Example:" }, { "code": null, "e": 493, "s": 414, "text": "Input: 1111\nOutput: F\n\nInput: 110101\nOutput: 35\n\nInput: 100001111\nOutput: 10F" }, { "code": null, "e": 523, "s": 493, "text": "Step 1: Input binary number." }, { "code": null, "e": 543, "s": 523, "text": "Input: 111101111011" }, { "code": null, "e": 620, "s": 543, "text": "Step 2: Divide your binary number into groups of four, starting from right. " }, { "code": null, "e": 654, "s": 620, "text": "111101111011 = (1111)(0111)(1011)" }, { "code": null, "e": 734, "s": 654, "text": "Step 3: Convert one 4-digit group of a binary number to one hexadecimal digit. " }, { "code": null, "e": 759, "s": 734, "text": "(1111)(0111)(1011) = F7B" }, { "code": null, "e": 817, "s": 759, "text": "Below is the Python implementation of the above approach:" }, { "code": null, "e": 825, "s": 817, "text": "Python3" }, { "code": "# Python code to convert binary number# into hexadecimal number # function to convert# binary to hexadecimal def binToHexa(n): bnum = int(n) temp = 0 mul = 1 # counter to check group of 4 count = 1 # char array to store hexadecimal number hexaDeciNum = ['0'] * 100 # counter for hexadecimal number array i = 0 while bnum != 0: rem = bnum % 10 temp = temp + (rem*mul) # check if group of 4 completed if count % 4 == 0: # check if temp < 10 if temp < 10: hexaDeciNum[i] = chr(temp+48) else: hexaDeciNum[i] = chr(temp+55) mul = 1 temp = 0 count = 1 i = i+1 # group of 4 is not completed else: mul = mul*2 count = count+1 bnum = int(bnum/10) # check if at end the group of 4 is not # completed if count != 1: hexaDeciNum[i] = chr(temp+48) # check at end the group of 4 is completed if count == 1: i = i-1 # printing hexadecimal number # array in reverse order print(\"\\n Hexadecimal equivalent of {}: \".format(n), end=\"\") while i >= 0: print(end=hexaDeciNum[i]) i = i-1 # Driver codeif __name__ == '__main__': binToHexa('1111') binToHexa('110101') binToHexa('100001111') binToHexa('111101111011')", "e": 2280, "s": 825, "text": null }, { "code": null, "e": 2288, "s": 2280, "text": "Output:" }, { "code": null, "e": 2448, "s": 2288, "text": "Hexadecimal equivalent of 1111: F\nHexadecimal equivalent of 110101: 35\nHexadecimal equivalent of 100001111: 10F\nHexadecimal equivalent of 111101111011: F7B" }, { "code": null, "e": 2478, "s": 2448, "text": "Step 1: Input binary number." }, { "code": null, "e": 2516, "s": 2478, "text": "Input: 111101111011 = (111101111011)2" }, { "code": null, "e": 2565, "s": 2516, "text": "Step 2: Convert binary number to decimal number." }, { "code": null, "e": 2592, "s": 2565, "text": "(111101111011)2 = (3963)10" }, { "code": null, "e": 2658, "s": 2592, "text": "Step 3: Convert the above decimal number to a hexadecimal number." }, { "code": null, "e": 2677, "s": 2658, "text": "(3963)10 = (F7B)16" }, { "code": null, "e": 2735, "s": 2677, "text": "Below is the Python implementation of the above approach:" }, { "code": null, "e": 2743, "s": 2735, "text": "Python3" }, { "code": "# Python program to convert binary number# into hexadecimal number # Function calculates the decimal equivalent# to given binary numberdef binaryToDecimal(binary): binary1 = int(binary) decimal, i, n = 0, 0, 0 while(binary1 != 0): dec = binary1 % 10 decimal = decimal + dec * pow(2, i) binary1 = binary1//10 i += 1 return(decimal) # function to convert# decimal to hexadecimaldef decToHexa(n): # char array to store # hexadecimal number hexaDeciNum = ['0'] * 100 # counter for hexadecimal # number array i = 0 while(n != 0): # temporary variable # to store remainder temp = 0 # storing remainder # in temp variable. temp = n % 16 # check if temp < 10 if(temp < 10): hexaDeciNum[i] = chr(temp + 48) i = i + 1 else: hexaDeciNum[i] = chr(temp + 55) i = i + 1 n = int(n / 16) # printing hexadecimal number # array in reverse order j = i - 1 while(j >= 0): print((hexaDeciNum[j]), end=\"\") j = j - 1 print() # function to convert binary to# hexadecimaldef binToHexa(n): decimal = binaryToDecimal(n) print(\"Hexadecimal equivalent of {}: \".format(n)) decToHexa(decimal) # Driver codeif __name__ == '__main__': binToHexa('1111') binToHexa('110101') binToHexa('100001111') binToHexa('111101111011')", "e": 4181, "s": 2743, "text": null }, { "code": null, "e": 4189, "s": 4181, "text": "Output:" }, { "code": null, "e": 4349, "s": 4189, "text": "Hexadecimal equivalent of 1111: \nF\nHexadecimal equivalent of 110101: \n35\nHexadecimal equivalent of 100001111: \n10F\nHexadecimal equivalent of 111101111011: \nF7B" }, { "code": null, "e": 4495, "s": 4349, "text": "We use int() and hex() to convert a binary number to its equivalent hexadecimal number. Below is the Python implementation using int() and hex()." }, { "code": null, "e": 4503, "s": 4495, "text": "Python3" }, { "code": "# Python code to convert from Binary# to Hexadecimal using int() and hex()def binToHexa(n): # convert binary to int num = int(n, 2) # convert int to hexadecimal hex_num = hex(num) return(hex_num) # Driver codeif __name__ == '__main__': print(binToHexa('1111')) print(binToHexa('110101')) print(binToHexa('100001111')) print(binToHexa('111101111011'))", "e": 4892, "s": 4503, "text": null }, { "code": null, "e": 4900, "s": 4892, "text": "Output:" }, { "code": null, "e": 4921, "s": 4900, "text": "0xf\n0x35\n0x10f\n0xf7b" }, { "code": null, "e": 5073, "s": 4921, "text": "We use int() and format() to convert a binary number to its equivalent hexadecimal number. Below is the Python implementation using int() and format()." }, { "code": null, "e": 5081, "s": 5073, "text": "Python3" }, { "code": "# Python code to convert from Binary# to hexadecimal using format()def binToHexa(n): # convert binary to int num = int(n, 2) # convert int to hexadecimal hex_num = format(num, 'x') return(hex_num) # Driver codeif __name__ == '__main__': print(binToHexa('1111')) print(binToHexa('110101')) print(binToHexa('100001111')) print(binToHexa('111101111011'))", "e": 5471, "s": 5081, "text": null }, { "code": null, "e": 5479, "s": 5471, "text": "Output:" }, { "code": null, "e": 5492, "s": 5479, "text": "f\n35\n10f\nf7b" }, { "code": null, "e": 5507, "s": 5492, "text": "Blogathon-2021" }, { "code": null, "e": 5514, "s": 5507, "text": "Picked" }, { "code": null, "e": 5524, "s": 5514, "text": "Blogathon" }, { "code": null, "e": 5531, "s": 5524, "text": "Python" }, { "code": null, "e": 5547, "s": 5531, "text": "Python Programs" }, { "code": null, "e": 5645, "s": 5547, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5686, "s": 5645, "text": "How to Import JSON Data into SQL Server?" }, { "code": null, "e": 5724, "s": 5686, "text": "SQL Query to Convert Datetime to Date" }, { "code": null, "e": 5768, "s": 5724, "text": "Python program to convert XML to Dictionary" }, { "code": null, "e": 5828, "s": 5768, "text": "Scrape LinkedIn Using Selenium And Beautiful Soup in Python" }, { "code": null, "e": 5895, "s": 5828, "text": "How to toggle password visibility in forms using Bootstrap-icons ?" }, { "code": null, "e": 5923, "s": 5895, "text": "Read JSON file using Python" }, { "code": null, "e": 5973, "s": 5923, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 5995, "s": 5973, "text": "Python map() function" } ]
Minimum number of bracket reversals needed to make an expression balanced
25 Jun, 2022 Given an expression with only ‘}’ and ‘{‘. The expression may not be balanced. Find minimum number of bracket reversals to make the expression balanced.Examples: Input: exp = "}{" Output: 2 We need to change '}' to '{' and '{' to '}' so that the expression becomes balanced, the balanced expression is '{}' Input: exp = "{{{" Output: Can't be made balanced using reversals Input: exp = "{{{{" Output: 2 Input: exp = "{{{{}}" Output: 1 Input: exp = "}{{}}{{{" Output: 3 One simple observation is, the string can be balanced only if total number of brackets is even (there must be equal no of ‘{‘ and ‘}’)A Naive Solution is to consider every bracket and recursively count number of reversals by taking two cases (i) keeping the bracket as it is (ii) reversing the bracket. If we get a balanced expression, we update result if number of steps followed for reaching here is smaller than the minimum so far. Time complexity of this solution is O(2n). An Efficient Solution can solve this problem in O(n) time. The idea is to first remove all balanced part of expression. For example, convert “}{{}}{{{” to “}{{{” by removing highlighted part. If we take a closer look, we can notice that, after removing balanced part, we always end up with an expression of the form }}...}{{...{, an expression that contains 0 or more number of closing brackets followed by 0 or more numbers of opening brackets. How many minimum reversals are required for an expression of the form “}}..}{{..{” ?. Let m be the total number of closing brackets and n be the number of opening brackets. We need ⌈m/2⌉ + ⌈n/2⌉ reversals. For example }}}}{{ requires 2+1 reversals.Below is implementation of above idea: C++14 Java Python3 C# Javascript // C++ program to find minimum number of// reversals required to balance an expression#include <bits/stdc++.h>using namespace std; // Returns count of minimum reversals for making// expr balanced. Returns -1 if expr cannot be// balanced.int countMinReversals(string expr){ int len = expr.length(); // length of expression must be even to make // it balanced by using reversals. if (len % 2) return -1; // After this loop, stack contains unbalanced // part of expression, i.e., expression of the // form "}}..}{{..{" stack<char> s; for (int i = 0; i < len; i++) { if (expr[i] == '}' && !s.empty()) { if (s.top() == '{') s.pop(); else s.push(expr[i]); } else s.push(expr[i]); } // Length of the reduced expression // red_len = (m+n) int red_len = s.size(); // count opening brackets at the end of // stack int n = 0; while (!s.empty() && s.top() == '{') { s.pop(); n++; } // return ceil(m/2) + ceil(n/2) which is // actually equal to (m+n)/2 + n%2 when // m+n is even. return (red_len / 2 + n % 2);} // Driver program to test above functionint main(){ string expr = "}}{{"; cout << countMinReversals(expr); return 0;} // Java Code to count minimum reversal for// making an expression balanced. import java.util.Stack; public class GFG { // Method count minimum reversal for // making an expression balanced. // Returns -1 if expression cannot be balanced static int countMinReversals(String expr) { int len = expr.length(); // length of expression must be even to make // it balanced by using reversals. if (len % 2 != 0) return -1; // After this loop, stack contains unbalanced // part of expression, i.e., expression of the // form "}}..}{{..{" Stack<Character> s = new Stack<>(); for (int i = 0; i < len; i++) { char c = expr.charAt(i); if (c == '}' && !s.empty()) { if (s.peek() == '{') s.pop(); else s.push(c); } else s.push(c); } // Length of the reduced expression // red_len = (m+n) int red_len = s.size(); // count opening brackets at the end of // stack int n = 0; while (!s.empty() && s.peek() == '{') { s.pop(); n++; } // return ceil(m/2) + ceil(n/2) which is // actually equal to (m+n)/2 + n%2 when // m+n is even. return (red_len / 2 + n % 2); } // Driver method public static void main(String[] args) { String expr = "}}{{"; System.out.println(countMinReversals(expr)); }}// This code is contributed by Sumit Ghosh # Python3 program to find minimum number of# reversals required to balance an expression # Returns count of minimum reversals# for making expr balanced. Returns -1# if expr cannot be balanced. def countMinReversals(expr): lenn = len(expr) # length of expression must be even # to make it balanced by using reversals. if (lenn % 2): return -1 # After this loop, stack contains # unbalanced part of expression, # i.e., expression of the form "...." s = [] for i in range(lenn): if (expr[i] == '}' and len(s)): if (s[0] == '{'): s.pop(0) else: s.insert(0, expr[i]) else: s.insert(0, expr[i]) # Length of the reduced expression # red_len = (m+n) red_len = len(s) # count opening brackets at the # end of stack n = 0 while (len(s)and s[0] == '{'): s.pop(0) n += 1 # return ceil(m/2) + ceil(n/2) which # is actually equal to (m+n)/2 + n%2 # when m+n is even. return (red_len // 2 + n % 2) # Driver Codeif __name__ == '__main__': expr = "}{" print(countMinReversals(expr.strip())) # This code is contributed by# Shubham Singh(SHUBHAMSINGH10) // C# Code to count minimum reversal for// making an expression balanced.using System;using System.Collections.Generic; class GFG { // Method count minimum reversal for // making an expression balanced. // Returns -1 if expression cannot be balanced public static int countMinReversals(string expr) { int len = expr.Length; // length of expression must be // even to make it balanced by // using reversals. if (len % 2 != 0) { return -1; } // After this loop, stack contains // unbalanced part of expression, // i.e., expression of the form "}}..}{{..{" Stack<char> s = new Stack<char>(); for (int i = 0; i < len; i++) { char c = expr[i]; if (c == '}' && s.Count > 0) { if (s.Peek() == '{') { s.Pop(); } else { s.Push(c); } } else { s.Push(c); } } // Length of the reduced expression // red_len = (m+n) int red_len = s.Count; // count opening brackets at // the end of stack int n = 0; while (s.Count > 0 && s.Peek() == '{') { s.Pop(); n++; } // return ceil(m/2) + ceil(n/2) which is // actually equal to (m+n)/2 + n%2 when // m+n is even. return (red_len / 2 + n % 2); } // Driver Code public static void Main(string[] args) { string expr = "}}{{"; Console.WriteLine(countMinReversals(expr)); }} // This code is contributed by Shrikant13 <script> // JavaScript program to find minimum number of // reversals required to balance an expression // Returns count of minimum reversals for making // expr balanced. Returns -1 if expr cannot be // balanced. function countMinReversals(expr) { let len = expr.length; // Expressions of odd lengths // cannot be balanced if (len % 2) return -1; // After this loop, stack contains unbalanced // part of expression, i.e., expression of the // form "}}..}{{..{" var s = new Array(); for (let i = 0; i < len; i++) { if (expr[i] == '}' && !s.length == 0) { if (s[s.length - 1] == '{') s.pop(); else s.push(expr[i]); } else s.push(expr[i]); } // Length of the reduced expression // red_len = (m+n) let red_len = s.length; // count opening brackets at the end of // stack let n = 0; while (!s.length == 0 && s[s.length - 1] == '{') { s.pop(); n++; } // return ceil(m/2) + ceil(n/2) which is // actually equal to (m+n)/2 + n%2 when // m+n is even. return (red_len / 2 + n % 2); } // Driver program to test above function let expr = "}}{{"; document.write(countMinReversals(expr)); </script> 2 Time Complexity: O(n) Auxiliary Space: O(n) An another Intuitive Solution can solve this problem with same complexity. The idea is to follow the algorithm used in Check if the parenthesis is balanced or not. We follow this algorithm with a new condition when we find that the parenthesis is not balanced. This case arises when the stack is empty and we encounter a ‘ } ‘. In Check if the parenthesis is balanced or not program we break the loop when we find that parenthesis is not balanced but here we will reverse it to ‘ { ‘ and push it to the stack. While doing this, answer is incremented by 1. Here, since we found a case of unbalanced expression the ‘ { ‘ must be changed in order to get a balanced expression. Also, changing this would be the most minimal way to get a balanced expression as it is a must condition to change it. For example, string = “}{{}}{}}” will be converted to “{{{}}{}}” and we get a balanced expression. There may arise a case where after doing this to the string we have some ‘{‘ left in the stack. For example, string = “{}{{{{” will be converted to “{}{{{{” and there will be 4 ‘{‘ present in the stack which are not popped and are not balanced. We can simply make it balanced by reversing the right half of the stack to ‘}’. Example: if stack has ‘ {{{{ ‘ left, we make it ‘ {{}} ‘ forming a balanced expression. Hence, answer gets updated by (stack size / 2). The case where the size of stack is odd, it is not possible to transform it to a balanced string. Below is implementation of above idea: C++ Java Python3 C# Javascript #include <iostream>using namespace std;#include <stack> int countMinReversals(string str){ // Step 1: Initialize a stack of char type and ans as 0. stack<char> st; int ans = 0; // Step 2: Run a loop for each character of the string for (int i = 0; i < str.size(); i++) { // Step 2.1: If ' { ' encountered push it to the // stack if (str[i] == '{') st.push(str[i]); // Step 2.2: If ' } ' is encountered else { // Step 2.2.1: If stack has a '{' present for // '}' encountered, pop from the stack. if (!st.empty()) st.pop(); // Step 2.2.2: If stack is empty, change '}' to // '{' and push it to stack and increment ans by // 1 else { st.push('{'); ans++; } } } // Step 3: if stack size is odd return -1. if (st.size() % 2 != 0) return -1; // Step 4: Increment ans by ( stackSize/2 ). ans += st.size() / 2; return ans;} int main(){ string expr = "{{{{}}"; cout << countMinReversals(expr); return 0;} /*package whatever //do not write package name here */ import java.io.*;import java.util.Stack; class GFG { static int countMinReversals(String str) { // Step 1: Initialize a stack of char type and ans as 0. Stack<Character> st = new Stack<Character>(); int ans = 0; // Step 2: Run a loop for each character of the string for (int i = 0; i < str.length(); i++) { // Step 2.1: If ' { ' encountered push it to the // stack if (str.charAt(i) == '{') st.add(str.charAt(i)); // Step 2.2: If ' } ' is encountered else { // Step 2.2.1: If stack has a '{' present for // '}' encountered, pop from the stack. if (!st.isEmpty()) st.pop(); // Step 2.2.2: If stack is empty, change '}' to // '{' and push it to stack and increment ans by // 1 else { st.add('{'); ans++; } } } // Step 3: if stack size is odd return -1. if (st.size() % 2 != 0) return -1; // Step 4: Increment ans by ( stackSize/2 ). ans += st.size() / 2; return ans; } // Driver code public static void main(String args[]) { String expr = "{{{{}}"; System.out.println(countMinReversals(expr)); }} // This code iscontributed by shinjanpatra. # Python code to implement the approach def countMinReversals(Str): # Step 1: Initialize a stack of char type and ans as 0. st = [] ans = 0 # Step 2: Run a loop for each character of the String for i in range(len(Str)): # Step 2.1: If ' { ' encountered push it to the # stack if (Str[i] == '{'): st.append(Str[i]) # Step 2.2: If ' } ' is encountered else: # Step 2.2.1: If stack has a '{' present for # '}' encountered, pop from the stack. if (len(st)>0): st.pop() # Step 2.2.2: If stack is empty, change '}' to # '{' and push it to stack and increment ans by # 1 else: st.push('{') ans += 1 # Step 3: if stack size is odd return -1. if (len(st) % 2 != 0): return -1 # Step 4: Increment ans by ( stackSize/2 ). ans += len(st) // 2 return ans # driver code expr = "{{{{}}"print(countMinReversals(expr)) # This code is contributed by shinjanpatra // C# Code to count minimum reversal for// making an expression balanced.using System;using System.Collections.Generic; class GFG{ public static int countMinReversals(string str) { // Step 1: Initialize a stack of char type and ans as 0. Stack<char> st = new Stack<char>(); int ans = 0; // Step 2: Run a loop for each character of the string for (int i = 0; i < str.Length; i++) { // Step 2.1: If ' { ' encountered push it to the // stack if (str[i] == '{') st.Push(str[i]); // Step 2.2: If ' } ' is encountered else { // Step 2.2.1: If stack has a '{' present for // '}' encountered, pop from the stack. if (st.Count > 0) st.Pop(); // Step 2.2.2: If stack is empty, change '}' to // '{' and push it to stack and increment ans by // 1 else { st.Push('{'); ans++; } } } // Step 3: if stack size is odd return -1. if (st.Count % 2 != 0) return -1; // Step 4: Increment ans by ( stackSize/2 ). ans += st.Count / 2; return ans; } // Driver Code public static void Main(string[] args) { string expr = "{{{{}}"; Console.WriteLine(countMinReversals(expr)); }} // This code is contributed by kothavvsaakash <script> // JavaScript code to implement the approach function countMinReversals(Str){ // Step 1: Initialize a stack of char type and ans as 0. let st = [] let ans = 0 // Step 2: Run a loop for each character of the String for(let i=0;i<Str.length;i++){ // Step 2.1: If ' { ' encountered push it to the // stack if (Str[i] == '{') st.push(Str[i]) // Step 2.2: If ' } ' is encountered else{ // Step 2.2.1: If stack has a '{' present for // '}' encountered, pop from the stack. if (st.length>0) st.pop() // Step 2.2.2: If stack is empty, change '}' to // '{' and push it to stack and increment ans by // 1 else{ st.push('{') ans += 1 } } } // Step 3: if stack size is odd return -1. if (st.length % 2 != 0) return -1 // Step 4: Increment ans by ( stackSize/2 ). ans += st.length / 2 return ans} // driver code let expr = "{{{{}}"document.write(countMinReversals(expr),"</br>") // This code is contributed by shinjanpatra </script> Output: 1 Time Complexity: O(n) Auxiliary Space: O(n) Another efficient solution solve the problem in O(1) i.e. constant space. Since the expression only contains one type of brackets, the idea is to maintain two variables to keep count of left bracket as well as right bracket as we did in Length of the longest valid substring. If the expression has balanced brackets, then we decrement left variable else we increment right variable. Then all we need to return is ceil(left/2) + ceil(right/2). C++ Java Python3 C# Javascript // C++ program to find minimum number of// reversals required to balance an expression#include <bits/stdc++.h>using namespace std; // Returns count of minimum reversals for making// expr balanced. Returns -1 if expr cannot be// balanced.int countMinReversals(string expr){ int len = expr.length(); // Expressions of odd lengths // cannot be balanced if (len % 2 != 0) { return -1; } int left_brace = 0, right_brace = 0; int ans; for (int i = 0; i < len; i++) { // If we find a left bracket then we simply // increment the left bracket if (expr[i] == '{') { left_brace++; } // Else if left bracket is 0 then we find // unbalanced right bracket and increment // right bracket or if the expression // is balanced then we decrement left else { if (left_brace == 0) { right_brace++; } else { left_brace--; } } } ans = ceil(left_brace / 2.0) + ceil(right_brace / 2.0); return ans;} // Driver program to test above functionint main(){ string expr = "}}{{"; cout << countMinReversals(expr); return 0;} // Java Code to count minimum reversal for// making an expression balanced.import java.util.*;public class GFG { // Method count minimum reversal for // making an expression balanced. // Returns -1 if expression cannot be balanced static int countMinReversals(String expr) { int len = expr.length(); int ans; // Expressions of odd lengths // cannot be balanced if (len % 2 != 0) { return -1; } int left_brace = 0, right_brace = 0; for (int i = 0; i < len; i++) { char ch = expr.charAt(i); // If we find a left bracket then we simply // increment the left bracket if (ch == '{') { left_brace++; } // Else if left bracket is 0 then we find // unbalanced right bracket and increment // right bracket or if the expression // is balanced then we decrement left else { if (left_brace == 0) { right_brace++; } else { left_brace--; } } } ans = (int)(Math.ceil((0.0 + left_brace) / 2) + Math.ceil((0.0 + right_brace) / 2)); return ans; } // Driver method public static void main(String[] args) { String expr = "}}{{"; System.out.println(countMinReversals(expr)); }} # Python 3 program to find minimum number of# reversals required to balance an expressionimport math # Returns count of minimum reversals for making# expr balanced. Returns -1 if expr cannot be# balanced. def countMinReversals(expr): length = len(expr) # Expressions of odd lengths # cannot be balanced if (length % 2 != 0): return -1 left_brace = 0 right_brace = 0 for i in range(length): # If we find a left bracket then we simply # increment the left bracket if (expr[i] == '{'): left_brace += 1 # Else if left bracket is 0 then we find # unbalanced right bracket and increment # right bracket or if the expression # is balanced then we decrement left else: if (left_brace == 0): right_brace += 1 else: left_brace -= 1 ans = math.ceil(left_brace / 2) + math.ceil(right_brace / 2) return ans # Driver program to test above functionif __name__ == "__main__": expr = "}}{{" print(countMinReversals(expr)) # This code is contributed by ukasp. // C# Code to count minimum reversal for// making an expression balanced.using System; public class GFG { // Method count minimum reversal for // making an expression balanced. // Returns -1 if expression cannot be balanced static int countMinReversals(String expr) { int len = expr.Length; int ans; // Expressions of odd lengths // cannot be balanced if (len % 2 != 0) { return -1; } int left_brace = 0, right_brace = 0; for (int i = 0; i < len; i++) { char ch = expr[i]; // If we find a left bracket then we simply // increment the left bracket if (ch == '{') { left_brace++; } // Else if left bracket is 0 then we find // unbalanced right bracket and increment // right bracket or if the expression // is balanced then we decrement left else { if (left_brace == 0) { right_brace++; } else { left_brace--; } } } ans = (int)(Math.Ceiling((0.0 + left_brace) / 2) + Math.Ceiling((0.0 + right_brace) / 2)); return ans; } // Driver method public static void Main(String[] args) { String expr = "}}{{"; Console.WriteLine(countMinReversals(expr)); }} // This code is contributed by aashish1995. <script> // JavaScript program to find minimum number of// reversals required to balance an expression // Returns count of minimum reversals for making// expr balanced. Returns -1 if expr cannot be// balanced.function countMinReversals( expr){ let len = expr.length; // Expressions of odd lengths // cannot be balanced if (len % 2 != 0) { return -1; } let left_brace = 0, right_brace = 0; let ans; for (let i = 0; i < len; i++) { // If we find a left bracket then we simply // increment the left bracket if (expr[i] == '{') { left_brace++; } // Else if left bracket is 0 then we find // unbalanced right bracket and increment // right bracket or if the expression // is balanced then we decrement left else { if (left_brace == 0) { right_brace++; } else { left_brace--; } } } ans = Math.ceil(left_brace / 2) + Math.ceil(right_brace / 2); return ans;} // Driver program to test above function let expr = "}}{{"; document.write(countMinReversals(expr)); </script> 2 Time Complexity: O(n) Auxiliary Space: O(1) Instead of maintaining two different variables for left brace and right brace, we can do it using a single temporary variable. Traverse the array. For each ‘{‘ , increment the value of temp by 1 and for each ‘}’, if value of temp >0, then decrement the value of temp by 1 else, increment the value of result as well as temp by 1. At end, add half of the value of temp to the result. Below is the implementation of above approach in C++. C++ Java Python3 C# Javascript // C++ program to find minimum number of// reversals required to balance an expression#include <bits/stdc++.h>using namespace std; // Returns count of minimum reversals for making// expr balanced. Returns -1 if expr cannot be// balanced.int countMinReversals(string s){ int temp = 0, res = 0, n = s.size(); if (n % 2 != 0) return -1; for (int i = 0; i < n; i++) { if (s[i] == '{') temp++; else { if (temp == 0) { res++; temp++; } else temp--; } } if (temp > 0) res += temp / 2; return res;} // Driver program to test above functionint main(){ string expr = "}}{{"; cout << countMinReversals(expr); return 0; // This code is contributed by Akansha Mittal} // Java program to find minimum number of// reversals required to balance an expressionimport java.util.*; class GFG { // Returns count of minimum reversals for making // expr balanced. Returns -1 if expr cannot be // balanced. static int countMinReversals(String s) { int temp = 0, res = 0, n = s.length(); if (n % 2 != 0) return -1; for (int i = 0; i < n; i++) { if (s.charAt(i) == '{') temp++; else { if (temp == 0) { res++; temp++; } else temp--; } } if (temp > 0) res += temp / 2; return res; } // Driver program to test above function public static void main(String[] args) { String expr = "}}{{"; System.out.print(countMinReversals(expr)); }} // This code is contributed by Rajput-Ji # Python program to find minimum number of# reversals required to balance an expression # Returns count of minimum reversals for making# expr balanced. Returns -1 if expr cannot be# balanced.def countMinReversals(s): temp, res, n = 0, 0, len(s) if (n % 2 != 0): return -1 for i in range(n): if (s[i] == '{'): temp += 1 else: if (temp == 0): res += 1 temp += 1 else: temp -= 1 if (temp > 0): res += temp // 2 return res # Driver program to test above functionexpr = "}}{{"print(countMinReversals(expr)) # This code is contributed by shinjanpatra // C# program to find minimum number of// reversals required to balance an expressionusing System;class GFG { // Returns count of minimum reversals for making // expr balanced. Returns -1 if expr cannot be // balanced. static int countMinReversals(string s) { int temp = 0, res = 0, n = s.Length; if (n % 2 != 0) return -1; for (int i = 0; i < n; i++) { if (s[i] == '{') temp++; else { if (temp == 0) { res++; temp++; } else temp--; } } if (temp > 0) res += temp / 2; return res; } // Driver program to test above function public static void Main() { string expr = "}}{{"; Console.Write(countMinReversals(expr)); }} // This code is contribute by ukasp. <script>// javascript program to find minimum number of// reversals required to balance an expression // Returns count of minimum reversals for making // expr balanced. Returns -1 if expr cannot be // balanced. function countMinReversals( s) { var temp = 0, res = 0, n = s.length; if (n % 2 != 0) return -1; for (i = 0; i < n; i++) { if (s.charAt(i) == '{') temp++; else { if (temp == 0) { res++; temp++; } else temp--; } } if (temp > 0) res += temp / 2; return res; } // Driver program to test above function var expr = "}}{{"; document.write(countMinReversals(expr)); // This code is contributed by Rajput-Ji</script> 2 Time Complexity: O(n) Auxiliary Space: O(1) Thanks to Utkarsh Trivedi for suggesting above approach.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. shrikanth13 SHUBHAMSINGH10 AakashYadav4 aashish1995 ukasp lokeshpotta20 amarb62 surinderdawra388 aakankshamittal22 201801082 Rajput-Ji manav888 shinjanpatra simmytarika5 sumitgumber28 avendrasingh786 kothavvsaakash Amazon Queue Stack Strings Amazon Strings Stack Queue Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n25 Jun, 2022" }, { "code": null, "e": 217, "s": 54, "text": "Given an expression with only ‘}’ and ‘{‘. The expression may not be balanced. Find minimum number of bracket reversals to make the expression balanced.Examples: " }, { "code": null, "e": 536, "s": 217, "text": "Input: exp = \"}{\"\nOutput: 2\nWe need to change '}' to '{' and '{' to\n'}' so that the expression becomes balanced, \nthe balanced expression is '{}'\n\nInput: exp = \"{{{\"\nOutput: Can't be made balanced using reversals\n\nInput: exp = \"{{{{\"\nOutput: 2 \n\nInput: exp = \"{{{{}}\"\nOutput: 1 \n\nInput: exp = \"}{{}}{{{\"\nOutput: 3" }, { "code": null, "e": 1015, "s": 536, "text": "One simple observation is, the string can be balanced only if total number of brackets is even (there must be equal no of ‘{‘ and ‘}’)A Naive Solution is to consider every bracket and recursively count number of reversals by taking two cases (i) keeping the bracket as it is (ii) reversing the bracket. If we get a balanced expression, we update result if number of steps followed for reaching here is smaller than the minimum so far. Time complexity of this solution is O(2n). " }, { "code": null, "e": 1749, "s": 1015, "text": "An Efficient Solution can solve this problem in O(n) time. The idea is to first remove all balanced part of expression. For example, convert “}{{}}{{{” to “}{{{” by removing highlighted part. If we take a closer look, we can notice that, after removing balanced part, we always end up with an expression of the form }}...}{{...{, an expression that contains 0 or more number of closing brackets followed by 0 or more numbers of opening brackets. How many minimum reversals are required for an expression of the form “}}..}{{..{” ?. Let m be the total number of closing brackets and n be the number of opening brackets. We need ⌈m/2⌉ + ⌈n/2⌉ reversals. For example }}}}{{ requires 2+1 reversals.Below is implementation of above idea: " }, { "code": null, "e": 1755, "s": 1749, "text": "C++14" }, { "code": null, "e": 1760, "s": 1755, "text": "Java" }, { "code": null, "e": 1768, "s": 1760, "text": "Python3" }, { "code": null, "e": 1771, "s": 1768, "text": "C#" }, { "code": null, "e": 1782, "s": 1771, "text": "Javascript" }, { "code": "// C++ program to find minimum number of// reversals required to balance an expression#include <bits/stdc++.h>using namespace std; // Returns count of minimum reversals for making// expr balanced. Returns -1 if expr cannot be// balanced.int countMinReversals(string expr){ int len = expr.length(); // length of expression must be even to make // it balanced by using reversals. if (len % 2) return -1; // After this loop, stack contains unbalanced // part of expression, i.e., expression of the // form \"}}..}{{..{\" stack<char> s; for (int i = 0; i < len; i++) { if (expr[i] == '}' && !s.empty()) { if (s.top() == '{') s.pop(); else s.push(expr[i]); } else s.push(expr[i]); } // Length of the reduced expression // red_len = (m+n) int red_len = s.size(); // count opening brackets at the end of // stack int n = 0; while (!s.empty() && s.top() == '{') { s.pop(); n++; } // return ceil(m/2) + ceil(n/2) which is // actually equal to (m+n)/2 + n%2 when // m+n is even. return (red_len / 2 + n % 2);} // Driver program to test above functionint main(){ string expr = \"}}{{\"; cout << countMinReversals(expr); return 0;}", "e": 3090, "s": 1782, "text": null }, { "code": "// Java Code to count minimum reversal for// making an expression balanced. import java.util.Stack; public class GFG { // Method count minimum reversal for // making an expression balanced. // Returns -1 if expression cannot be balanced static int countMinReversals(String expr) { int len = expr.length(); // length of expression must be even to make // it balanced by using reversals. if (len % 2 != 0) return -1; // After this loop, stack contains unbalanced // part of expression, i.e., expression of the // form \"}}..}{{..{\" Stack<Character> s = new Stack<>(); for (int i = 0; i < len; i++) { char c = expr.charAt(i); if (c == '}' && !s.empty()) { if (s.peek() == '{') s.pop(); else s.push(c); } else s.push(c); } // Length of the reduced expression // red_len = (m+n) int red_len = s.size(); // count opening brackets at the end of // stack int n = 0; while (!s.empty() && s.peek() == '{') { s.pop(); n++; } // return ceil(m/2) + ceil(n/2) which is // actually equal to (m+n)/2 + n%2 when // m+n is even. return (red_len / 2 + n % 2); } // Driver method public static void main(String[] args) { String expr = \"}}{{\"; System.out.println(countMinReversals(expr)); }}// This code is contributed by Sumit Ghosh", "e": 4680, "s": 3090, "text": null }, { "code": "# Python3 program to find minimum number of# reversals required to balance an expression # Returns count of minimum reversals# for making expr balanced. Returns -1# if expr cannot be balanced. def countMinReversals(expr): lenn = len(expr) # length of expression must be even # to make it balanced by using reversals. if (lenn % 2): return -1 # After this loop, stack contains # unbalanced part of expression, # i.e., expression of the form \"....\" s = [] for i in range(lenn): if (expr[i] == '}' and len(s)): if (s[0] == '{'): s.pop(0) else: s.insert(0, expr[i]) else: s.insert(0, expr[i]) # Length of the reduced expression # red_len = (m+n) red_len = len(s) # count opening brackets at the # end of stack n = 0 while (len(s)and s[0] == '{'): s.pop(0) n += 1 # return ceil(m/2) + ceil(n/2) which # is actually equal to (m+n)/2 + n%2 # when m+n is even. return (red_len // 2 + n % 2) # Driver Codeif __name__ == '__main__': expr = \"}{\" print(countMinReversals(expr.strip())) # This code is contributed by# Shubham Singh(SHUBHAMSINGH10)", "e": 5903, "s": 4680, "text": null }, { "code": "// C# Code to count minimum reversal for// making an expression balanced.using System;using System.Collections.Generic; class GFG { // Method count minimum reversal for // making an expression balanced. // Returns -1 if expression cannot be balanced public static int countMinReversals(string expr) { int len = expr.Length; // length of expression must be // even to make it balanced by // using reversals. if (len % 2 != 0) { return -1; } // After this loop, stack contains // unbalanced part of expression, // i.e., expression of the form \"}}..}{{..{\" Stack<char> s = new Stack<char>(); for (int i = 0; i < len; i++) { char c = expr[i]; if (c == '}' && s.Count > 0) { if (s.Peek() == '{') { s.Pop(); } else { s.Push(c); } } else { s.Push(c); } } // Length of the reduced expression // red_len = (m+n) int red_len = s.Count; // count opening brackets at // the end of stack int n = 0; while (s.Count > 0 && s.Peek() == '{') { s.Pop(); n++; } // return ceil(m/2) + ceil(n/2) which is // actually equal to (m+n)/2 + n%2 when // m+n is even. return (red_len / 2 + n % 2); } // Driver Code public static void Main(string[] args) { string expr = \"}}{{\"; Console.WriteLine(countMinReversals(expr)); }} // This code is contributed by Shrikant13", "e": 7575, "s": 5903, "text": null }, { "code": "<script> // JavaScript program to find minimum number of // reversals required to balance an expression // Returns count of minimum reversals for making // expr balanced. Returns -1 if expr cannot be // balanced. function countMinReversals(expr) { let len = expr.length; // Expressions of odd lengths // cannot be balanced if (len % 2) return -1; // After this loop, stack contains unbalanced // part of expression, i.e., expression of the // form \"}}..}{{..{\" var s = new Array(); for (let i = 0; i < len; i++) { if (expr[i] == '}' && !s.length == 0) { if (s[s.length - 1] == '{') s.pop(); else s.push(expr[i]); } else s.push(expr[i]); } // Length of the reduced expression // red_len = (m+n) let red_len = s.length; // count opening brackets at the end of // stack let n = 0; while (!s.length == 0 && s[s.length - 1] == '{') { s.pop(); n++; } // return ceil(m/2) + ceil(n/2) which is // actually equal to (m+n)/2 + n%2 when // m+n is even. return (red_len / 2 + n % 2); } // Driver program to test above function let expr = \"}}{{\"; document.write(countMinReversals(expr)); </script>", "e": 9186, "s": 7575, "text": null }, { "code": null, "e": 9188, "s": 9186, "text": "2" }, { "code": null, "e": 9232, "s": 9188, "text": "Time Complexity: O(n) Auxiliary Space: O(n)" }, { "code": null, "e": 9308, "s": 9232, "text": "An another Intuitive Solution can solve this problem with same complexity. " }, { "code": null, "e": 9790, "s": 9308, "text": "The idea is to follow the algorithm used in Check if the parenthesis is balanced or not. We follow this algorithm with a new condition when we find that the parenthesis is not balanced. This case arises when the stack is empty and we encounter a ‘ } ‘. In Check if the parenthesis is balanced or not program we break the loop when we find that parenthesis is not balanced but here we will reverse it to ‘ { ‘ and push it to the stack. While doing this, answer is incremented by 1." }, { "code": null, "e": 10027, "s": 9790, "text": "Here, since we found a case of unbalanced expression the ‘ { ‘ must be changed in order to get a balanced expression. Also, changing this would be the most minimal way to get a balanced expression as it is a must condition to change it." }, { "code": null, "e": 10373, "s": 10027, "text": "For example, string = “}{{}}{}}” will be converted to “{{{}}{}}” and we get a balanced expression. There may arise a case where after doing this to the string we have some ‘{‘ left in the stack. For example, string = “{}{{{{” will be converted to “{}{{{{” and there will be 4 ‘{‘ present in the stack which are not popped and are not balanced." }, { "code": null, "e": 10687, "s": 10373, "text": "We can simply make it balanced by reversing the right half of the stack to ‘}’. Example: if stack has ‘ {{{{ ‘ left, we make it ‘ {{}} ‘ forming a balanced expression. Hence, answer gets updated by (stack size / 2). The case where the size of stack is odd, it is not possible to transform it to a balanced string." }, { "code": null, "e": 10727, "s": 10687, "text": "Below is implementation of above idea: " }, { "code": null, "e": 10731, "s": 10727, "text": "C++" }, { "code": null, "e": 10736, "s": 10731, "text": "Java" }, { "code": null, "e": 10744, "s": 10736, "text": "Python3" }, { "code": null, "e": 10747, "s": 10744, "text": "C#" }, { "code": null, "e": 10758, "s": 10747, "text": "Javascript" }, { "code": "#include <iostream>using namespace std;#include <stack> int countMinReversals(string str){ // Step 1: Initialize a stack of char type and ans as 0. stack<char> st; int ans = 0; // Step 2: Run a loop for each character of the string for (int i = 0; i < str.size(); i++) { // Step 2.1: If ' { ' encountered push it to the // stack if (str[i] == '{') st.push(str[i]); // Step 2.2: If ' } ' is encountered else { // Step 2.2.1: If stack has a '{' present for // '}' encountered, pop from the stack. if (!st.empty()) st.pop(); // Step 2.2.2: If stack is empty, change '}' to // '{' and push it to stack and increment ans by // 1 else { st.push('{'); ans++; } } } // Step 3: if stack size is odd return -1. if (st.size() % 2 != 0) return -1; // Step 4: Increment ans by ( stackSize/2 ). ans += st.size() / 2; return ans;} int main(){ string expr = \"{{{{}}\"; cout << countMinReversals(expr); return 0;}", "e": 11903, "s": 10758, "text": null }, { "code": "/*package whatever //do not write package name here */ import java.io.*;import java.util.Stack; class GFG { static int countMinReversals(String str) { // Step 1: Initialize a stack of char type and ans as 0. Stack<Character> st = new Stack<Character>(); int ans = 0; // Step 2: Run a loop for each character of the string for (int i = 0; i < str.length(); i++) { // Step 2.1: If ' { ' encountered push it to the // stack if (str.charAt(i) == '{') st.add(str.charAt(i)); // Step 2.2: If ' } ' is encountered else { // Step 2.2.1: If stack has a '{' present for // '}' encountered, pop from the stack. if (!st.isEmpty()) st.pop(); // Step 2.2.2: If stack is empty, change '}' to // '{' and push it to stack and increment ans by // 1 else { st.add('{'); ans++; } } } // Step 3: if stack size is odd return -1. if (st.size() % 2 != 0) return -1; // Step 4: Increment ans by ( stackSize/2 ). ans += st.size() / 2; return ans; } // Driver code public static void main(String args[]) { String expr = \"{{{{}}\"; System.out.println(countMinReversals(expr)); }} // This code iscontributed by shinjanpatra.", "e": 13432, "s": 11903, "text": null }, { "code": "# Python code to implement the approach def countMinReversals(Str): # Step 1: Initialize a stack of char type and ans as 0. st = [] ans = 0 # Step 2: Run a loop for each character of the String for i in range(len(Str)): # Step 2.1: If ' { ' encountered push it to the # stack if (Str[i] == '{'): st.append(Str[i]) # Step 2.2: If ' } ' is encountered else: # Step 2.2.1: If stack has a '{' present for # '}' encountered, pop from the stack. if (len(st)>0): st.pop() # Step 2.2.2: If stack is empty, change '}' to # '{' and push it to stack and increment ans by # 1 else: st.push('{') ans += 1 # Step 3: if stack size is odd return -1. if (len(st) % 2 != 0): return -1 # Step 4: Increment ans by ( stackSize/2 ). ans += len(st) // 2 return ans # driver code expr = \"{{{{}}\"print(countMinReversals(expr)) # This code is contributed by shinjanpatra", "e": 14506, "s": 13432, "text": null }, { "code": "// C# Code to count minimum reversal for// making an expression balanced.using System;using System.Collections.Generic; class GFG{ public static int countMinReversals(string str) { // Step 1: Initialize a stack of char type and ans as 0. Stack<char> st = new Stack<char>(); int ans = 0; // Step 2: Run a loop for each character of the string for (int i = 0; i < str.Length; i++) { // Step 2.1: If ' { ' encountered push it to the // stack if (str[i] == '{') st.Push(str[i]); // Step 2.2: If ' } ' is encountered else { // Step 2.2.1: If stack has a '{' present for // '}' encountered, pop from the stack. if (st.Count > 0) st.Pop(); // Step 2.2.2: If stack is empty, change '}' to // '{' and push it to stack and increment ans by // 1 else { st.Push('{'); ans++; } } } // Step 3: if stack size is odd return -1. if (st.Count % 2 != 0) return -1; // Step 4: Increment ans by ( stackSize/2 ). ans += st.Count / 2; return ans; } // Driver Code public static void Main(string[] args) { string expr = \"{{{{}}\"; Console.WriteLine(countMinReversals(expr)); }} // This code is contributed by kothavvsaakash", "e": 15810, "s": 14506, "text": null }, { "code": "<script> // JavaScript code to implement the approach function countMinReversals(Str){ // Step 1: Initialize a stack of char type and ans as 0. let st = [] let ans = 0 // Step 2: Run a loop for each character of the String for(let i=0;i<Str.length;i++){ // Step 2.1: If ' { ' encountered push it to the // stack if (Str[i] == '{') st.push(Str[i]) // Step 2.2: If ' } ' is encountered else{ // Step 2.2.1: If stack has a '{' present for // '}' encountered, pop from the stack. if (st.length>0) st.pop() // Step 2.2.2: If stack is empty, change '}' to // '{' and push it to stack and increment ans by // 1 else{ st.push('{') ans += 1 } } } // Step 3: if stack size is odd return -1. if (st.length % 2 != 0) return -1 // Step 4: Increment ans by ( stackSize/2 ). ans += st.length / 2 return ans} // driver code let expr = \"{{{{}}\"document.write(countMinReversals(expr),\"</br>\") // This code is contributed by shinjanpatra </script>", "e": 16981, "s": 15810, "text": null }, { "code": null, "e": 16989, "s": 16981, "text": "Output:" }, { "code": null, "e": 16991, "s": 16989, "text": "1" }, { "code": null, "e": 17036, "s": 16991, "text": " Time Complexity: O(n) Auxiliary Space: O(n)" }, { "code": null, "e": 17479, "s": 17036, "text": "Another efficient solution solve the problem in O(1) i.e. constant space. Since the expression only contains one type of brackets, the idea is to maintain two variables to keep count of left bracket as well as right bracket as we did in Length of the longest valid substring. If the expression has balanced brackets, then we decrement left variable else we increment right variable. Then all we need to return is ceil(left/2) + ceil(right/2)." }, { "code": null, "e": 17483, "s": 17479, "text": "C++" }, { "code": null, "e": 17488, "s": 17483, "text": "Java" }, { "code": null, "e": 17496, "s": 17488, "text": "Python3" }, { "code": null, "e": 17499, "s": 17496, "text": "C#" }, { "code": null, "e": 17510, "s": 17499, "text": "Javascript" }, { "code": "// C++ program to find minimum number of// reversals required to balance an expression#include <bits/stdc++.h>using namespace std; // Returns count of minimum reversals for making// expr balanced. Returns -1 if expr cannot be// balanced.int countMinReversals(string expr){ int len = expr.length(); // Expressions of odd lengths // cannot be balanced if (len % 2 != 0) { return -1; } int left_brace = 0, right_brace = 0; int ans; for (int i = 0; i < len; i++) { // If we find a left bracket then we simply // increment the left bracket if (expr[i] == '{') { left_brace++; } // Else if left bracket is 0 then we find // unbalanced right bracket and increment // right bracket or if the expression // is balanced then we decrement left else { if (left_brace == 0) { right_brace++; } else { left_brace--; } } } ans = ceil(left_brace / 2.0) + ceil(right_brace / 2.0); return ans;} // Driver program to test above functionint main(){ string expr = \"}}{{\"; cout << countMinReversals(expr); return 0;}", "e": 18716, "s": 17510, "text": null }, { "code": "// Java Code to count minimum reversal for// making an expression balanced.import java.util.*;public class GFG { // Method count minimum reversal for // making an expression balanced. // Returns -1 if expression cannot be balanced static int countMinReversals(String expr) { int len = expr.length(); int ans; // Expressions of odd lengths // cannot be balanced if (len % 2 != 0) { return -1; } int left_brace = 0, right_brace = 0; for (int i = 0; i < len; i++) { char ch = expr.charAt(i); // If we find a left bracket then we simply // increment the left bracket if (ch == '{') { left_brace++; } // Else if left bracket is 0 then we find // unbalanced right bracket and increment // right bracket or if the expression // is balanced then we decrement left else { if (left_brace == 0) { right_brace++; } else { left_brace--; } } } ans = (int)(Math.ceil((0.0 + left_brace) / 2) + Math.ceil((0.0 + right_brace) / 2)); return ans; } // Driver method public static void main(String[] args) { String expr = \"}}{{\"; System.out.println(countMinReversals(expr)); }}", "e": 20170, "s": 18716, "text": null }, { "code": "# Python 3 program to find minimum number of# reversals required to balance an expressionimport math # Returns count of minimum reversals for making# expr balanced. Returns -1 if expr cannot be# balanced. def countMinReversals(expr): length = len(expr) # Expressions of odd lengths # cannot be balanced if (length % 2 != 0): return -1 left_brace = 0 right_brace = 0 for i in range(length): # If we find a left bracket then we simply # increment the left bracket if (expr[i] == '{'): left_brace += 1 # Else if left bracket is 0 then we find # unbalanced right bracket and increment # right bracket or if the expression # is balanced then we decrement left else: if (left_brace == 0): right_brace += 1 else: left_brace -= 1 ans = math.ceil(left_brace / 2) + math.ceil(right_brace / 2) return ans # Driver program to test above functionif __name__ == \"__main__\": expr = \"}}{{\" print(countMinReversals(expr)) # This code is contributed by ukasp.", "e": 21299, "s": 20170, "text": null }, { "code": "// C# Code to count minimum reversal for// making an expression balanced.using System; public class GFG { // Method count minimum reversal for // making an expression balanced. // Returns -1 if expression cannot be balanced static int countMinReversals(String expr) { int len = expr.Length; int ans; // Expressions of odd lengths // cannot be balanced if (len % 2 != 0) { return -1; } int left_brace = 0, right_brace = 0; for (int i = 0; i < len; i++) { char ch = expr[i]; // If we find a left bracket then we simply // increment the left bracket if (ch == '{') { left_brace++; } // Else if left bracket is 0 then we find // unbalanced right bracket and increment // right bracket or if the expression // is balanced then we decrement left else { if (left_brace == 0) { right_brace++; } else { left_brace--; } } } ans = (int)(Math.Ceiling((0.0 + left_brace) / 2) + Math.Ceiling((0.0 + right_brace) / 2)); return ans; } // Driver method public static void Main(String[] args) { String expr = \"}}{{\"; Console.WriteLine(countMinReversals(expr)); }} // This code is contributed by aashish1995.", "e": 22822, "s": 21299, "text": null }, { "code": "<script> // JavaScript program to find minimum number of// reversals required to balance an expression // Returns count of minimum reversals for making// expr balanced. Returns -1 if expr cannot be// balanced.function countMinReversals( expr){ let len = expr.length; // Expressions of odd lengths // cannot be balanced if (len % 2 != 0) { return -1; } let left_brace = 0, right_brace = 0; let ans; for (let i = 0; i < len; i++) { // If we find a left bracket then we simply // increment the left bracket if (expr[i] == '{') { left_brace++; } // Else if left bracket is 0 then we find // unbalanced right bracket and increment // right bracket or if the expression // is balanced then we decrement left else { if (left_brace == 0) { right_brace++; } else { left_brace--; } } } ans = Math.ceil(left_brace / 2) + Math.ceil(right_brace / 2); return ans;} // Driver program to test above function let expr = \"}}{{\"; document.write(countMinReversals(expr)); </script>", "e": 24014, "s": 22822, "text": null }, { "code": null, "e": 24016, "s": 24014, "text": "2" }, { "code": null, "e": 24039, "s": 24016, "text": "Time Complexity: O(n) " }, { "code": null, "e": 24061, "s": 24039, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 24188, "s": 24061, "text": "Instead of maintaining two different variables for left brace and right brace, we can do it using a single temporary variable." }, { "code": null, "e": 24444, "s": 24188, "text": "Traverse the array. For each ‘{‘ , increment the value of temp by 1 and for each ‘}’, if value of temp >0, then decrement the value of temp by 1 else, increment the value of result as well as temp by 1. At end, add half of the value of temp to the result." }, { "code": null, "e": 24498, "s": 24444, "text": "Below is the implementation of above approach in C++." }, { "code": null, "e": 24502, "s": 24498, "text": "C++" }, { "code": null, "e": 24507, "s": 24502, "text": "Java" }, { "code": null, "e": 24515, "s": 24507, "text": "Python3" }, { "code": null, "e": 24518, "s": 24515, "text": "C#" }, { "code": null, "e": 24529, "s": 24518, "text": "Javascript" }, { "code": "// C++ program to find minimum number of// reversals required to balance an expression#include <bits/stdc++.h>using namespace std; // Returns count of minimum reversals for making// expr balanced. Returns -1 if expr cannot be// balanced.int countMinReversals(string s){ int temp = 0, res = 0, n = s.size(); if (n % 2 != 0) return -1; for (int i = 0; i < n; i++) { if (s[i] == '{') temp++; else { if (temp == 0) { res++; temp++; } else temp--; } } if (temp > 0) res += temp / 2; return res;} // Driver program to test above functionint main(){ string expr = \"}}{{\"; cout << countMinReversals(expr); return 0; // This code is contributed by Akansha Mittal}", "e": 25340, "s": 24529, "text": null }, { "code": "// Java program to find minimum number of// reversals required to balance an expressionimport java.util.*; class GFG { // Returns count of minimum reversals for making // expr balanced. Returns -1 if expr cannot be // balanced. static int countMinReversals(String s) { int temp = 0, res = 0, n = s.length(); if (n % 2 != 0) return -1; for (int i = 0; i < n; i++) { if (s.charAt(i) == '{') temp++; else { if (temp == 0) { res++; temp++; } else temp--; } } if (temp > 0) res += temp / 2; return res; } // Driver program to test above function public static void main(String[] args) { String expr = \"}}{{\"; System.out.print(countMinReversals(expr)); }} // This code is contributed by Rajput-Ji", "e": 26295, "s": 25340, "text": null }, { "code": "# Python program to find minimum number of# reversals required to balance an expression # Returns count of minimum reversals for making# expr balanced. Returns -1 if expr cannot be# balanced.def countMinReversals(s): temp, res, n = 0, 0, len(s) if (n % 2 != 0): return -1 for i in range(n): if (s[i] == '{'): temp += 1 else: if (temp == 0): res += 1 temp += 1 else: temp -= 1 if (temp > 0): res += temp // 2 return res # Driver program to test above functionexpr = \"}}{{\"print(countMinReversals(expr)) # This code is contributed by shinjanpatra", "e": 26968, "s": 26295, "text": null }, { "code": "// C# program to find minimum number of// reversals required to balance an expressionusing System;class GFG { // Returns count of minimum reversals for making // expr balanced. Returns -1 if expr cannot be // balanced. static int countMinReversals(string s) { int temp = 0, res = 0, n = s.Length; if (n % 2 != 0) return -1; for (int i = 0; i < n; i++) { if (s[i] == '{') temp++; else { if (temp == 0) { res++; temp++; } else temp--; } } if (temp > 0) res += temp / 2; return res; } // Driver program to test above function public static void Main() { string expr = \"}}{{\"; Console.Write(countMinReversals(expr)); }} // This code is contribute by ukasp.", "e": 27884, "s": 26968, "text": null }, { "code": "<script>// javascript program to find minimum number of// reversals required to balance an expression // Returns count of minimum reversals for making // expr balanced. Returns -1 if expr cannot be // balanced. function countMinReversals( s) { var temp = 0, res = 0, n = s.length; if (n % 2 != 0) return -1; for (i = 0; i < n; i++) { if (s.charAt(i) == '{') temp++; else { if (temp == 0) { res++; temp++; } else temp--; } } if (temp > 0) res += temp / 2; return res; } // Driver program to test above function var expr = \"}}{{\"; document.write(countMinReversals(expr)); // This code is contributed by Rajput-Ji</script>", "e": 28743, "s": 27884, "text": null }, { "code": null, "e": 28745, "s": 28743, "text": "2" }, { "code": null, "e": 28767, "s": 28745, "text": "Time Complexity: O(n)" }, { "code": null, "e": 28789, "s": 28767, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 28970, "s": 28789, "text": "Thanks to Utkarsh Trivedi for suggesting above approach.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 28982, "s": 28970, "text": "shrikanth13" }, { "code": null, "e": 28997, "s": 28982, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 29010, "s": 28997, "text": "AakashYadav4" }, { "code": null, "e": 29022, "s": 29010, "text": "aashish1995" }, { "code": null, "e": 29028, "s": 29022, "text": "ukasp" }, { "code": null, "e": 29042, "s": 29028, "text": "lokeshpotta20" }, { "code": null, "e": 29050, "s": 29042, "text": "amarb62" }, { "code": null, "e": 29067, "s": 29050, "text": "surinderdawra388" }, { "code": null, "e": 29085, "s": 29067, "text": "aakankshamittal22" }, { "code": null, "e": 29095, "s": 29085, "text": "201801082" }, { "code": null, "e": 29105, "s": 29095, "text": "Rajput-Ji" }, { "code": null, "e": 29114, "s": 29105, "text": "manav888" }, { "code": null, "e": 29127, "s": 29114, "text": "shinjanpatra" }, { "code": null, "e": 29140, "s": 29127, "text": "simmytarika5" }, { "code": null, "e": 29154, "s": 29140, "text": "sumitgumber28" }, { "code": null, "e": 29170, "s": 29154, "text": "avendrasingh786" }, { "code": null, "e": 29185, "s": 29170, "text": "kothavvsaakash" }, { "code": null, "e": 29192, "s": 29185, "text": "Amazon" }, { "code": null, "e": 29198, "s": 29192, "text": "Queue" }, { "code": null, "e": 29204, "s": 29198, "text": "Stack" }, { "code": null, "e": 29212, "s": 29204, "text": "Strings" }, { "code": null, "e": 29219, "s": 29212, "text": "Amazon" }, { "code": null, "e": 29227, "s": 29219, "text": "Strings" }, { "code": null, "e": 29233, "s": 29227, "text": "Stack" }, { "code": null, "e": 29239, "s": 29233, "text": "Queue" } ]
Convert Matrix to Dataframe in R - GeeksforGeeks
09 May, 2021 In this article, we will discuss how to convert the matrix into DataFrame, or we can also say that we will discuss how to create a DataFrame from a matrix in R Programming Language. A matrix can be converted to a dataframe by using a function called as.data.frame(). It will take each column from the matrix and convert it to each column in the dataframe. Syntax: as.data.frame(matrix_data) Where, matrix_data is the input matrix. Example 1: R # create the matrix with 4 rows # with numeric elementsmatrix_data=matrix(c(1,2,3,4,5,6,7,8),nrow=4) # display the dataprint(matrix_data) # convert the matrix into dataframedataframe_data=as.data.frame(matrix_data) # print dataframe dataprint(dataframe_data) Output: Example 2: R # create the matrix with 8 rows # with numeric elementsmatrix_data=matrix(c(1,2,3,4,5,6,7,8,11:18),nrow=8) # display the dataprint(matrix_data) # convert the matrix into dataframedataframe_data=as.data.frame(matrix_data) # print dataframe dataprint(dataframe_data) Output: Example 3: R # create the matrix with 8 rows # with different elementsmatrix_data=matrix(c( "bobby","pinkey","rohith","gnanesh",5.3,6.6,7,8,11:18),nrow=8) # display the dataprint(matrix_data) # convert the matrix into dataframedataframe_data=as.data.frame(matrix_data) # print dataframe dataprint(dataframe_data) Output: Picked R DataFrame-Programs R-DataFrame R Language R Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Replace specific values in column in R DataFrame ? Loops in R (for, while, repeat) Filter data by multiple conditions in R using Dplyr Change Color of Bars in Barchart using ggplot2 in R How to change Row Names of DataFrame in R ? How to Replace specific values in column in R DataFrame ? How to change Row Names of DataFrame in R ? Remove rows with NA in one column of R DataFrame How to Split Column Into Multiple Columns in R DataFrame? Replace Specific Characters in String in R
[ { "code": null, "e": 24618, "s": 24590, "text": "\n09 May, 2021" }, { "code": null, "e": 24800, "s": 24618, "text": "In this article, we will discuss how to convert the matrix into DataFrame, or we can also say that we will discuss how to create a DataFrame from a matrix in R Programming Language." }, { "code": null, "e": 24974, "s": 24800, "text": "A matrix can be converted to a dataframe by using a function called as.data.frame(). It will take each column from the matrix and convert it to each column in the dataframe." }, { "code": null, "e": 24982, "s": 24974, "text": "Syntax:" }, { "code": null, "e": 25009, "s": 24982, "text": "as.data.frame(matrix_data)" }, { "code": null, "e": 25049, "s": 25009, "text": "Where, matrix_data is the input matrix." }, { "code": null, "e": 25060, "s": 25049, "text": "Example 1:" }, { "code": null, "e": 25062, "s": 25060, "text": "R" }, { "code": "# create the matrix with 4 rows # with numeric elementsmatrix_data=matrix(c(1,2,3,4,5,6,7,8),nrow=4) # display the dataprint(matrix_data) # convert the matrix into dataframedataframe_data=as.data.frame(matrix_data) # print dataframe dataprint(dataframe_data)", "e": 25324, "s": 25062, "text": null }, { "code": null, "e": 25332, "s": 25324, "text": "Output:" }, { "code": null, "e": 25343, "s": 25332, "text": "Example 2:" }, { "code": null, "e": 25345, "s": 25343, "text": "R" }, { "code": "# create the matrix with 8 rows # with numeric elementsmatrix_data=matrix(c(1,2,3,4,5,6,7,8,11:18),nrow=8) # display the dataprint(matrix_data) # convert the matrix into dataframedataframe_data=as.data.frame(matrix_data) # print dataframe dataprint(dataframe_data)", "e": 25613, "s": 25345, "text": null }, { "code": null, "e": 25621, "s": 25613, "text": "Output:" }, { "code": null, "e": 25632, "s": 25621, "text": "Example 3:" }, { "code": null, "e": 25634, "s": 25632, "text": "R" }, { "code": "# create the matrix with 8 rows # with different elementsmatrix_data=matrix(c( \"bobby\",\"pinkey\",\"rohith\",\"gnanesh\",5.3,6.6,7,8,11:18),nrow=8) # display the dataprint(matrix_data) # convert the matrix into dataframedataframe_data=as.data.frame(matrix_data) # print dataframe dataprint(dataframe_data)", "e": 25938, "s": 25634, "text": null }, { "code": null, "e": 25946, "s": 25938, "text": "Output:" }, { "code": null, "e": 25953, "s": 25946, "text": "Picked" }, { "code": null, "e": 25974, "s": 25953, "text": "R DataFrame-Programs" }, { "code": null, "e": 25986, "s": 25974, "text": "R-DataFrame" }, { "code": null, "e": 25997, "s": 25986, "text": "R Language" }, { "code": null, "e": 26008, "s": 25997, "text": "R Programs" }, { "code": null, "e": 26106, "s": 26008, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26115, "s": 26106, "text": "Comments" }, { "code": null, "e": 26128, "s": 26115, "text": "Old Comments" }, { "code": null, "e": 26186, "s": 26128, "text": "How to Replace specific values in column in R DataFrame ?" }, { "code": null, "e": 26218, "s": 26186, "text": "Loops in R (for, while, repeat)" }, { "code": null, "e": 26270, "s": 26218, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 26322, "s": 26270, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 26366, "s": 26322, "text": "How to change Row Names of DataFrame in R ?" }, { "code": null, "e": 26424, "s": 26366, "text": "How to Replace specific values in column in R DataFrame ?" }, { "code": null, "e": 26468, "s": 26424, "text": "How to change Row Names of DataFrame in R ?" }, { "code": null, "e": 26517, "s": 26468, "text": "Remove rows with NA in one column of R DataFrame" }, { "code": null, "e": 26575, "s": 26517, "text": "How to Split Column Into Multiple Columns in R DataFrame?" } ]
Display the minimum of three integer values in Java
The following is an example displaying the minimum of three integer values. Live Demo public class Demo { public static void main(String[] args) { int val1 = 99; int val2 = 87; int val3 = 130; System.out.println("Number 1 = "+val1); System.out.println("Number 2 = "+val2); System.out.println("Number 3 = "+val3); if (val2 < val1) { val1 = val2; } if (val3 < val1) { val1 = val3; } System.out.println("The smallest of three numbers: "+val1); } } Number 1 = 99 Number 2 = 87 Number 3 = 130 The smallest of three numbers: 87 In the above program, we have taken three integer variables, which will be compared. int val1 = 99; int val2 = 87; int val3 = 130; Now condition is used to check which of the integer value is the smallest. if (val2 < val1) { val1 = val2; } if (val3 < val1) { val1 = val3; } The above returns the smallest value.
[ { "code": null, "e": 1138, "s": 1062, "text": "The following is an example displaying the minimum of three integer values." }, { "code": null, "e": 1149, "s": 1138, "text": " Live Demo" }, { "code": null, "e": 1598, "s": 1149, "text": "public class Demo {\n public static void main(String[] args) {\n int val1 = 99;\n int val2 = 87;\n int val3 = 130;\n System.out.println(\"Number 1 = \"+val1);\n System.out.println(\"Number 2 = \"+val2);\n System.out.println(\"Number 3 = \"+val3);\n if (val2 < val1) {\n val1 = val2;\n }\n if (val3 < val1) {\n val1 = val3;\n }\n System.out.println(\"The smallest of three numbers: \"+val1);\n }\n}" }, { "code": null, "e": 1675, "s": 1598, "text": "Number 1 = 99\nNumber 2 = 87\nNumber 3 = 130\nThe smallest of three numbers: 87" }, { "code": null, "e": 1760, "s": 1675, "text": "In the above program, we have taken three integer variables, which will be compared." }, { "code": null, "e": 1806, "s": 1760, "text": "int val1 = 99;\nint val2 = 87;\nint val3 = 130;" }, { "code": null, "e": 1881, "s": 1806, "text": "Now condition is used to check which of the integer value is the smallest." }, { "code": null, "e": 1955, "s": 1881, "text": "if (val2 < val1) {\n val1 = val2;\n}\nif (val3 < val1) {\n val1 = val3;\n}" }, { "code": null, "e": 1993, "s": 1955, "text": "The above returns the smallest value." } ]
Create Simple Optical Character Recognition (OCR) with Python | by Fahmi Nurfikri | Towards Data Science
When collecting data for the text mining process or looking for other references, we often find sources in the form of images. For example, if we are going to analyze a word in pdf format, the file instead contains an image of text. This certainly makes it difficult for data processing. One solution to this problem is that we can use Optical Character Recognition (OCR). OCR is a technology for recognizing text in images, such as scanned documents and photos. One of the OCR tools that are often used is Tesseract. Tesseract is an optical character recognition engine for various operating systems. It was originally developed by Hewlett-Packard as proprietary software. Later Google took over development. Currently Tesseract is running well on the Windows, macOS, and Linux platforms. Tesseract supports Unicode (UTF-8) and supports more than 100 languages. In this article we will start with the Tesseract OCR installation process, and test the extraction of text in images. The first step is to install the Tesseract. In order to use the Tesseract library, we first need to install it on our system. If you’re using Ubuntu, you can simply use apt-get to install Tesseract OCR: sudo apt-get install tesseract-ocr For macOS users, we’ll be using Homebrew to install Tesseract. brew install tesseract For Windows, please see Tesseract documentation. Let’s begin by getting pytesseract installed. $ pip install pytesseract After installation completed, let’s move forward by applying tesseract with python. First we import the dependencies. from PIL import Imageimport pytesseractimport numpy as np I will use a simple image to test the usage of the tesseract. I will use the image below. Let’s load this image and convert it to text. filename = 'image_01.png'img1 = np.array(Image.open(filename))text = pytesseract.image_to_string(img1) Now, let’s see the result. print(text) And this is the result. The results obtained from the tesseract are good enough for simple images. Because in the real world it is difficult to find images that are really simple, so I will add noise to see the performance of the tesseract. I will use the image below. Then we will do the same process as before. filename = 'image_02.png'img2 = np.array(Image.open(filename))text = pytesseract.image_to_string(img2)print(text) This is the result. The result is ... Nothing. This means that Tesseract cannot read words in images that have noise. Then we try to use a little image processing to eliminate noise in the image. Here I will use the Open CV library. In this experiment, I’m using normalization, thresholding and image blur. import numpy as npimport cv2norm_img = np.zeros((img.shape[0], img.shape[1]))img = cv2.normalize(img, norm_img, 0, 255, cv2.NORM_MINMAX)img = cv2.threshold(img, 100, 255, cv2.THRESH_BINARY)[1]img = cv2.GaussianBlur(img, (1, 1), 0) Then the result will be like this. The image is clean enough, then we will try again with the same process as before. And this is the result. Can be seen from the picture above that the results are in accordance with what we expect. medium.com The conclusion that can be obtained is that the tesseract is most suitable when building a document processing pipeline where images are scanned and processed. This works best for situations with high-resolution input where foreground text is neatly segmented from the background.
[ { "code": null, "e": 545, "s": 172, "text": "When collecting data for the text mining process or looking for other references, we often find sources in the form of images. For example, if we are going to analyze a word in pdf format, the file instead contains an image of text. This certainly makes it difficult for data processing. One solution to this problem is that we can use Optical Character Recognition (OCR)." }, { "code": null, "e": 882, "s": 545, "text": "OCR is a technology for recognizing text in images, such as scanned documents and photos. One of the OCR tools that are often used is Tesseract. Tesseract is an optical character recognition engine for various operating systems. It was originally developed by Hewlett-Packard as proprietary software. Later Google took over development." }, { "code": null, "e": 1153, "s": 882, "text": "Currently Tesseract is running well on the Windows, macOS, and Linux platforms. Tesseract supports Unicode (UTF-8) and supports more than 100 languages. In this article we will start with the Tesseract OCR installation process, and test the extraction of text in images." }, { "code": null, "e": 1356, "s": 1153, "text": "The first step is to install the Tesseract. In order to use the Tesseract library, we first need to install it on our system. If you’re using Ubuntu, you can simply use apt-get to install Tesseract OCR:" }, { "code": null, "e": 1391, "s": 1356, "text": "sudo apt-get install tesseract-ocr" }, { "code": null, "e": 1454, "s": 1391, "text": "For macOS users, we’ll be using Homebrew to install Tesseract." }, { "code": null, "e": 1477, "s": 1454, "text": "brew install tesseract" }, { "code": null, "e": 1572, "s": 1477, "text": "For Windows, please see Tesseract documentation. Let’s begin by getting pytesseract installed." }, { "code": null, "e": 1598, "s": 1572, "text": "$ pip install pytesseract" }, { "code": null, "e": 1716, "s": 1598, "text": "After installation completed, let’s move forward by applying tesseract with python. First we import the dependencies." }, { "code": null, "e": 1774, "s": 1716, "text": "from PIL import Imageimport pytesseractimport numpy as np" }, { "code": null, "e": 1864, "s": 1774, "text": "I will use a simple image to test the usage of the tesseract. I will use the image below." }, { "code": null, "e": 1910, "s": 1864, "text": "Let’s load this image and convert it to text." }, { "code": null, "e": 2013, "s": 1910, "text": "filename = 'image_01.png'img1 = np.array(Image.open(filename))text = pytesseract.image_to_string(img1)" }, { "code": null, "e": 2040, "s": 2013, "text": "Now, let’s see the result." }, { "code": null, "e": 2052, "s": 2040, "text": "print(text)" }, { "code": null, "e": 2076, "s": 2052, "text": "And this is the result." }, { "code": null, "e": 2321, "s": 2076, "text": "The results obtained from the tesseract are good enough for simple images. Because in the real world it is difficult to find images that are really simple, so I will add noise to see the performance of the tesseract. I will use the image below." }, { "code": null, "e": 2365, "s": 2321, "text": "Then we will do the same process as before." }, { "code": null, "e": 2479, "s": 2365, "text": "filename = 'image_02.png'img2 = np.array(Image.open(filename))text = pytesseract.image_to_string(img2)print(text)" }, { "code": null, "e": 2499, "s": 2479, "text": "This is the result." }, { "code": null, "e": 2597, "s": 2499, "text": "The result is ... Nothing. This means that Tesseract cannot read words in images that have noise." }, { "code": null, "e": 2786, "s": 2597, "text": "Then we try to use a little image processing to eliminate noise in the image. Here I will use the Open CV library. In this experiment, I’m using normalization, thresholding and image blur." }, { "code": null, "e": 3017, "s": 2786, "text": "import numpy as npimport cv2norm_img = np.zeros((img.shape[0], img.shape[1]))img = cv2.normalize(img, norm_img, 0, 255, cv2.NORM_MINMAX)img = cv2.threshold(img, 100, 255, cv2.THRESH_BINARY)[1]img = cv2.GaussianBlur(img, (1, 1), 0)" }, { "code": null, "e": 3052, "s": 3017, "text": "Then the result will be like this." }, { "code": null, "e": 3159, "s": 3052, "text": "The image is clean enough, then we will try again with the same process as before. And this is the result." }, { "code": null, "e": 3250, "s": 3159, "text": "Can be seen from the picture above that the results are in accordance with what we expect." }, { "code": null, "e": 3261, "s": 3250, "text": "medium.com" } ]
How To Change Default Shell In Linux - GeeksforGeeks
23 Dec, 2021 In most Linux systems, the default shell is bash but we can change that to any other shell-like zsh, fish, sh, and any other. In this article, we are going to show how to change that default shell to any other shell in Linux systems. To change the user’s shell, first, let’s find the current shell. There are many ways by which we can change the shell of any user on a Linux system. We are going to see three methods of changing the user’s shell. In Linux systems, there is one file which is /etc/passwd. The /etc/passwd file stores essential information of user accounts, which is required during login. By using this file we can identify the current user login shell. We are going to see the current user information in the /etc/file using the following command: grep `whoami` /etc/passwd In the above image we can see that the user nishant (current user) has home directory /home/nishant and the shell is /bin/sh Now to change the shell, first, we need to see which shells are installed on the system. We can check installed shells using the following command : cat /etc/shells This will show all shells as follows: Before moving further, first understand who can change the user shell Users can change shell to any other shell listed in /etc/shells/. The root account can be used to change any other user login shell. If an account has a restricted login shell, then only the root can change that user’s shell. usermod is a command that modifies the system account files. usemod can change the shell of Users by modifying file /etc/passwd. usermod command provides the -s or –shell option to change the user’s login shell. In this example, we are going to change the shell of a user named nishant. We are going to change the shell from /bin/sh to /bin/bash of user nishant using usermod command. sudo usermod --shell /bin/bash nishant With usermod command mention shell and username after –shell option. Now you can see the shell use changed. In the above commands, replace nishant with the user name whose shell has to change. chsh is the utility to change a user’s login shell. chsh provides the -s option to change the user’s shell. This method also modifies the file /etc/passwd. Use the following command to change shells using chsh: chsh -s /bin/bash nishant As we see in the above two methods, the usermod command and chsh utility modify the /etc/passwd file and change the user shell. We can do that manually also by editing the /etc/passwd file. Just change the shell after the username and home directory in the /etc/passwd file and save the file. nano /etc/passwd varshagumber28 How To Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install FFmpeg on Windows? How to Add External JAR File to an IntelliJ IDEA Project? How to Set Git Username and Password in GitBash? How to create a nested RecyclerView in Android How to Install Jupyter Notebook on MacOS? Sed Command in Linux/Unix with examples AWK command in Unix/Linux with examples grep command in Unix/Linux cut command in Linux with examples cp command in Linux with examples
[ { "code": null, "e": 26197, "s": 26169, "text": "\n23 Dec, 2021" }, { "code": null, "e": 26644, "s": 26197, "text": "In most Linux systems, the default shell is bash but we can change that to any other shell-like zsh, fish, sh, and any other. In this article, we are going to show how to change that default shell to any other shell in Linux systems. To change the user’s shell, first, let’s find the current shell. There are many ways by which we can change the shell of any user on a Linux system. We are going to see three methods of changing the user’s shell." }, { "code": null, "e": 26867, "s": 26644, "text": "In Linux systems, there is one file which is /etc/passwd. The /etc/passwd file stores essential information of user accounts, which is required during login. By using this file we can identify the current user login shell." }, { "code": null, "e": 26962, "s": 26867, "text": "We are going to see the current user information in the /etc/file using the following command:" }, { "code": null, "e": 26988, "s": 26962, "text": "grep `whoami` /etc/passwd" }, { "code": null, "e": 27113, "s": 26988, "text": "In the above image we can see that the user nishant (current user) has home directory /home/nishant and the shell is /bin/sh" }, { "code": null, "e": 27262, "s": 27113, "text": "Now to change the shell, first, we need to see which shells are installed on the system. We can check installed shells using the following command :" }, { "code": null, "e": 27278, "s": 27262, "text": "cat /etc/shells" }, { "code": null, "e": 27316, "s": 27278, "text": "This will show all shells as follows:" }, { "code": null, "e": 27386, "s": 27316, "text": "Before moving further, first understand who can change the user shell" }, { "code": null, "e": 27452, "s": 27386, "text": "Users can change shell to any other shell listed in /etc/shells/." }, { "code": null, "e": 27519, "s": 27452, "text": "The root account can be used to change any other user login shell." }, { "code": null, "e": 27612, "s": 27519, "text": "If an account has a restricted login shell, then only the root can change that user’s shell." }, { "code": null, "e": 27824, "s": 27612, "text": "usermod is a command that modifies the system account files. usemod can change the shell of Users by modifying file /etc/passwd. usermod command provides the -s or –shell option to change the user’s login shell." }, { "code": null, "e": 27997, "s": 27824, "text": "In this example, we are going to change the shell of a user named nishant. We are going to change the shell from /bin/sh to /bin/bash of user nishant using usermod command." }, { "code": null, "e": 28036, "s": 27997, "text": "sudo usermod --shell /bin/bash nishant" }, { "code": null, "e": 28105, "s": 28036, "text": "With usermod command mention shell and username after –shell option." }, { "code": null, "e": 28229, "s": 28105, "text": "Now you can see the shell use changed. In the above commands, replace nishant with the user name whose shell has to change." }, { "code": null, "e": 28440, "s": 28229, "text": "chsh is the utility to change a user’s login shell. chsh provides the -s option to change the user’s shell. This method also modifies the file /etc/passwd. Use the following command to change shells using chsh:" }, { "code": null, "e": 28466, "s": 28440, "text": "chsh -s /bin/bash nishant" }, { "code": null, "e": 28760, "s": 28466, "text": " As we see in the above two methods, the usermod command and chsh utility modify the /etc/passwd file and change the user shell. We can do that manually also by editing the /etc/passwd file. Just change the shell after the username and home directory in the /etc/passwd file and save the file." }, { "code": null, "e": 28777, "s": 28760, "text": "nano /etc/passwd" }, { "code": null, "e": 28792, "s": 28777, "text": "varshagumber28" }, { "code": null, "e": 28799, "s": 28792, "text": "How To" }, { "code": null, "e": 28810, "s": 28799, "text": "Linux-Unix" }, { "code": null, "e": 28908, "s": 28810, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28942, "s": 28908, "text": "How to Install FFmpeg on Windows?" }, { "code": null, "e": 29000, "s": 28942, "text": "How to Add External JAR File to an IntelliJ IDEA Project?" }, { "code": null, "e": 29049, "s": 29000, "text": "How to Set Git Username and Password in GitBash?" }, { "code": null, "e": 29096, "s": 29049, "text": "How to create a nested RecyclerView in Android" }, { "code": null, "e": 29138, "s": 29096, "text": "How to Install Jupyter Notebook on MacOS?" }, { "code": null, "e": 29178, "s": 29138, "text": "Sed Command in Linux/Unix with examples" }, { "code": null, "e": 29218, "s": 29178, "text": "AWK command in Unix/Linux with examples" }, { "code": null, "e": 29245, "s": 29218, "text": "grep command in Unix/Linux" }, { "code": null, "e": 29280, "s": 29245, "text": "cut command in Linux with examples" } ]
How to change svg icon colors with Tailwind CSS ? - GeeksforGeeks
26 May, 2021 SVG stands for Scalable Vector Graphics and is an XML-based ( can be edited ) vector image format. SVG is commonly used for icons, animations, interactive charts, graphs, and other dynamic graphics in the browser. As it is XML-based, you can easily edit or change the SVG icon colors with Tailwind. Approach: You can simply customize the class of SVG by adding text-color or background-color in icons, but in this process, you have to carefully use the utilities for styling the SVG like fill and stroke in Tailwind CSS. Syntax: <svg class=" text-color bg-color" viewBox="0 0 24 24"> <path d=" "/> </svg> Note: The viewBox attribute defines the position and dimension of an SVG viewport. The value of the viewBox attribute is a list of four numbers, min-x, min-y, width, and height. So the viewBox doesn’t set the size of the SVG, it just determines the frame or window through which we will see the SVG. Example 1: HTML <!DOCTYPE html><html><head> <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet"></head> <body class="text-center mx-4 space-y-2"> <h1 class="text-green-600 text-5xl font-bold"> GeeksforGeeks </h1> <b>Tailwind CSS Stroke Class</b> <div class=" m-4 grid grid-flow-col gap-4 p-5"> <!--- Home Icon ---> <svg xmlns="http://www.w3.org/2000/svg" class="text-red-500 h-16 w-16" fill="none" viewBox="0 0 24 24" stroke="currentColor"> <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6" /> </svg> <!--- Emoji Icon ---> <svg xmlns="http://www.w3.org/2000/svg" class="text-yellow-400 h-16 w-16" fill="none" viewBox="0 0 24 24" stroke="currentColor"> <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M14.828 14.828a4 4 0 01-5.656 0M9 10h.01M15 10h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" /> </svg> </div></body> </html> Output: Example 2: Using fill and stroke utilities for styling icon. fill-current is used to set the fill color of an SVG to the current text color. This makes it easy to set an element’s fill color by combining this class with an existing text color utility. stroke-current is used to set the stroke color of an SVG to the current text color. This makes it easy to set an element’s stroke color by combining this class with an existing text color utility. stroke-width is used to set the stroke width of an SVG. Syntax: <svg class="stroke-current stroke-current stroke-1">...</svg> HTML <!DOCTYPE html><html><head> <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet"></head> <body class="text-center mx-4 space-y-2"> <h1 class="text-green-600 text-5xl font-bold"> GeeksforGeeks </h1> <b>Tailwind CSS SVG</b> <div class=" m-4 grid grid-flow-col gap-4 p-5"> <!--- Home Icon ---> <svg xmlns="http://www.w3.org/2000/svg" class="fill-current text-red-500 h-16 w-16" fill="none" viewBox="0 0 24 24" stroke="currentColor"> <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6" /> </svg> <!--- Emoji Icon ---> <svg xmlns="http://www.w3.org/2000/svg" class="stroke-current stroke-2 text-yellow-400 h-16 w-16" fill="none" viewBox="0 0 24 24" stroke="currentColor"> <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M14.828 14.828a4 4 0 01-5.656 0M9 10h.01M15 10h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" /> </svg> <svg xmlns="http://www.w3.org/2000/svg" class="bg-red-400 text-green-300 h-16 w-16" fill="none" viewBox="0 0 24 24" stroke="currentColor"> <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11.049 2.927c.3-.921 1.603-.921 1.902 0l1.519 4.674a1 1 0 00.95.69h4.915c.969 0 1.371 1.24.588 1.81l-3.976 2.888a1 1 0 00-.363 1.118l1.518 4.674c.3.922-.755 1.688-1.538 1.118l-3.976-2.888a1 1 0 00-1.176 0l-3.976 2.888c-.783.57-1.838-.197-1.538-1.118l1.518-4.674a1 1 0 00-.363-1.118l-3.976-2.888c-.784-.57-.38-1.81.588-1.81h4.914a1 1 0 00.951-.69l1.519-4.674z" /> </svg> </div></body> </html> Output: Picked Tailwind CSS-Questions CSS Web Technologies 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 Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26647, "s": 26619, "text": "\n26 May, 2021" }, { "code": null, "e": 26946, "s": 26647, "text": "SVG stands for Scalable Vector Graphics and is an XML-based ( can be edited ) vector image format. SVG is commonly used for icons, animations, interactive charts, graphs, and other dynamic graphics in the browser. As it is XML-based, you can easily edit or change the SVG icon colors with Tailwind." }, { "code": null, "e": 27168, "s": 26946, "text": "Approach: You can simply customize the class of SVG by adding text-color or background-color in icons, but in this process, you have to carefully use the utilities for styling the SVG like fill and stroke in Tailwind CSS." }, { "code": null, "e": 27176, "s": 27168, "text": "Syntax:" }, { "code": null, "e": 27256, "s": 27176, "text": "<svg class=\" text-color bg-color\" viewBox=\"0 0 24 24\">\n <path d=\" \"/>\n</svg>" }, { "code": null, "e": 27556, "s": 27256, "text": "Note: The viewBox attribute defines the position and dimension of an SVG viewport. The value of the viewBox attribute is a list of four numbers, min-x, min-y, width, and height. So the viewBox doesn’t set the size of the SVG, it just determines the frame or window through which we will see the SVG." }, { "code": null, "e": 27567, "s": 27556, "text": "Example 1:" }, { "code": null, "e": 27572, "s": 27567, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <link href=\"https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css\" rel=\"stylesheet\"></head> <body class=\"text-center mx-4 space-y-2\"> <h1 class=\"text-green-600 text-5xl font-bold\"> GeeksforGeeks </h1> <b>Tailwind CSS Stroke Class</b> <div class=\" m-4 grid grid-flow-col gap-4 p-5\"> <!--- Home Icon ---> <svg xmlns=\"http://www.w3.org/2000/svg\" class=\"text-red-500 h-16 w-16\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\"> <path stroke-linecap=\"round\" stroke-linejoin=\"round\" stroke-width=\"2\" d=\"M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6\" /> </svg> <!--- Emoji Icon ---> <svg xmlns=\"http://www.w3.org/2000/svg\" class=\"text-yellow-400 h-16 w-16\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\"> <path stroke-linecap=\"round\" stroke-linejoin=\"round\" stroke-width=\"2\" d=\"M14.828 14.828a4 4 0 01-5.656 0M9 10h.01M15 10h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z\" /> </svg> </div></body> </html>", "e": 28878, "s": 27572, "text": null }, { "code": null, "e": 28886, "s": 28878, "text": "Output:" }, { "code": null, "e": 28947, "s": 28886, "text": "Example 2: Using fill and stroke utilities for styling icon." }, { "code": null, "e": 29138, "s": 28947, "text": "fill-current is used to set the fill color of an SVG to the current text color. This makes it easy to set an element’s fill color by combining this class with an existing text color utility." }, { "code": null, "e": 29335, "s": 29138, "text": "stroke-current is used to set the stroke color of an SVG to the current text color. This makes it easy to set an element’s stroke color by combining this class with an existing text color utility." }, { "code": null, "e": 29391, "s": 29335, "text": "stroke-width is used to set the stroke width of an SVG." }, { "code": null, "e": 29399, "s": 29391, "text": "Syntax:" }, { "code": null, "e": 29461, "s": 29399, "text": "<svg class=\"stroke-current stroke-current stroke-1\">...</svg>" }, { "code": null, "e": 29466, "s": 29461, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <link href=\"https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css\" rel=\"stylesheet\"></head> <body class=\"text-center mx-4 space-y-2\"> <h1 class=\"text-green-600 text-5xl font-bold\"> GeeksforGeeks </h1> <b>Tailwind CSS SVG</b> <div class=\" m-4 grid grid-flow-col gap-4 p-5\"> <!--- Home Icon ---> <svg xmlns=\"http://www.w3.org/2000/svg\" class=\"fill-current text-red-500 h-16 w-16\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\"> <path stroke-linecap=\"round\" stroke-linejoin=\"round\" stroke-width=\"2\" d=\"M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6\" /> </svg> <!--- Emoji Icon ---> <svg xmlns=\"http://www.w3.org/2000/svg\" class=\"stroke-current stroke-2 text-yellow-400 h-16 w-16\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\"> <path stroke-linecap=\"round\" stroke-linejoin=\"round\" stroke-width=\"2\" d=\"M14.828 14.828a4 4 0 01-5.656 0M9 10h.01M15 10h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z\" /> </svg> <svg xmlns=\"http://www.w3.org/2000/svg\" class=\"bg-red-400 text-green-300 h-16 w-16\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\"> <path stroke-linecap=\"round\" stroke-linejoin=\"round\" stroke-width=\"2\" d=\"M11.049 2.927c.3-.921 1.603-.921 1.902 0l1.519 4.674a1 1 0 00.95.69h4.915c.969 0 1.371 1.24.588 1.81l-3.976 2.888a1 1 0 00-.363 1.118l1.518 4.674c.3.922-.755 1.688-1.538 1.118l-3.976-2.888a1 1 0 00-1.176 0l-3.976 2.888c-.783.57-1.838-.197-1.538-1.118l1.518-4.674a1 1 0 00-.363-1.118l-3.976-2.888c-.784-.57-.38-1.81.588-1.81h4.914a1 1 0 00.951-.69l1.519-4.674z\" /> </svg> </div></body> </html>", "e": 31503, "s": 29466, "text": null }, { "code": null, "e": 31511, "s": 31503, "text": "Output:" }, { "code": null, "e": 31518, "s": 31511, "text": "Picked" }, { "code": null, "e": 31541, "s": 31518, "text": "Tailwind CSS-Questions" }, { "code": null, "e": 31545, "s": 31541, "text": "CSS" }, { "code": null, "e": 31562, "s": 31545, "text": "Web Technologies" }, { "code": null, "e": 31660, "s": 31562, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31699, "s": 31660, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 31736, "s": 31699, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 31765, "s": 31736, "text": "Form validation using jQuery" }, { "code": null, "e": 31800, "s": 31765, "text": "How to style a checkbox using CSS?" }, { "code": null, "e": 31842, "s": 31800, "text": "Search Bar using HTML, CSS and JavaScript" }, { "code": null, "e": 31882, "s": 31842, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 31915, "s": 31882, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 31960, "s": 31915, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 32003, "s": 31960, "text": "How to fetch data from an API in ReactJS ?" } ]
Finding the Size Resolution of Image in Python - GeeksforGeeks
02 Sep, 2020 Let us see how to find the resolution of an image in Python. We will be solving this problem with two different libraries which are present in Python: PIL OpenCV In our examples we will be using the following image: The resolution of the above image is 600×135. We will be using a library named Pillow to find the size(resolution) of the image. We will be using the function PIL.Image.open() to open and read our image and store the size in two variables by using the function img.size. Python3 # importing the moduleimport PILfrom PIL import Image # loading the imageimg = PIL.Image.open("geeksforgeeks.png") # fetching the dimensionswid, hgt = img.size # displaying the dimensionsprint(str(wid) + "x" + str(hgt)) Output: 600x135 We will import OpenCV by importing the library cv2. We will load the image using the cv2.imread() function. After this, the dimensions can be found using the shape attribute. shape[0] will give us the height and shape[1] will give us the width. Python3 # importing the moduleimport cv2 # loading the imageimg = cv2.imread("geeksforgeeks.png") # fetching the dimensionswid = img.shape[1]hgt = img.shape[0] # displaying the dimensionsprint(str(wid) + "x" + str(hgt)) Output: 600x135 Python-OpenCV Python-pil Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | Get unique values from a list Python | os.path.join() method Create a directory in Python Defaultdict in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n02 Sep, 2020" }, { "code": null, "e": 25688, "s": 25537, "text": "Let us see how to find the resolution of an image in Python. We will be solving this problem with two different libraries which are present in Python:" }, { "code": null, "e": 25692, "s": 25688, "text": "PIL" }, { "code": null, "e": 25699, "s": 25692, "text": "OpenCV" }, { "code": null, "e": 25753, "s": 25699, "text": "In our examples we will be using the following image:" }, { "code": null, "e": 25799, "s": 25753, "text": "The resolution of the above image is 600×135." }, { "code": null, "e": 26025, "s": 25799, "text": "We will be using a library named Pillow to find the size(resolution) of the image. We will be using the function PIL.Image.open() to open and read our image and store the size in two variables by using the function img.size. " }, { "code": null, "e": 26033, "s": 26025, "text": "Python3" }, { "code": "# importing the moduleimport PILfrom PIL import Image # loading the imageimg = PIL.Image.open(\"geeksforgeeks.png\") # fetching the dimensionswid, hgt = img.size # displaying the dimensionsprint(str(wid) + \"x\" + str(hgt))", "e": 26256, "s": 26033, "text": null }, { "code": null, "e": 26264, "s": 26256, "text": "Output:" }, { "code": null, "e": 26273, "s": 26264, "text": "600x135\n" }, { "code": null, "e": 26519, "s": 26273, "text": "We will import OpenCV by importing the library cv2. We will load the image using the cv2.imread() function. After this, the dimensions can be found using the shape attribute. shape[0] will give us the height and shape[1] will give us the width. " }, { "code": null, "e": 26527, "s": 26519, "text": "Python3" }, { "code": "# importing the moduleimport cv2 # loading the imageimg = cv2.imread(\"geeksforgeeks.png\") # fetching the dimensionswid = img.shape[1]hgt = img.shape[0] # displaying the dimensionsprint(str(wid) + \"x\" + str(hgt))", "e": 26742, "s": 26527, "text": null }, { "code": null, "e": 26750, "s": 26742, "text": "Output:" }, { "code": null, "e": 26759, "s": 26750, "text": "600x135\n" }, { "code": null, "e": 26773, "s": 26759, "text": "Python-OpenCV" }, { "code": null, "e": 26784, "s": 26773, "text": "Python-pil" }, { "code": null, "e": 26791, "s": 26784, "text": "Python" }, { "code": null, "e": 26889, "s": 26791, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26921, "s": 26889, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26963, "s": 26921, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27005, "s": 26963, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27061, "s": 27005, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27088, "s": 27061, "text": "Python Classes and Objects" }, { "code": null, "e": 27127, "s": 27088, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27158, "s": 27127, "text": "Python | os.path.join() method" }, { "code": null, "e": 27187, "s": 27158, "text": "Create a directory in Python" }, { "code": null, "e": 27209, "s": 27187, "text": "Defaultdict in Python" } ]
Smallest N digit number whose sum of square of digits is a Perfect Square - GeeksforGeeks
17 Feb, 2022 Given an integer N, find the smallest N digit number such that the sum of the square of digits (in decimal representation) of the number is also a perfect square. If no such number exists, print -1.Examples: Input : N = 2 Output : 34 Explanation: The smallest possible 2 digit number whose sum of square of digits is a perfect square is 34 because 32 + 42 = 52.Input : N = 1 Output : 1 Explanation: The smallest possible 1 digit number is 1 itself. Method 1:To solve the problem mentioned above we can use Backtracking. Since we want to find the minimum N digit number satisfying the given condition, the answer will have digits in non-decreasing order. Therefore we generate the possible numbers recursively keeping track of following in each recursive step : position: the current position of the recursive step i.e. which position digit is being placed. prev: the previous digit placed because the current digit has to be greater than equal to prev. sum: the sum of squares of digits placed till now. When digits are placed, this will be used to check whether the sum of squares of all digits placed is a perfect square or not. A vector which stores what all digits have been placed till this position. If placing a digit at a position and moving to the next recursive step leads to a possible solution then return 1, else backtrack.Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation to find Smallest N// digit number whose sum of square// of digits is a Perfect Square #include <bits/stdc++.h>using namespace std; // function to check if// number is a perfect squareint isSquare(int n){ int k = sqrt(n); return (k * k == n);} // function to calculate the// smallest N digit numberint calculate(int pos, int prev, int sum, vector<int>& v){ if (pos == v.size()) return isSquare(sum); // place digits greater than equal to prev for (int i = prev; i <= 9; i++) { v[pos] = i; sum += i * i; // check if placing this digit leads // to a solution then return it if (calculate(pos + 1, i, sum, v)) return 1; // else backtrack sum -= i * i; } return 0;} string minValue(int n){ vector<int> v(n); if (calculate(0, 1, 0, v)) { // create a string representing // the N digit number string answer = ""; for (int i = 0; i < v.size(); i++) answer += char(v[i] + '0'); return answer; } else return "-1";} // driver codeint main(){ // initialise N int N = 2; cout << minValue(N); return 0;} // Java implementation to find Smallest N// digit number whose sum of square// of digits is a Perfect Squareclass GFG{ // function to check if// number is a perfect squarestatic int isSquare(int n){ int k = (int)Math.sqrt(n); return k * k == n ? 1 : 0;} // Function to calculate the// smallest N digit numberstatic int calculate(int pos, int prev, int sum, int[] v){ if (pos == v.length) return isSquare(sum); // Place digits greater than equal to prev for(int i = prev; i <= 9; i++) { v[pos] = i; sum += i * i; // Check if placing this digit leads // to a solution then return it if (calculate(pos + 1, i, sum, v) != 0) return 1; // Else backtrack sum -= i * i; } return 0;} static String minValue(int n){ int[] v = new int[n]; if (calculate(0, 1, 0, v) != 0) { // Create a string representing // the N digit number String answer = ""; for(int i = 0; i < v.length; i++) answer += (char)(v[i] + '0'); return answer; } else return "-1";} // Driver codepublic static void main(String[] args){ // Initialise N int N = 2; System.out.println(minValue(N));}} // This code is contributed by jrishabh99 # Python3 implementation to find Smallest N# digit number whose sum of square# of digits is a Perfect Squarefrom math import sqrt # function to check if# number is a perfect squaredef isSquare(n): k = int(sqrt(n)) return (k * k == n) # function to calculate the# smallest N digit numberdef calculate(pos, prev, sum, v): if (pos == len(v)): return isSquare(sum) # place digits greater than equal to prev for i in range(prev, 9 + 1): v[pos] = i sum += i * i # check if placing this digit leads # to a solution then return it if (calculate(pos + 1, i, sum, v)): return 1 # else backtrack sum -= i * i return 0 def minValue(n): v = [0]*(n) if (calculate(0, 1, 0, v)): # create a representing # the N digit number answer = "" for i in range(len(v)): answer += chr(v[i] + ord('0')) return answer else: return "-1" # Driver codeif __name__ == '__main__': # initialise N N = 2 print(minValue(N)) # This code is contributed by mohit kumar 29 // C# implementation to find Smallest N// digit number whose sum of square// of digits is a Perfect Squareusing System;class GFG{ // function to check if// number is a perfect squarestatic int isSquare(int n){ int k = (int)Math.Sqrt(n); return k * k == n ? 1 : 0;} // Function to calculate the// smallest N digit numberstatic int calculate(int pos, int prev, int sum, int[] v){ if (pos == v.Length) return isSquare(sum); // Place digits greater than equal to prev for(int i = prev; i <= 9; i++) { v[pos] = i; sum += i * i; // Check if placing this digit leads // to a solution then return it if (calculate(pos + 1, i, sum, v) != 0) return 1; // Else backtrack sum -= i * i; } return 0;} static string minValue(int n){ int[] v = new int[n]; if (calculate(0, 1, 0, v) != 0) { // Create a string representing // the N digit number string answer = ""; for(int i = 0; i < v.Length; i++) answer += (char)(v[i] + '0'); return answer; } else return "-1";} // Driver codepublic static void Main(){ // Initialise N int N = 2; Console.Write(minValue(N));}} <script> // Javascript implementation to find Smallest N// digit number whose sum of square// of digits is a Perfect Square // function to check if// number is a perfect squarefunction isSquare(n){ let k = Math.floor(Math.sqrt(n)); return k * k == n ? 1 : 0;} // Function to calculate the// smallest N digit numberfunction calculate(pos, prev, sum, v){ if (pos == v.length) return isSquare(sum); // Place digits greater than equal to prev for(let i = prev; i <= 9; i++) { v[pos] = i; sum += i * i; // Check if placing this digit leads // to a solution then return it if (calculate(pos + 1, i, sum, v) != 0) return 1; // Else backtrack sum -= (i * i); } return 0;} function minValue(n){ let v = Array.from({length: n}, (_, i) => 0); if (calculate(0, 1, 0, v) != 0) { // Create a string representing // the N digit number let answer = ""; for(let i = 0; i < v.length; i++) answer += (v[i] + 0); return answer; } else return "-1";} // Driver Code // Initialise N let N = 2; document.write(minValue(N)); // This code is contributed by sanjoy_62.</script> 34 Time Complexity: O(sqrt(n)) Auxiliary Space: O(n) Method 2:The above-mentioned problem can also be solved using Dynamic Programming. If we observe the question carefully we see that it can be converted to the standard Coin Change problem. Given N as the number of digits, the base answer will be N 1’s, the sum of the square of whose digits will be N. If N itself is a perfect square then the N times 1 will be the final answer. Otherwise, we will have to replace some 1’s in the answer with other digits from 2-9. Each replacement in the digit will increase the sum of the square by a certain amount and since 1 can be changed to only 8 other possible digits there are only 8 such possible increments. For example, if 1 is changed to 2, then increment will be 22 – 12 = 3. Similarly, all possible changes are : {3, 8, 15, 24, 35, 48, 63, 80}. So the problem now can be interpreted as having 8 kinds of coins of the aforementioned values and we can use any coin any number of times to create the required sum. The sum of squares will lie in the range of N (all digits are 1) to 81 * N (all digits are 9). We just have to consider perfect square sums in the range and use the idea of coin change to find the N digits that will be in the answer. One important point we need to take into account is that we have to find the smallest N digit number not the number with the smallest square sum of digits.Below is the implementation of the above-mentioned approach: C++ Java // C++ implementation to find the Smallest// N digit number whose sum of square// of digits is a Perfect Square#include <bits/stdc++.h>using namespace std;long long value[8100006];int first[8100006];// array for all possible changesint coins[8] = { 3, 8, 15, 24, 35, 48, 63, 80 }; void coinChange(){ const long long inf = INT_MAX; // iterating till 81 * N // since N is at max 10^5 for (int x = 1; x <= 8100005; x++) { value[x] = inf; for (auto c : coins) { if (x - c >= 0 && value[x - c] + 1 < value[x]) { value[x] = min(value[x], value[x - c] + 1); // least value of coin first[x] = c; } } }} // function to find the// minimum possible valuestring minValue(int n){ // applying coin change for all the numbers coinChange(); string answer = ""; // check if number is // perfect square or not if ((sqrt(n) * sqrt(n)) == n) { for (int i = 0; i < n; i++) answer += "1"; return answer; } long long hi = 81 * n; long long lo = sqrt(n); // keeps a check whether // number is found or not bool found = false; long long upper = 81 * n; long long lower = n; // sorting suffix strings string suffix; bool suf_init = false; while ((lo * lo) <= hi) { lo++; long long curr = lo * lo; long long change = curr - n; if (value[change] <= lower) { // build a suffix string found = true; if (lower > value[change]) { // number to be used for updation of lower, // first values that will be used // to construct the final number later lower = value[change]; upper = change; suffix = ""; suf_init = true; int len = change; while (len > 0) { int k = sqrt(first[len] + 1); suffix = suffix + char(k + 48); len = len - first[len]; } } else if (lower == value[change]) { string tempsuf = ""; int len = change; while (len > 0) { int k = sqrt(first[len] + 1); tempsuf = tempsuf + char(k + 48); len = len - first[len]; } if (tempsuf < suffix or suf_init == false) { lower = value[change]; upper = change; suffix = tempsuf; suf_init = true; } } } } // check if number is found if (found) { // construct the number from first values long long x = lower; for (int i = 0; i < (n - x); i++) answer += "1"; long long temp = upper; // fill in rest of the digits while (temp > 0) { int dig = sqrt(first[temp] + 1); temp = temp - first[temp]; answer += char(dig + '0'); } return answer; } else return "-1";} // driver codeint main(){ // initialise N int N = 2; cout << minValue(N); return 0;} // Java implementation to find the Smallest// N digit number whose sum of square// of digits is a Perfect Squareimport java.util.*; class GFG { static long[] value = new long[(int)8100006]; static int[] first = new int[8100006]; // array for all possible changes static int coins[] = { 3, 8, 15, 24, 35, 48, 63, 80 }; public static void coinChange() { final long inf = Integer.MAX_VALUE; // iterating till 81 * N // since N is at max 10^5 for (int x = 1; x <= 8100005; x++) { value[x] = inf; for (int c : coins) { if (x - c >= 0 && value[x - c] + 1 < value[x]) { value[x] = Math.min(value[x], value[x - c] + 1); // least value of coin first[x] = c; } } } } // function to find the // minimum possible value public static String minValue(int n) { // applying coin change for all the numbers coinChange(); String answer = ""; // check if number is // perfect square or not if ((Math.sqrt(n) * Math.sqrt(n)) == n) { for (int i = 0; i < n; i++) answer += "1"; return answer; } long hi = 81 * n; long lo = (long)Math.sqrt(n); // keeps a check whether // number is found or not boolean found = false; long upper = 81 * n; long lower = n; // sorting suffix strings String suffix = ""; boolean suf_init = false; while ((lo * lo) <= hi) { lo++; long curr = lo * lo; long change = curr - n; if (value[(int)change] <= lower) { // build a suffix string found = true; if (lower > value[(int)change]) { // number to be used for updation of // lower, first values that will be used // to construct the final number later lower = value[(int)change]; upper = change; suffix = ""; suf_init = true; int len = (int)change; while (len > 0) { int k = (int)Math.sqrt(first[len] + 1); suffix = suffix + (char)(k + 48); len = len - first[len]; } } else if (lower == value[(int)change]) { String tempsuf = ""; int len = (int)change; while (len > 0) { int k = (int)Math.sqrt(first[len] + 1); tempsuf = tempsuf + (char)(k + 48); len = len - first[len]; } if ((tempsuf.compareTo(suffix) < 0) || (suf_init == false)) { lower = value[(int)change]; upper = change; suffix = tempsuf; suf_init = true; } } } } // check if number is found if (found) { // construct the number from first values long x = lower; for (int i = 0; i < (n - x); i++) answer += "1"; long temp = upper; // fill in rest of the digits while (temp > 0) { int dig = (int)Math.sqrt(first[(int)temp] + 1); temp = temp - first[(int)temp]; answer += (char)(dig + '0'); } return answer; } else return "-1"; } // Driver code public static void main(String[] args) { // initialise N int N = 2; System.out.println(minValue(N)); }} // This code is contributed by Palak Gupta 34 Time Complexity : O(81 * N) Auxiliary Space: O(81 * 105) mohit kumar 29 jrishabh99 ukasp sanjoy_62 sumitgumber28 as5853535 gulshankumarar231 rishavmahato348 ninja_hattori Backtracking Dynamic Programming Mathematical Dynamic Programming Mathematical Backtracking Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Hamiltonian Cycle | Backtracking-6 m Coloring Problem | Backtracking-5 8 queen problem Subset Sum | Backtracking-4 Printing all solutions in N-Queen Problem 0-1 Knapsack Problem | DP-10 Largest Sum Contiguous Subarray Longest Common Subsequence | DP-4 Bellman–Ford Algorithm | DP-23 Floyd Warshall Algorithm | DP-16
[ { "code": null, "e": 26349, "s": 26321, "text": "\n17 Feb, 2022" }, { "code": null, "e": 26558, "s": 26349, "text": "Given an integer N, find the smallest N digit number such that the sum of the square of digits (in decimal representation) of the number is also a perfect square. If no such number exists, print -1.Examples: " }, { "code": null, "e": 26801, "s": 26558, "text": "Input : N = 2 Output : 34 Explanation: The smallest possible 2 digit number whose sum of square of digits is a perfect square is 34 because 32 + 42 = 52.Input : N = 1 Output : 1 Explanation: The smallest possible 1 digit number is 1 itself. " }, { "code": null, "e": 27113, "s": 26801, "text": "Method 1:To solve the problem mentioned above we can use Backtracking. Since we want to find the minimum N digit number satisfying the given condition, the answer will have digits in non-decreasing order. Therefore we generate the possible numbers recursively keeping track of following in each recursive step :" }, { "code": null, "e": 27209, "s": 27113, "text": "position: the current position of the recursive step i.e. which position digit is being placed." }, { "code": null, "e": 27305, "s": 27209, "text": "prev: the previous digit placed because the current digit has to be greater than equal to prev." }, { "code": null, "e": 27483, "s": 27305, "text": "sum: the sum of squares of digits placed till now. When digits are placed, this will be used to check whether the sum of squares of all digits placed is a perfect square or not." }, { "code": null, "e": 27558, "s": 27483, "text": "A vector which stores what all digits have been placed till this position." }, { "code": null, "e": 27739, "s": 27558, "text": "If placing a digit at a position and moving to the next recursive step leads to a possible solution then return 1, else backtrack.Below is the implementation of the above approach:" }, { "code": null, "e": 27743, "s": 27739, "text": "C++" }, { "code": null, "e": 27748, "s": 27743, "text": "Java" }, { "code": null, "e": 27756, "s": 27748, "text": "Python3" }, { "code": null, "e": 27759, "s": 27756, "text": "C#" }, { "code": null, "e": 27770, "s": 27759, "text": "Javascript" }, { "code": "// C++ implementation to find Smallest N// digit number whose sum of square// of digits is a Perfect Square #include <bits/stdc++.h>using namespace std; // function to check if// number is a perfect squareint isSquare(int n){ int k = sqrt(n); return (k * k == n);} // function to calculate the// smallest N digit numberint calculate(int pos, int prev, int sum, vector<int>& v){ if (pos == v.size()) return isSquare(sum); // place digits greater than equal to prev for (int i = prev; i <= 9; i++) { v[pos] = i; sum += i * i; // check if placing this digit leads // to a solution then return it if (calculate(pos + 1, i, sum, v)) return 1; // else backtrack sum -= i * i; } return 0;} string minValue(int n){ vector<int> v(n); if (calculate(0, 1, 0, v)) { // create a string representing // the N digit number string answer = \"\"; for (int i = 0; i < v.size(); i++) answer += char(v[i] + '0'); return answer; } else return \"-1\";} // driver codeint main(){ // initialise N int N = 2; cout << minValue(N); return 0;}", "e": 28972, "s": 27770, "text": null }, { "code": "// Java implementation to find Smallest N// digit number whose sum of square// of digits is a Perfect Squareclass GFG{ // function to check if// number is a perfect squarestatic int isSquare(int n){ int k = (int)Math.sqrt(n); return k * k == n ? 1 : 0;} // Function to calculate the// smallest N digit numberstatic int calculate(int pos, int prev, int sum, int[] v){ if (pos == v.length) return isSquare(sum); // Place digits greater than equal to prev for(int i = prev; i <= 9; i++) { v[pos] = i; sum += i * i; // Check if placing this digit leads // to a solution then return it if (calculate(pos + 1, i, sum, v) != 0) return 1; // Else backtrack sum -= i * i; } return 0;} static String minValue(int n){ int[] v = new int[n]; if (calculate(0, 1, 0, v) != 0) { // Create a string representing // the N digit number String answer = \"\"; for(int i = 0; i < v.length; i++) answer += (char)(v[i] + '0'); return answer; } else return \"-1\";} // Driver codepublic static void main(String[] args){ // Initialise N int N = 2; System.out.println(minValue(N));}} // This code is contributed by jrishabh99", "e": 30283, "s": 28972, "text": null }, { "code": "# Python3 implementation to find Smallest N# digit number whose sum of square# of digits is a Perfect Squarefrom math import sqrt # function to check if# number is a perfect squaredef isSquare(n): k = int(sqrt(n)) return (k * k == n) # function to calculate the# smallest N digit numberdef calculate(pos, prev, sum, v): if (pos == len(v)): return isSquare(sum) # place digits greater than equal to prev for i in range(prev, 9 + 1): v[pos] = i sum += i * i # check if placing this digit leads # to a solution then return it if (calculate(pos + 1, i, sum, v)): return 1 # else backtrack sum -= i * i return 0 def minValue(n): v = [0]*(n) if (calculate(0, 1, 0, v)): # create a representing # the N digit number answer = \"\" for i in range(len(v)): answer += chr(v[i] + ord('0')) return answer else: return \"-1\" # Driver codeif __name__ == '__main__': # initialise N N = 2 print(minValue(N)) # This code is contributed by mohit kumar 29", "e": 31384, "s": 30283, "text": null }, { "code": "// C# implementation to find Smallest N// digit number whose sum of square// of digits is a Perfect Squareusing System;class GFG{ // function to check if// number is a perfect squarestatic int isSquare(int n){ int k = (int)Math.Sqrt(n); return k * k == n ? 1 : 0;} // Function to calculate the// smallest N digit numberstatic int calculate(int pos, int prev, int sum, int[] v){ if (pos == v.Length) return isSquare(sum); // Place digits greater than equal to prev for(int i = prev; i <= 9; i++) { v[pos] = i; sum += i * i; // Check if placing this digit leads // to a solution then return it if (calculate(pos + 1, i, sum, v) != 0) return 1; // Else backtrack sum -= i * i; } return 0;} static string minValue(int n){ int[] v = new int[n]; if (calculate(0, 1, 0, v) != 0) { // Create a string representing // the N digit number string answer = \"\"; for(int i = 0; i < v.Length; i++) answer += (char)(v[i] + '0'); return answer; } else return \"-1\";} // Driver codepublic static void Main(){ // Initialise N int N = 2; Console.Write(minValue(N));}}", "e": 32646, "s": 31384, "text": null }, { "code": "<script> // Javascript implementation to find Smallest N// digit number whose sum of square// of digits is a Perfect Square // function to check if// number is a perfect squarefunction isSquare(n){ let k = Math.floor(Math.sqrt(n)); return k * k == n ? 1 : 0;} // Function to calculate the// smallest N digit numberfunction calculate(pos, prev, sum, v){ if (pos == v.length) return isSquare(sum); // Place digits greater than equal to prev for(let i = prev; i <= 9; i++) { v[pos] = i; sum += i * i; // Check if placing this digit leads // to a solution then return it if (calculate(pos + 1, i, sum, v) != 0) return 1; // Else backtrack sum -= (i * i); } return 0;} function minValue(n){ let v = Array.from({length: n}, (_, i) => 0); if (calculate(0, 1, 0, v) != 0) { // Create a string representing // the N digit number let answer = \"\"; for(let i = 0; i < v.length; i++) answer += (v[i] + 0); return answer; } else return \"-1\";} // Driver Code // Initialise N let N = 2; document.write(minValue(N)); // This code is contributed by sanjoy_62.</script>", "e": 33904, "s": 32646, "text": null }, { "code": null, "e": 33907, "s": 33904, "text": "34" }, { "code": null, "e": 33935, "s": 33907, "text": "Time Complexity: O(sqrt(n))" }, { "code": null, "e": 33957, "s": 33935, "text": "Auxiliary Space: O(n)" }, { "code": null, "e": 34261, "s": 33957, "text": "Method 2:The above-mentioned problem can also be solved using Dynamic Programming. If we observe the question carefully we see that it can be converted to the standard Coin Change problem. Given N as the number of digits, the base answer will be N 1’s, the sum of the square of whose digits will be N. " }, { "code": null, "e": 34338, "s": 34261, "text": "If N itself is a perfect square then the N times 1 will be the final answer." }, { "code": null, "e": 34753, "s": 34338, "text": "Otherwise, we will have to replace some 1’s in the answer with other digits from 2-9. Each replacement in the digit will increase the sum of the square by a certain amount and since 1 can be changed to only 8 other possible digits there are only 8 such possible increments. For example, if 1 is changed to 2, then increment will be 22 – 12 = 3. Similarly, all possible changes are : {3, 8, 15, 24, 35, 48, 63, 80}." }, { "code": null, "e": 35370, "s": 34753, "text": "So the problem now can be interpreted as having 8 kinds of coins of the aforementioned values and we can use any coin any number of times to create the required sum. The sum of squares will lie in the range of N (all digits are 1) to 81 * N (all digits are 9). We just have to consider perfect square sums in the range and use the idea of coin change to find the N digits that will be in the answer. One important point we need to take into account is that we have to find the smallest N digit number not the number with the smallest square sum of digits.Below is the implementation of the above-mentioned approach: " }, { "code": null, "e": 35374, "s": 35370, "text": "C++" }, { "code": null, "e": 35379, "s": 35374, "text": "Java" }, { "code": "// C++ implementation to find the Smallest// N digit number whose sum of square// of digits is a Perfect Square#include <bits/stdc++.h>using namespace std;long long value[8100006];int first[8100006];// array for all possible changesint coins[8] = { 3, 8, 15, 24, 35, 48, 63, 80 }; void coinChange(){ const long long inf = INT_MAX; // iterating till 81 * N // since N is at max 10^5 for (int x = 1; x <= 8100005; x++) { value[x] = inf; for (auto c : coins) { if (x - c >= 0 && value[x - c] + 1 < value[x]) { value[x] = min(value[x], value[x - c] + 1); // least value of coin first[x] = c; } } }} // function to find the// minimum possible valuestring minValue(int n){ // applying coin change for all the numbers coinChange(); string answer = \"\"; // check if number is // perfect square or not if ((sqrt(n) * sqrt(n)) == n) { for (int i = 0; i < n; i++) answer += \"1\"; return answer; } long long hi = 81 * n; long long lo = sqrt(n); // keeps a check whether // number is found or not bool found = false; long long upper = 81 * n; long long lower = n; // sorting suffix strings string suffix; bool suf_init = false; while ((lo * lo) <= hi) { lo++; long long curr = lo * lo; long long change = curr - n; if (value[change] <= lower) { // build a suffix string found = true; if (lower > value[change]) { // number to be used for updation of lower, // first values that will be used // to construct the final number later lower = value[change]; upper = change; suffix = \"\"; suf_init = true; int len = change; while (len > 0) { int k = sqrt(first[len] + 1); suffix = suffix + char(k + 48); len = len - first[len]; } } else if (lower == value[change]) { string tempsuf = \"\"; int len = change; while (len > 0) { int k = sqrt(first[len] + 1); tempsuf = tempsuf + char(k + 48); len = len - first[len]; } if (tempsuf < suffix or suf_init == false) { lower = value[change]; upper = change; suffix = tempsuf; suf_init = true; } } } } // check if number is found if (found) { // construct the number from first values long long x = lower; for (int i = 0; i < (n - x); i++) answer += \"1\"; long long temp = upper; // fill in rest of the digits while (temp > 0) { int dig = sqrt(first[temp] + 1); temp = temp - first[temp]; answer += char(dig + '0'); } return answer; } else return \"-1\";} // driver codeint main(){ // initialise N int N = 2; cout << minValue(N); return 0;}", "e": 38608, "s": 35379, "text": null }, { "code": "// Java implementation to find the Smallest// N digit number whose sum of square// of digits is a Perfect Squareimport java.util.*; class GFG { static long[] value = new long[(int)8100006]; static int[] first = new int[8100006]; // array for all possible changes static int coins[] = { 3, 8, 15, 24, 35, 48, 63, 80 }; public static void coinChange() { final long inf = Integer.MAX_VALUE; // iterating till 81 * N // since N is at max 10^5 for (int x = 1; x <= 8100005; x++) { value[x] = inf; for (int c : coins) { if (x - c >= 0 && value[x - c] + 1 < value[x]) { value[x] = Math.min(value[x], value[x - c] + 1); // least value of coin first[x] = c; } } } } // function to find the // minimum possible value public static String minValue(int n) { // applying coin change for all the numbers coinChange(); String answer = \"\"; // check if number is // perfect square or not if ((Math.sqrt(n) * Math.sqrt(n)) == n) { for (int i = 0; i < n; i++) answer += \"1\"; return answer; } long hi = 81 * n; long lo = (long)Math.sqrt(n); // keeps a check whether // number is found or not boolean found = false; long upper = 81 * n; long lower = n; // sorting suffix strings String suffix = \"\"; boolean suf_init = false; while ((lo * lo) <= hi) { lo++; long curr = lo * lo; long change = curr - n; if (value[(int)change] <= lower) { // build a suffix string found = true; if (lower > value[(int)change]) { // number to be used for updation of // lower, first values that will be used // to construct the final number later lower = value[(int)change]; upper = change; suffix = \"\"; suf_init = true; int len = (int)change; while (len > 0) { int k = (int)Math.sqrt(first[len] + 1); suffix = suffix + (char)(k + 48); len = len - first[len]; } } else if (lower == value[(int)change]) { String tempsuf = \"\"; int len = (int)change; while (len > 0) { int k = (int)Math.sqrt(first[len] + 1); tempsuf = tempsuf + (char)(k + 48); len = len - first[len]; } if ((tempsuf.compareTo(suffix) < 0) || (suf_init == false)) { lower = value[(int)change]; upper = change; suffix = tempsuf; suf_init = true; } } } } // check if number is found if (found) { // construct the number from first values long x = lower; for (int i = 0; i < (n - x); i++) answer += \"1\"; long temp = upper; // fill in rest of the digits while (temp > 0) { int dig = (int)Math.sqrt(first[(int)temp] + 1); temp = temp - first[(int)temp]; answer += (char)(dig + '0'); } return answer; } else return \"-1\"; } // Driver code public static void main(String[] args) { // initialise N int N = 2; System.out.println(minValue(N)); }} // This code is contributed by Palak Gupta", "e": 41978, "s": 38608, "text": null }, { "code": null, "e": 41981, "s": 41978, "text": "34" }, { "code": null, "e": 42011, "s": 41983, "text": "Time Complexity : O(81 * N)" }, { "code": null, "e": 42041, "s": 42011, "text": "Auxiliary Space: O(81 * 105) " }, { "code": null, "e": 42056, "s": 42041, "text": "mohit kumar 29" }, { "code": null, "e": 42067, "s": 42056, "text": "jrishabh99" }, { "code": null, "e": 42073, "s": 42067, "text": "ukasp" }, { "code": null, "e": 42083, "s": 42073, "text": "sanjoy_62" }, { "code": null, "e": 42097, "s": 42083, "text": "sumitgumber28" }, { "code": null, "e": 42107, "s": 42097, "text": "as5853535" }, { "code": null, "e": 42125, "s": 42107, "text": "gulshankumarar231" }, { "code": null, "e": 42141, "s": 42125, "text": "rishavmahato348" }, { "code": null, "e": 42155, "s": 42141, "text": "ninja_hattori" }, { "code": null, "e": 42168, "s": 42155, "text": "Backtracking" }, { "code": null, "e": 42188, "s": 42168, "text": "Dynamic Programming" }, { "code": null, "e": 42201, "s": 42188, "text": "Mathematical" }, { "code": null, "e": 42221, "s": 42201, "text": "Dynamic Programming" }, { "code": null, "e": 42234, "s": 42221, "text": "Mathematical" }, { "code": null, "e": 42247, "s": 42234, "text": "Backtracking" }, { "code": null, "e": 42345, "s": 42247, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 42380, "s": 42345, "text": "Hamiltonian Cycle | Backtracking-6" }, { "code": null, "e": 42416, "s": 42380, "text": "m Coloring Problem | Backtracking-5" }, { "code": null, "e": 42432, "s": 42416, "text": "8 queen problem" }, { "code": null, "e": 42460, "s": 42432, "text": "Subset Sum | Backtracking-4" }, { "code": null, "e": 42502, "s": 42460, "text": "Printing all solutions in N-Queen Problem" }, { "code": null, "e": 42531, "s": 42502, "text": "0-1 Knapsack Problem | DP-10" }, { "code": null, "e": 42563, "s": 42531, "text": "Largest Sum Contiguous Subarray" }, { "code": null, "e": 42597, "s": 42563, "text": "Longest Common Subsequence | DP-4" }, { "code": null, "e": 42628, "s": 42597, "text": "Bellman–Ford Algorithm | DP-23" } ]
Period parse() method in Java with Examples - GeeksforGeeks
28 Nov, 2018 The parse() method of Period Class is used to obtain a period from given string in the form of PnYnMnD where nY means n years, nM means n months and nD means n days. Syntax: public static Period parse(CharSequence text) Parameters: This method accepts a single parameter text which is the String to be parsed. Returns: This function returns the period which is the parsed representation of the String given as the parameter Below is the implementation of Period.parse() method: Example 1: // Java code to demonstrate parse() method// to obtain period from given string import java.time.Period; class GFG { public static void main(String[] args) { // Get the String to be parsed String period = "P1Y2M21D"; // Parse the String into Period // using parse() method Period p = Period.parse(period); System.out.println(p.getYears() + " Years\n" + p.getMonths() + " Months\n" + p.getDays() + " Days"); }} 1 Years 2 Months 21 Days Example 2: // Java code to demonstrate parse() method// to obtain period from given string import java.time.Period; class GFG { public static void main(String[] args) { // Get the String to be parsed String period = "-P1Y2M21D"; // Parse the String into Period // using parse() method Period p = Period.parse(period); System.out.println(p.getYears() + " Years\n" + p.getMonths() + " Months\n" + p.getDays() + " Days"); }} -1 Years -2 Months -21 Days Reference: https://docs.oracle.com/javase/9/docs/api/java/time/Period.html#parse-java.lang.CharSequence- Java-Functions Java-Period Java-time package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples Stream In Java Interfaces in Java How to iterate any Map in Java ArrayList in Java Initialize an ArrayList in Java Stack Class in Java Multidimensional Arrays in Java Singleton Class in Java
[ { "code": null, "e": 25609, "s": 25581, "text": "\n28 Nov, 2018" }, { "code": null, "e": 25775, "s": 25609, "text": "The parse() method of Period Class is used to obtain a period from given string in the form of PnYnMnD where nY means n years, nM means n months and nD means n days." }, { "code": null, "e": 25783, "s": 25775, "text": "Syntax:" }, { "code": null, "e": 25829, "s": 25783, "text": "public static Period parse(CharSequence text)" }, { "code": null, "e": 25919, "s": 25829, "text": "Parameters: This method accepts a single parameter text which is the String to be parsed." }, { "code": null, "e": 26033, "s": 25919, "text": "Returns: This function returns the period which is the parsed representation of the String given as the parameter" }, { "code": null, "e": 26087, "s": 26033, "text": "Below is the implementation of Period.parse() method:" }, { "code": null, "e": 26098, "s": 26087, "text": "Example 1:" }, { "code": "// Java code to demonstrate parse() method// to obtain period from given string import java.time.Period; class GFG { public static void main(String[] args) { // Get the String to be parsed String period = \"P1Y2M21D\"; // Parse the String into Period // using parse() method Period p = Period.parse(period); System.out.println(p.getYears() + \" Years\\n\" + p.getMonths() + \" Months\\n\" + p.getDays() + \" Days\"); }}", "e": 26619, "s": 26098, "text": null }, { "code": null, "e": 26645, "s": 26619, "text": "1 Years\n2 Months\n21 Days\n" }, { "code": null, "e": 26656, "s": 26645, "text": "Example 2:" }, { "code": "// Java code to demonstrate parse() method// to obtain period from given string import java.time.Period; class GFG { public static void main(String[] args) { // Get the String to be parsed String period = \"-P1Y2M21D\"; // Parse the String into Period // using parse() method Period p = Period.parse(period); System.out.println(p.getYears() + \" Years\\n\" + p.getMonths() + \" Months\\n\" + p.getDays() + \" Days\"); }}", "e": 27178, "s": 26656, "text": null }, { "code": null, "e": 27207, "s": 27178, "text": "-1 Years\n-2 Months\n-21 Days\n" }, { "code": null, "e": 27312, "s": 27207, "text": "Reference: https://docs.oracle.com/javase/9/docs/api/java/time/Period.html#parse-java.lang.CharSequence-" }, { "code": null, "e": 27327, "s": 27312, "text": "Java-Functions" }, { "code": null, "e": 27339, "s": 27327, "text": "Java-Period" }, { "code": null, "e": 27357, "s": 27339, "text": "Java-time package" }, { "code": null, "e": 27362, "s": 27357, "text": "Java" }, { "code": null, "e": 27367, "s": 27362, "text": "Java" }, { "code": null, "e": 27465, "s": 27367, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27516, "s": 27465, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 27546, "s": 27516, "text": "HashMap in Java with Examples" }, { "code": null, "e": 27561, "s": 27546, "text": "Stream In Java" }, { "code": null, "e": 27580, "s": 27561, "text": "Interfaces in Java" }, { "code": null, "e": 27611, "s": 27580, "text": "How to iterate any Map in Java" }, { "code": null, "e": 27629, "s": 27611, "text": "ArrayList in Java" }, { "code": null, "e": 27661, "s": 27629, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 27681, "s": 27661, "text": "Stack Class in Java" }, { "code": null, "e": 27713, "s": 27681, "text": "Multidimensional Arrays in Java" } ]
Count prime factors of N! - GeeksforGeeks
09 Nov, 2021 Given an integer N, the task is to count the number of prime factors of N!. Examples: Input: N = 5Output: 3Explanation: Factorial of 5 = 120. Prime factors of 120 are {2, 3, 5}. Therefore, the count is 3. Input: N = 1Output: 0 Naive Approach: Follow the steps to solve the problem : Initialize a variable, say fac, to store the factorial of a number.Initialize a variable, say count, to count the prime factors of N!.Iterate over the range [2, fac], and if the number is not prime, increment count.Print the count as the answer. Initialize a variable, say fac, to store the factorial of a number. Initialize a variable, say count, to count the prime factors of N!. Iterate over the range [2, fac], and if the number is not prime, increment count. Print the count as the answer. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to calculate// factorial of a numberint factorial(int f){ // Base Case if (f == 0 || f == 1) { return 1; } else { // Recursive call return (f * factorial(f - 1)); }} // Function to check if a// number is prime or notbool isPrime(int element){ for (int i = 2; i <= sqrt(element); i++) { if (element % i == 0) { // Not prime return false; } } // Is prime return true;} // Function to count the number// of prime factors of N!int countPrimeFactors(int N){ // Stores factorial of N int fac = factorial(N); // Stores the count of // prime factors int count = 0; // Iterate over the rage [2, fac] for (int i = 2; i <= fac; i++) { // If not prime if (fac % i == 0 && isPrime(i)) { // Increment count count++; } } // Print the count cout << count;} // Driver Codeint main(){ // Given value of N int N = 5; // Function call to count the // number of prime factors of N countPrimeFactors(N); return 0;} // Java program for the above approachimport java.util.*; class GFG{ // Function to calculate // factorial of a number static int factorial(int f) { // Base Case if (f == 0 || f == 1) { return 1; } else { // Recursive call return (f * factorial(f - 1)); } } // Function to check if a // number is prime or not static boolean isPrime(int element) { for (int i = 2; i <= (int)Math.sqrt(element); i++) { if (element % i == 0) { // Not prime return false; } } // Is prime return true; } // Function to count the number // of prime factors of N! static void countPrimeFactors(int N) { // Stores factorial of N int fac = factorial(N); // Stores the count of // prime factors int count = 0; // Iterate over the rage [2, fac] for (int i = 2; i <= fac; i++) { // If not prime if ((fac % i == 0 && isPrime(i))) { // Increment count count++; } } // Print the count System.out.println(count); } // Driver Code public static void main(String[] args) { // Given value of N int N = 5; // Function call to count the // number of prime factors of N countPrimeFactors(N); }} // This code is contributed by sanjoy_62. # Python program for the above approachfrom math import sqrt # Function to calculate# factorial of a numberdef factorial(f): # Base Case if (f == 0 or f == 1): return 1 else: # Recursive call return (f * factorial(f - 1)) # Function to check if a# number is prime or notdef isPrime(element): for i in range(2,int(sqrt(element))+1): if (element % i == 0): # Not prime return False # Is prime return True # Function to count the number# of prime factors of N!def countPrimeFactors(N): # Stores factorial of N fac = factorial(N) # Stores the count of # prime factors count = 0 # Iterate over the rage [2, fac] for i in range(2, fac + 1): # If not prime if (fac % i == 0 and isPrime(i)): # Increment count count += 1 # Print the count print(count) # Driver Code# Given value of NN = 5 # Function call to count the# number of prime factors of NcountPrimeFactors(N) # This code is contributed by shubhamsingh10 // C# program for the above approachusing System; class GFG{ // Function to calculate // factorial of a number static int factorial(int f) { // Base Case if (f == 0 || f == 1) { return 1; } else { // Recursive call return (f * factorial(f - 1)); } } // Function to check if a // number is prime or not static bool isPrime(int element) { for (int i = 2; i <= (int)Math.Sqrt(element); i++) { if (element % i == 0) { // Not prime return false; } } // Is prime return true; } // Function to count the number // of prime factors of N! static void countPrimeFactors(int N) { // Stores factorial of N int fac = factorial(N); // Stores the count of // prime factors int count = 0; // Iterate over the range [2, fac] for (int i = 2; i <= fac; i++) { // If not prime if ((fac % i == 0 && isPrime(i))) { // Increment count count++; } } // Print the count Console.Write(count); } // Driver Codepublic static void Main(){ // Given value of N int N = 5; // Function call to count the // number of prime factors of N countPrimeFactors(N);}} // This code is contributed by code_hunt. <script>// Javascript program for the above approach // Function to calculate// factorial of a numberfunction factorial(f){ // Base Case if (f == 0 || f == 1){ return 1 } else{ // Recursive call return (f * factorial(f - 1)) } } // Function to check if a// number is prime or notfunction isPrime(element){ for (let i = 2; i < Math.floor(Math.sqrt(element)+1); i++){ if (element % i == 0){ // Not prime return false } } // Is prime return true} // Function to count the number// of prime factors of N!function countPrimeFactors(N){ // Stores factorial of N let fac = factorial(N) // Stores the count of // prime factors let count = 0 // Iterate over the range [2, fac] for(let i = 2; i < fac + 1; i++){ // If not prime if (fac % i == 0 && isPrime(i)){ // Increment count count += 1 } } // Print the count document.write(count)} // Driver Code// Given value of Nlet N = 5 // Function call to count the// number of prime factors of NcountPrimeFactors(N)// This code is contributed by _saurabh_jaiswal</script> 3 Time Complexity: O(N! * sqrt(N))Auxiliary Space: O(1) Efficient Approach: To optimize the above approach, the idea is to use Sieve Of Eratosthenes. Follow the steps below to solve the problem: Initialize a variable, say count, to store the count of prime factors of N!.Initialize a boolean array, say prime[] to check if a number is prime or not.Perform Sieve of Eratosthenes and populate count at each iteration, if found prime.Print the value of count as the answer. Initialize a variable, say count, to store the count of prime factors of N!. Initialize a boolean array, say prime[] to check if a number is prime or not. Perform Sieve of Eratosthenes and populate count at each iteration, if found prime. Print the value of count as the answer. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ approach for the above approach #include <bits/stdc++.h>using namespace std; // Function to count the// prime factors of N!int countPrimeFactors(int N){ // Stores the count of // prime factors int count = 0; // Stores whether a number // is prime or not bool prime[N + 1]; // Mark all as true initially memset(prime, true, sizeof(prime)); // Sieve of Eratosthenes for (int p = 2; p * p <= N; p++) { // If prime[p] is not changed, // then it is a prime if (prime[p] == true) { // Update all subsequent multiples for (int i = p * p; i <= N; i += p) prime[i] = false; } } // Traverse in the range [2, N] for (int p = 2; p <= N; p++) { // If prime if (prime[p]) { // Increment the count count++; } } // Print the count cout << count;} // Driver Codeint main(){ // Given value of N int N = 5; // Function call to count // the prime factors of N! countPrimeFactors(N); return 0;} // Java program for the above approachimport java.io.*;import java.util.*;class GFG{ // Function to count the // prime factors of N! static void countPrimeFactors(int N) { // Stores the count of // prime factors int count = 0; // Stores whether a number // is prime or not boolean[] prime = new boolean[N + 1]; // Mark all as true initially Arrays.fill(prime, true); // Sieve of Eratosthenes for (int p = 2; p * p <= N; p++) { // If prime[p] is not changed, // then it is a prime if (prime[p] == true) { // Update all subsequent multiples for (int i = p * p; i <= N; i += p) prime[i] = false; } } // Traverse in the range [2, N] for (int p = 2; p <= N; p++) { // If prime if (prime[p] != false) { // Increment the count count++; } } // Print the count System.out.print(count); } // Driver Code public static void main(String[] args) { // Given value of N int N = 5; // Function call to count // the prime factors of N! countPrimeFactors(N); }} // This code is contributed by susmitakundugoaldanga. # Python3 approach for the above approach # Function to count the# prime factors of N!def countPrimeFactors(N): # Stores the count of # prime factors count = 0 # Stores whether a number # is prime or not prime = [1] * (N + 1) # Sieve of Eratosthenes for p in range(2, N + 1): if p * p > N: break # If prime[p] is not changed, # then it is a prime if (prime[p]): # Update all subsequent multiples for i in range(p * p, N + 1, p): prime[i] = 0 # Traverse in the range [2, N] for p in range(2, N + 1): # If prime if (prime[p]): # Increment the count count += 1 # Print the count print (count) # Driver Codeif __name__ == '__main__': # Given value of N N = 5 # Function call to count # the prime factors of N! countPrimeFactors(N) # This code is contributed by mohit kumar 29 // C# program for the above approachusing System;public class GFG{ // Function to count the // prime factors of N! static void countPrimeFactors(int N) { // Stores the count of // prime factors int count = 0; // Stores whether a number // is prime or not bool[] prime = new bool[N + 1]; // Mark all as true initially for (int i = 0; i < prime.Length; i++) prime[i] = true; // Sieve of Eratosthenes for (int p = 2; p * p <= N; p++) { // If prime[p] is not changed, // then it is a prime if (prime[p] == true) { // Update all subsequent multiples for (int i = p * p; i <= N; i += p) prime[i] = false; } } // Traverse in the range [2, N] for (int p = 2; p <= N; p++) { // If prime if (prime[p] != false) { // Increment the count count++; } } // Print the count Console.Write(count); } // Driver Code public static void Main(String[] args) { // Given value of N int N = 5; // Function call to count // the prime factors of N! countPrimeFactors(N); }} // This code is contributed by shikhasingrajput <script> // JavaScript program for the above approach // Function to count the // prime factors of N! function countPrimeFactors( N) { // Stores the count of // prime factors var count = 0; // Stores whether a number // is prime or not var prime = Array(N + 1).fill(true); // Sieve of Eratosthenes for (var p = 2; p * p <= N; p++) { // If prime[p] is not changed, // then it is a prime if (prime[p] == true) { // Update all subsequent multiples for (var i = p * p; i <= N; i += p) prime[i] = false; } } // Traverse in the range [2, N] for (var p = 2; p <= N; p++) { // If prime if (prime[p] != false) { // Increment the count count++; } } // Print the count document.write(count); } // Driver Code // Given value of N var N = 5; // Function call to count // the prime factors of N! countPrimeFactors(N); // This code is contributed by Amit Katiyar </script> 3 Time Complexity: O(N * log(logN))Auxiliary Space: O(N) sanjoy_62 code_hunt SHUBHAMSINGH10 susmitakundugoaldanga shikhasingrajput _saurabh_jaiswal amit143katiyar mohit kumar 29 Kirti_Mangal factorial prime-factor sieve Mathematical Recursion Mathematical Recursion sieve factorial Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Program to print prime numbers from 1 to N. Segment Tree | Set 1 (Sum of given range) Modular multiplicative inverse Count all possible paths from top left to bottom right of a mXn matrix Fizz Buzz Implementation 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 Program for Sum of the digits of a given number
[ { "code": null, "e": 25961, "s": 25933, "text": "\n09 Nov, 2021" }, { "code": null, "e": 26037, "s": 25961, "text": "Given an integer N, the task is to count the number of prime factors of N!." }, { "code": null, "e": 26047, "s": 26037, "text": "Examples:" }, { "code": null, "e": 26166, "s": 26047, "text": "Input: N = 5Output: 3Explanation: Factorial of 5 = 120. Prime factors of 120 are {2, 3, 5}. Therefore, the count is 3." }, { "code": null, "e": 26188, "s": 26166, "text": "Input: N = 1Output: 0" }, { "code": null, "e": 26244, "s": 26188, "text": "Naive Approach: Follow the steps to solve the problem :" }, { "code": null, "e": 26490, "s": 26244, "text": "Initialize a variable, say fac, to store the factorial of a number.Initialize a variable, say count, to count the prime factors of N!.Iterate over the range [2, fac], and if the number is not prime, increment count.Print the count as the answer." }, { "code": null, "e": 26558, "s": 26490, "text": "Initialize a variable, say fac, to store the factorial of a number." }, { "code": null, "e": 26626, "s": 26558, "text": "Initialize a variable, say count, to count the prime factors of N!." }, { "code": null, "e": 26708, "s": 26626, "text": "Iterate over the range [2, fac], and if the number is not prime, increment count." }, { "code": null, "e": 26739, "s": 26708, "text": "Print the count as the answer." }, { "code": null, "e": 26790, "s": 26739, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 26794, "s": 26790, "text": "C++" }, { "code": null, "e": 26799, "s": 26794, "text": "Java" }, { "code": null, "e": 26807, "s": 26799, "text": "Python3" }, { "code": null, "e": 26810, "s": 26807, "text": "C#" }, { "code": null, "e": 26821, "s": 26810, "text": "Javascript" }, { "code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to calculate// factorial of a numberint factorial(int f){ // Base Case if (f == 0 || f == 1) { return 1; } else { // Recursive call return (f * factorial(f - 1)); }} // Function to check if a// number is prime or notbool isPrime(int element){ for (int i = 2; i <= sqrt(element); i++) { if (element % i == 0) { // Not prime return false; } } // Is prime return true;} // Function to count the number// of prime factors of N!int countPrimeFactors(int N){ // Stores factorial of N int fac = factorial(N); // Stores the count of // prime factors int count = 0; // Iterate over the rage [2, fac] for (int i = 2; i <= fac; i++) { // If not prime if (fac % i == 0 && isPrime(i)) { // Increment count count++; } } // Print the count cout << count;} // Driver Codeint main(){ // Given value of N int N = 5; // Function call to count the // number of prime factors of N countPrimeFactors(N); return 0;}", "e": 28002, "s": 26821, "text": null }, { "code": "// Java program for the above approachimport java.util.*; class GFG{ // Function to calculate // factorial of a number static int factorial(int f) { // Base Case if (f == 0 || f == 1) { return 1; } else { // Recursive call return (f * factorial(f - 1)); } } // Function to check if a // number is prime or not static boolean isPrime(int element) { for (int i = 2; i <= (int)Math.sqrt(element); i++) { if (element % i == 0) { // Not prime return false; } } // Is prime return true; } // Function to count the number // of prime factors of N! static void countPrimeFactors(int N) { // Stores factorial of N int fac = factorial(N); // Stores the count of // prime factors int count = 0; // Iterate over the rage [2, fac] for (int i = 2; i <= fac; i++) { // If not prime if ((fac % i == 0 && isPrime(i))) { // Increment count count++; } } // Print the count System.out.println(count); } // Driver Code public static void main(String[] args) { // Given value of N int N = 5; // Function call to count the // number of prime factors of N countPrimeFactors(N); }} // This code is contributed by sanjoy_62.", "e": 29282, "s": 28002, "text": null }, { "code": "# Python program for the above approachfrom math import sqrt # Function to calculate# factorial of a numberdef factorial(f): # Base Case if (f == 0 or f == 1): return 1 else: # Recursive call return (f * factorial(f - 1)) # Function to check if a# number is prime or notdef isPrime(element): for i in range(2,int(sqrt(element))+1): if (element % i == 0): # Not prime return False # Is prime return True # Function to count the number# of prime factors of N!def countPrimeFactors(N): # Stores factorial of N fac = factorial(N) # Stores the count of # prime factors count = 0 # Iterate over the rage [2, fac] for i in range(2, fac + 1): # If not prime if (fac % i == 0 and isPrime(i)): # Increment count count += 1 # Print the count print(count) # Driver Code# Given value of NN = 5 # Function call to count the# number of prime factors of NcountPrimeFactors(N) # This code is contributed by shubhamsingh10", "e": 30409, "s": 29282, "text": null }, { "code": "// C# program for the above approachusing System; class GFG{ // Function to calculate // factorial of a number static int factorial(int f) { // Base Case if (f == 0 || f == 1) { return 1; } else { // Recursive call return (f * factorial(f - 1)); } } // Function to check if a // number is prime or not static bool isPrime(int element) { for (int i = 2; i <= (int)Math.Sqrt(element); i++) { if (element % i == 0) { // Not prime return false; } } // Is prime return true; } // Function to count the number // of prime factors of N! static void countPrimeFactors(int N) { // Stores factorial of N int fac = factorial(N); // Stores the count of // prime factors int count = 0; // Iterate over the range [2, fac] for (int i = 2; i <= fac; i++) { // If not prime if ((fac % i == 0 && isPrime(i))) { // Increment count count++; } } // Print the count Console.Write(count); } // Driver Codepublic static void Main(){ // Given value of N int N = 5; // Function call to count the // number of prime factors of N countPrimeFactors(N);}} // This code is contributed by code_hunt.", "e": 31677, "s": 30409, "text": null }, { "code": "<script>// Javascript program for the above approach // Function to calculate// factorial of a numberfunction factorial(f){ // Base Case if (f == 0 || f == 1){ return 1 } else{ // Recursive call return (f * factorial(f - 1)) } } // Function to check if a// number is prime or notfunction isPrime(element){ for (let i = 2; i < Math.floor(Math.sqrt(element)+1); i++){ if (element % i == 0){ // Not prime return false } } // Is prime return true} // Function to count the number// of prime factors of N!function countPrimeFactors(N){ // Stores factorial of N let fac = factorial(N) // Stores the count of // prime factors let count = 0 // Iterate over the range [2, fac] for(let i = 2; i < fac + 1; i++){ // If not prime if (fac % i == 0 && isPrime(i)){ // Increment count count += 1 } } // Print the count document.write(count)} // Driver Code// Given value of Nlet N = 5 // Function call to count the// number of prime factors of NcountPrimeFactors(N)// This code is contributed by _saurabh_jaiswal</script>", "e": 32910, "s": 31677, "text": null }, { "code": null, "e": 32912, "s": 32910, "text": "3" }, { "code": null, "e": 32968, "s": 32914, "text": "Time Complexity: O(N! * sqrt(N))Auxiliary Space: O(1)" }, { "code": null, "e": 33108, "s": 32968, "text": "Efficient Approach: To optimize the above approach, the idea is to use Sieve Of Eratosthenes. Follow the steps below to solve the problem: " }, { "code": null, "e": 33384, "s": 33108, "text": "Initialize a variable, say count, to store the count of prime factors of N!.Initialize a boolean array, say prime[] to check if a number is prime or not.Perform Sieve of Eratosthenes and populate count at each iteration, if found prime.Print the value of count as the answer." }, { "code": null, "e": 33461, "s": 33384, "text": "Initialize a variable, say count, to store the count of prime factors of N!." }, { "code": null, "e": 33539, "s": 33461, "text": "Initialize a boolean array, say prime[] to check if a number is prime or not." }, { "code": null, "e": 33623, "s": 33539, "text": "Perform Sieve of Eratosthenes and populate count at each iteration, if found prime." }, { "code": null, "e": 33663, "s": 33623, "text": "Print the value of count as the answer." }, { "code": null, "e": 33715, "s": 33663, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 33719, "s": 33715, "text": "C++" }, { "code": null, "e": 33724, "s": 33719, "text": "Java" }, { "code": null, "e": 33732, "s": 33724, "text": "Python3" }, { "code": null, "e": 33735, "s": 33732, "text": "C#" }, { "code": null, "e": 33746, "s": 33735, "text": "Javascript" }, { "code": "// C++ approach for the above approach #include <bits/stdc++.h>using namespace std; // Function to count the// prime factors of N!int countPrimeFactors(int N){ // Stores the count of // prime factors int count = 0; // Stores whether a number // is prime or not bool prime[N + 1]; // Mark all as true initially memset(prime, true, sizeof(prime)); // Sieve of Eratosthenes for (int p = 2; p * p <= N; p++) { // If prime[p] is not changed, // then it is a prime if (prime[p] == true) { // Update all subsequent multiples for (int i = p * p; i <= N; i += p) prime[i] = false; } } // Traverse in the range [2, N] for (int p = 2; p <= N; p++) { // If prime if (prime[p]) { // Increment the count count++; } } // Print the count cout << count;} // Driver Codeint main(){ // Given value of N int N = 5; // Function call to count // the prime factors of N! countPrimeFactors(N); return 0;}", "e": 34813, "s": 33746, "text": null }, { "code": "// Java program for the above approachimport java.io.*;import java.util.*;class GFG{ // Function to count the // prime factors of N! static void countPrimeFactors(int N) { // Stores the count of // prime factors int count = 0; // Stores whether a number // is prime or not boolean[] prime = new boolean[N + 1]; // Mark all as true initially Arrays.fill(prime, true); // Sieve of Eratosthenes for (int p = 2; p * p <= N; p++) { // If prime[p] is not changed, // then it is a prime if (prime[p] == true) { // Update all subsequent multiples for (int i = p * p; i <= N; i += p) prime[i] = false; } } // Traverse in the range [2, N] for (int p = 2; p <= N; p++) { // If prime if (prime[p] != false) { // Increment the count count++; } } // Print the count System.out.print(count); } // Driver Code public static void main(String[] args) { // Given value of N int N = 5; // Function call to count // the prime factors of N! countPrimeFactors(N); }} // This code is contributed by susmitakundugoaldanga.", "e": 35978, "s": 34813, "text": null }, { "code": "# Python3 approach for the above approach # Function to count the# prime factors of N!def countPrimeFactors(N): # Stores the count of # prime factors count = 0 # Stores whether a number # is prime or not prime = [1] * (N + 1) # Sieve of Eratosthenes for p in range(2, N + 1): if p * p > N: break # If prime[p] is not changed, # then it is a prime if (prime[p]): # Update all subsequent multiples for i in range(p * p, N + 1, p): prime[i] = 0 # Traverse in the range [2, N] for p in range(2, N + 1): # If prime if (prime[p]): # Increment the count count += 1 # Print the count print (count) # Driver Codeif __name__ == '__main__': # Given value of N N = 5 # Function call to count # the prime factors of N! countPrimeFactors(N) # This code is contributed by mohit kumar 29", "e": 36949, "s": 35978, "text": null }, { "code": "// C# program for the above approachusing System;public class GFG{ // Function to count the // prime factors of N! static void countPrimeFactors(int N) { // Stores the count of // prime factors int count = 0; // Stores whether a number // is prime or not bool[] prime = new bool[N + 1]; // Mark all as true initially for (int i = 0; i < prime.Length; i++) prime[i] = true; // Sieve of Eratosthenes for (int p = 2; p * p <= N; p++) { // If prime[p] is not changed, // then it is a prime if (prime[p] == true) { // Update all subsequent multiples for (int i = p * p; i <= N; i += p) prime[i] = false; } } // Traverse in the range [2, N] for (int p = 2; p <= N; p++) { // If prime if (prime[p] != false) { // Increment the count count++; } } // Print the count Console.Write(count); } // Driver Code public static void Main(String[] args) { // Given value of N int N = 5; // Function call to count // the prime factors of N! countPrimeFactors(N); }} // This code is contributed by shikhasingrajput", "e": 38118, "s": 36949, "text": null }, { "code": "<script> // JavaScript program for the above approach // Function to count the // prime factors of N! function countPrimeFactors( N) { // Stores the count of // prime factors var count = 0; // Stores whether a number // is prime or not var prime = Array(N + 1).fill(true); // Sieve of Eratosthenes for (var p = 2; p * p <= N; p++) { // If prime[p] is not changed, // then it is a prime if (prime[p] == true) { // Update all subsequent multiples for (var i = p * p; i <= N; i += p) prime[i] = false; } } // Traverse in the range [2, N] for (var p = 2; p <= N; p++) { // If prime if (prime[p] != false) { // Increment the count count++; } } // Print the count document.write(count); } // Driver Code // Given value of N var N = 5; // Function call to count // the prime factors of N! countPrimeFactors(N); // This code is contributed by Amit Katiyar </script>", "e": 39305, "s": 38118, "text": null }, { "code": null, "e": 39307, "s": 39305, "text": "3" }, { "code": null, "e": 39364, "s": 39309, "text": "Time Complexity: O(N * log(logN))Auxiliary Space: O(N)" }, { "code": null, "e": 39376, "s": 39366, "text": "sanjoy_62" }, { "code": null, "e": 39386, "s": 39376, "text": "code_hunt" }, { "code": null, "e": 39401, "s": 39386, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 39423, "s": 39401, "text": "susmitakundugoaldanga" }, { "code": null, "e": 39440, "s": 39423, "text": "shikhasingrajput" }, { "code": null, "e": 39457, "s": 39440, "text": "_saurabh_jaiswal" }, { "code": null, "e": 39472, "s": 39457, "text": "amit143katiyar" }, { "code": null, "e": 39487, "s": 39472, "text": "mohit kumar 29" }, { "code": null, "e": 39500, "s": 39487, "text": "Kirti_Mangal" }, { "code": null, "e": 39510, "s": 39500, "text": "factorial" }, { "code": null, "e": 39523, "s": 39510, "text": "prime-factor" }, { "code": null, "e": 39529, "s": 39523, "text": "sieve" }, { "code": null, "e": 39542, "s": 39529, "text": "Mathematical" }, { "code": null, "e": 39552, "s": 39542, "text": "Recursion" }, { "code": null, "e": 39565, "s": 39552, "text": "Mathematical" }, { "code": null, "e": 39575, "s": 39565, "text": "Recursion" }, { "code": null, "e": 39581, "s": 39575, "text": "sieve" }, { "code": null, "e": 39591, "s": 39581, "text": "factorial" }, { "code": null, "e": 39689, "s": 39591, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 39733, "s": 39689, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 39775, "s": 39733, "text": "Segment Tree | Set 1 (Sum of given range)" }, { "code": null, "e": 39806, "s": 39775, "text": "Modular multiplicative inverse" }, { "code": null, "e": 39877, "s": 39806, "text": "Count all possible paths from top left to bottom right of a mXn matrix" }, { "code": null, "e": 39902, "s": 39877, "text": "Fizz Buzz Implementation" }, { "code": null, "e": 39987, "s": 39902, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 39997, "s": 39987, "text": "Recursion" }, { "code": null, "e": 40024, "s": 39997, "text": "Program for Tower of Hanoi" }, { "code": null, "e": 40052, "s": 40024, "text": "Backtracking | Introduction" } ]
Implementation of Perceptron Algorithm for AND Logic Gate with 2-bit Binary Input - GeeksforGeeks
08 Jun, 2020 In the field of Machine Learning, the Perceptron is a Supervised Learning Algorithm for binary classifiers. The Perceptron Model implements the following function: For a particular choice of the weight vector and bias parameter , the model predicts output for the corresponding input vector . AND logical function truth table for 2-bit binary variables, i.e, the input vector and the corresponding output – Now for the corresponding weight vector of the input vector , the associated Perceptron Function can be defined as: For the implementation, considered weight parameters are and the bias parameter is . Python Implementation: # importing Python libraryimport numpy as np # define Unit Step Functiondef unitStep(v): if v >= 0: return 1 else: return 0 # design Perceptron Modeldef perceptronModel(x, w, b): v = np.dot(w, x) + b y = unitStep(v) return y # AND Logic Function# w1 = 1, w2 = 1, b = -1.5def AND_logicFunction(x): w = np.array([1, 1]) b = -1.5 return perceptronModel(x, w, b) # testing the Perceptron Modeltest1 = np.array([0, 1])test2 = np.array([1, 1])test3 = np.array([0, 0])test4 = np.array([1, 0]) print("AND({}, {}) = {}".format(0, 1, AND_logicFunction(test1)))print("AND({}, {}) = {}".format(1, 1, AND_logicFunction(test2)))print("AND({}, {}) = {}".format(0, 0, AND_logicFunction(test3)))print("AND({}, {}) = {}".format(1, 0, AND_logicFunction(test4))) AND(0, 1) = 0 AND(1, 1) = 1 AND(0, 0) = 0 AND(1, 0) = 0 Here, the model predicted output () for each of the test inputs are exactly matched with the AND logic gate conventional output () according to the truth table for 2-bit binary input.Hence, it is verified that the perceptron algorithm for AND logic gate is correctly implemented. Neural Network Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ML | Linear Regression Reinforcement learning Decision Tree Decision Tree Introduction with example Support Vector Machine Algorithm 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": 26839, "s": 26811, "text": "\n08 Jun, 2020" }, { "code": null, "e": 27003, "s": 26839, "text": "In the field of Machine Learning, the Perceptron is a Supervised Learning Algorithm for binary classifiers. The Perceptron Model implements the following function:" }, { "code": null, "e": 27139, "s": 27008, "text": "For a particular choice of the weight vector and bias parameter , the model predicts output for the corresponding input vector ." }, { "code": null, "e": 27255, "s": 27139, "text": "AND logical function truth table for 2-bit binary variables, i.e, the input vector and the corresponding output –" }, { "code": null, "e": 27372, "s": 27255, "text": "Now for the corresponding weight vector of the input vector , the associated Perceptron Function can be defined as:" }, { "code": null, "e": 27463, "s": 27377, "text": "For the implementation, considered weight parameters are and the bias parameter is ." }, { "code": null, "e": 27486, "s": 27463, "text": "Python Implementation:" }, { "code": "# importing Python libraryimport numpy as np # define Unit Step Functiondef unitStep(v): if v >= 0: return 1 else: return 0 # design Perceptron Modeldef perceptronModel(x, w, b): v = np.dot(w, x) + b y = unitStep(v) return y # AND Logic Function# w1 = 1, w2 = 1, b = -1.5def AND_logicFunction(x): w = np.array([1, 1]) b = -1.5 return perceptronModel(x, w, b) # testing the Perceptron Modeltest1 = np.array([0, 1])test2 = np.array([1, 1])test3 = np.array([0, 0])test4 = np.array([1, 0]) print(\"AND({}, {}) = {}\".format(0, 1, AND_logicFunction(test1)))print(\"AND({}, {}) = {}\".format(1, 1, AND_logicFunction(test2)))print(\"AND({}, {}) = {}\".format(0, 0, AND_logicFunction(test3)))print(\"AND({}, {}) = {}\".format(1, 0, AND_logicFunction(test4)))", "e": 28272, "s": 27486, "text": null }, { "code": null, "e": 28329, "s": 28272, "text": "AND(0, 1) = 0\nAND(1, 1) = 1\nAND(0, 0) = 0\nAND(1, 0) = 0\n" }, { "code": null, "e": 28609, "s": 28329, "text": "Here, the model predicted output () for each of the test inputs are exactly matched with the AND logic gate conventional output () according to the truth table for 2-bit binary input.Hence, it is verified that the perceptron algorithm for AND logic gate is correctly implemented." }, { "code": null, "e": 28624, "s": 28609, "text": "Neural Network" }, { "code": null, "e": 28641, "s": 28624, "text": "Machine Learning" }, { "code": null, "e": 28648, "s": 28641, "text": "Python" }, { "code": null, "e": 28665, "s": 28648, "text": "Machine Learning" }, { "code": null, "e": 28763, "s": 28665, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28786, "s": 28763, "text": "ML | Linear Regression" }, { "code": null, "e": 28809, "s": 28786, "text": "Reinforcement learning" }, { "code": null, "e": 28823, "s": 28809, "text": "Decision Tree" }, { "code": null, "e": 28863, "s": 28823, "text": "Decision Tree Introduction with example" }, { "code": null, "e": 28896, "s": 28863, "text": "Support Vector Machine Algorithm" }, { "code": null, "e": 28924, "s": 28896, "text": "Read JSON file using Python" }, { "code": null, "e": 28974, "s": 28924, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 28996, "s": 28974, "text": "Python map() function" } ]
Command Line Arguments in Python - GeeksforGeeks
12 Apr, 2022 The arguments that are given after the name of the program in the command line shell of the operating system are known as Command Line Arguments. Python provides various ways of dealing with these types of arguments. The three most common are: Using sys.argv Using getopt module Using argparse module The sys module provides functions and variables used to manipulate different parts of the Python runtime environment. This module provides access to some variables used or maintained by the interpreter and to functions that interact strongly with the interpreter.One such variable is sys.argv which is a simple list structure. It’s main purpose are: It is a list of command line arguments. len(sys.argv) provides the number of command line arguments. sys.argv[0] is the name of the current Python script. Example: Let’s suppose there is a Python script for adding two numbers and the numbers are passed as command-line arguments. Python3 # Python program to demonstrate# command line arguments import sys # total argumentsn = len(sys.argv)print("Total arguments passed:", n) # Arguments passedprint("\nName of Python script:", sys.argv[0]) print("\nArguments passed:", end = " ")for i in range(1, n): print(sys.argv[i], end = " ") # Addition of numbersSum = 0# Using argparse modulefor i in range(1, n): Sum += int(sys.argv[i]) print("\n\nResult:", Sum) Output: Python getopt module is similar to the getopt() function of C. Unlike sys module getopt module extends the separation of the input string by parameter validation. It allows both short, and long options including a value assignment. However, this module requires the use of the sys module to process input data properly. To use getopt module, it is required to remove the first element from the list of command-line arguments. Syntax: getopt.getopt(args, options, [long_options])Parameters: args: List of arguments to be passed. options: String of option letters that the script want to recognize. Options that require an argument should be followed by a colon (:). long_options: List of string with the name of long options. Options that require arguments should be followed by an equal sign (=).Return Type: Returns value consisting of two elements: the first is a list of (option, value) pairs. The second is the list of program arguments left after the option list was stripped. Example: Python3 # Python program to demonstrate# command line arguments import getopt, sys # Remove 1st argument from the# list of command line argumentsargumentList = sys.argv[1:] # Optionsoptions = "hmo:" # Long optionslong_options = ["Help", "My_file", "Output="] try: # Parsing argument arguments, values = getopt.getopt(argumentList, options, long_options) # checking each argument for currentArgument, currentValue in arguments: if currentArgument in ("-h", "--Help"): print ("Displaying Help") elif currentArgument in ("-m", "--My_file"): print ("Displaying file_name:", sys.argv[0]) elif currentArgument in ("-o", "--Output"): print (("Enabling special output mode (% s)") % (currentValue)) except getopt.error as err: # output error, and return with an error code print (str(err)) Output: Using argparse module is a better option than the above two options as it provides a lot of options such as positional arguments, default value for arguments, help message, specifying data type of argument etc. Note: As a default optional argument, it includes -h, along with its long version –help. Example 1: Basic use of argparse module. Python3 # Python program to demonstrate# command line arguments import argparse # Initialize parserparser = argparse.ArgumentParser()parser.parse_args() Output: Example 2: Adding description to the help message. Python3 # Python program to demonstrate# command line arguments import argparse msg = "Adding description" # Initialize parserparser = argparse.ArgumentParser(description = msg)parser.parse_args() Output: Example 3: Defining optional value Python3 # Python program to demonstrate# command line arguments import argparse # Initialize parserparser = argparse.ArgumentParser() # Adding optional argumentparser.add_argument("-o", "--Output", help = "Show Output") # Read arguments from command lineargs = parser.parse_args() if args.Output: print("Displaying Output as: % s" % args.Output) Output: zaedansari6 as5853535 adnanirshad158 realista95 python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Python String | replace() Create a Pandas DataFrame from Lists Convert integer to string in Python Check if element exists in list in Python How To Convert Python Dictionary To JSON? sum() function in Python isupper(), islower(), lower(), upper() in Python and their applications
[ { "code": null, "e": 25457, "s": 25429, "text": "\n12 Apr, 2022" }, { "code": null, "e": 25702, "s": 25457, "text": "The arguments that are given after the name of the program in the command line shell of the operating system are known as Command Line Arguments. Python provides various ways of dealing with these types of arguments. The three most common are: " }, { "code": null, "e": 25717, "s": 25702, "text": "Using sys.argv" }, { "code": null, "e": 25737, "s": 25717, "text": "Using getopt module" }, { "code": null, "e": 25759, "s": 25737, "text": "Using argparse module" }, { "code": null, "e": 26109, "s": 25759, "text": "The sys module provides functions and variables used to manipulate different parts of the Python runtime environment. This module provides access to some variables used or maintained by the interpreter and to functions that interact strongly with the interpreter.One such variable is sys.argv which is a simple list structure. It’s main purpose are:" }, { "code": null, "e": 26149, "s": 26109, "text": "It is a list of command line arguments." }, { "code": null, "e": 26210, "s": 26149, "text": "len(sys.argv) provides the number of command line arguments." }, { "code": null, "e": 26266, "s": 26210, "text": "sys.argv[0] is the name of the current Python script. " }, { "code": null, "e": 26392, "s": 26266, "text": "Example: Let’s suppose there is a Python script for adding two numbers and the numbers are passed as command-line arguments. " }, { "code": null, "e": 26400, "s": 26392, "text": "Python3" }, { "code": "# Python program to demonstrate# command line arguments import sys # total argumentsn = len(sys.argv)print(\"Total arguments passed:\", n) # Arguments passedprint(\"\\nName of Python script:\", sys.argv[0]) print(\"\\nArguments passed:\", end = \" \")for i in range(1, n): print(sys.argv[i], end = \" \") # Addition of numbersSum = 0# Using argparse modulefor i in range(1, n): Sum += int(sys.argv[i]) print(\"\\n\\nResult:\", Sum)", "e": 26831, "s": 26400, "text": null }, { "code": null, "e": 26840, "s": 26831, "text": "Output: " }, { "code": null, "e": 27270, "s": 26842, "text": "Python getopt module is similar to the getopt() function of C. Unlike sys module getopt module extends the separation of the input string by parameter validation. It allows both short, and long options including a value assignment. However, this module requires the use of the sys module to process input data properly. To use getopt module, it is required to remove the first element from the list of command-line arguments. " }, { "code": null, "e": 27828, "s": 27270, "text": "Syntax: getopt.getopt(args, options, [long_options])Parameters: args: List of arguments to be passed. options: String of option letters that the script want to recognize. Options that require an argument should be followed by a colon (:). long_options: List of string with the name of long options. Options that require arguments should be followed by an equal sign (=).Return Type: Returns value consisting of two elements: the first is a list of (option, value) pairs. The second is the list of program arguments left after the option list was stripped. " }, { "code": null, "e": 27837, "s": 27828, "text": "Example:" }, { "code": null, "e": 27845, "s": 27837, "text": "Python3" }, { "code": "# Python program to demonstrate# command line arguments import getopt, sys # Remove 1st argument from the# list of command line argumentsargumentList = sys.argv[1:] # Optionsoptions = \"hmo:\" # Long optionslong_options = [\"Help\", \"My_file\", \"Output=\"] try: # Parsing argument arguments, values = getopt.getopt(argumentList, options, long_options) # checking each argument for currentArgument, currentValue in arguments: if currentArgument in (\"-h\", \"--Help\"): print (\"Displaying Help\") elif currentArgument in (\"-m\", \"--My_file\"): print (\"Displaying file_name:\", sys.argv[0]) elif currentArgument in (\"-o\", \"--Output\"): print ((\"Enabling special output mode (% s)\") % (currentValue)) except getopt.error as err: # output error, and return with an error code print (str(err))", "e": 28737, "s": 27845, "text": null }, { "code": null, "e": 28746, "s": 28737, "text": "Output: " }, { "code": null, "e": 28961, "s": 28748, "text": "Using argparse module is a better option than the above two options as it provides a lot of options such as positional arguments, default value for arguments, help message, specifying data type of argument etc. " }, { "code": null, "e": 29051, "s": 28961, "text": "Note: As a default optional argument, it includes -h, along with its long version –help. " }, { "code": null, "e": 29093, "s": 29051, "text": "Example 1: Basic use of argparse module. " }, { "code": null, "e": 29101, "s": 29093, "text": "Python3" }, { "code": "# Python program to demonstrate# command line arguments import argparse # Initialize parserparser = argparse.ArgumentParser()parser.parse_args()", "e": 29247, "s": 29101, "text": null }, { "code": null, "e": 29256, "s": 29247, "text": "Output: " }, { "code": null, "e": 29310, "s": 29256, "text": " Example 2: Adding description to the help message. " }, { "code": null, "e": 29318, "s": 29310, "text": "Python3" }, { "code": "# Python program to demonstrate# command line arguments import argparse msg = \"Adding description\" # Initialize parserparser = argparse.ArgumentParser(description = msg)parser.parse_args()", "e": 29508, "s": 29318, "text": null }, { "code": null, "e": 29517, "s": 29508, "text": "Output: " }, { "code": null, "e": 29555, "s": 29517, "text": " Example 3: Defining optional value " }, { "code": null, "e": 29563, "s": 29555, "text": "Python3" }, { "code": "# Python program to demonstrate# command line arguments import argparse # Initialize parserparser = argparse.ArgumentParser() # Adding optional argumentparser.add_argument(\"-o\", \"--Output\", help = \"Show Output\") # Read arguments from command lineargs = parser.parse_args() if args.Output: print(\"Displaying Output as: % s\" % args.Output)", "e": 29906, "s": 29563, "text": null }, { "code": null, "e": 29915, "s": 29906, "text": "Output: " }, { "code": null, "e": 29929, "s": 29917, "text": "zaedansari6" }, { "code": null, "e": 29939, "s": 29929, "text": "as5853535" }, { "code": null, "e": 29954, "s": 29939, "text": "adnanirshad158" }, { "code": null, "e": 29965, "s": 29954, "text": "realista95" }, { "code": null, "e": 29980, "s": 29965, "text": "python-utility" }, { "code": null, "e": 29987, "s": 29980, "text": "Python" }, { "code": null, "e": 30085, "s": 29987, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30117, "s": 30085, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 30139, "s": 30117, "text": "Enumerate() in Python" }, { "code": null, "e": 30181, "s": 30139, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 30207, "s": 30181, "text": "Python String | replace()" }, { "code": null, "e": 30244, "s": 30207, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 30280, "s": 30244, "text": "Convert integer to string in Python" }, { "code": null, "e": 30322, "s": 30280, "text": "Check if element exists in list in Python" }, { "code": null, "e": 30364, "s": 30322, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 30389, "s": 30364, "text": "sum() function in Python" } ]
Count of subarrays whose maximum element is greater than k - GeeksforGeeks
03 Feb, 2022 Given an array of n elements and an integer k. The task is to find the count of subarray which has maximum element greater than K.Examples : Input : arr[] = {1, 2, 3} and k = 2. Output : 3 All the possible subarrays of arr[] are { 1 }, { 2 }, { 3 }, { 1, 2 }, { 2, 3 }, { 1, 2, 3 }. Their maximum elements are 1, 2, 3, 2, 3, 3. There are only 3 maximum elements > 2. The idea is to approach problem by counting subarrays whose maximum element is less than or equal to k as counting such subarrays is easier. To find the number of subarray whose maximum element is less than or equal to k, remove all the element which is greater than K and find the number of subarray with the left elements. Once we find above count, we can subtract it from n*(n+1)/2 to get our required result. Observe, there can be n*(n+1)/2 possible number of subarray of any array of size n. So, finding the number of subarray whose maximum element is less than or equal to K and subtracting it from n*(n+1)/2 gets us the answer.Below is the implementation of this approach: C++ Java Python3 C# PHP Javascript // C++ program to count number of subarrays// whose maximum element is greater than K.#include <bits/stdc++.h>using namespace std; // Return number of subarrays whose maximum// element is less than or equal to K.int countSubarray(int arr[], int n, int k){ // To store count of subarrays with all // elements less than or equal to k. int s = 0; // Traversing the array. int i = 0; while (i < n) { // If element is greater than k, ignore. if (arr[i] > k) { i++; continue; } // Counting the subarray length whose // each element is less than equal to k. int count = 0; while (i < n && arr[i] <= k) { i++; count++; } // Summing number of subarray whose // maximum element is less than equal to k. s += ((count * (count + 1)) / 2); } return (n * (n + 1) / 2 - s);} // Driven Programint main(){ int arr[] = { 1, 2, 3 }; int k = 2; int n = sizeof(arr) / sizeof(arr[0]); cout << countSubarray(arr, n, k); return 0;} // Java program to count number of subarrays// whose maximum element is greater than K.import java.util.*; class GFG { // Return number of subarrays whose maximum // element is less than or equal to K. static int countSubarray(int arr[], int n, int k) { // To store count of subarrays with all // elements less than or equal to k. int s = 0; // Traversing the array. int i = 0; while (i < n) { // If element is greater than k, ignore. if (arr[i] > k) { i++; continue; } // Counting the subarray length whose // each element is less than equal to k. int count = 0; while (i < n && arr[i] <= k) { i++; count++; } // Summing number of subarray whose // maximum element is less than equal to k. s += ((count * (count + 1)) / 2); } return (n * (n + 1) / 2 - s); } // Driver code public static void main(String[] args) { int arr[] = { 1, 2, 3 }; int k = 2; int n = arr.length; System.out.print(countSubarray(arr, n, k)); }} // This code is contributed by Anant Agarwal. # Python program to count# number of subarrays# whose maximum element# is greater than K. # Return number of# subarrays whose maximum# element is less than or equal to K.def countSubarray(arr, n, k): # To store count of # subarrays with all # elements less than # or equal to k. s = 0 # Traversing the array. i = 0 while (i < n): # If element is greater # than k, ignore. if (arr[i] > k): i = i + 1 continue # Counting the subarray # length whose # each element is less # than equal to k. count = 0 while (i < n and arr[i] <= k): i = i + 1 count = count + 1 # Summing number of subarray whose # maximum element is less # than equal to k. s = s + ((count*(count + 1))//2) return (n*(n + 1)//2 - s) # Driver code arr = [1, 2, 3]k = 2n = len(arr) print(countSubarray(arr, n, k)) # This code is contributed# by Anant Agarwal. // C# program to count number of subarrays// whose maximum element is greater than K.using System; class GFG { // Return number of subarrays whose maximum // element is less than or equal to K. static int countSubarray(int[] arr, int n, int k) { // To store count of subarrays with all // elements less than or equal to k. int s = 0; // Traversing the array. int i = 0; while (i < n) { // If element is greater than k, ignore. if (arr[i] > k) { i++; continue; } // Counting the subarray length whose // each element is less than equal to k. int count = 0; while (i < n && arr[i] <= k) { i++; count++; } // Summing number of subarray whose // maximum element is less than equal to k. s += ((count * (count + 1)) / 2); } return (n * (n + 1) / 2 - s); } // Driver code public static void Main() { int[] arr = {1, 2, 3}; int k = 2; int n = arr.Length; Console.WriteLine(countSubarray(arr, n, k)); }} // This code is contributed by vt_m. <?php// PHP program to count number of subarrays// whose maximum element is greater than K. // Return number of subarrays whose maximum// element is less than or equal to K.function countSubarray( $arr, $n, $k){ // To store count of subarrays with all // elements less than or equal to k. $s = 0; // Traversing the array. $i = 0; while ($i < $n) { // If element is greater than k, // ignore. if ($arr[$i] > $k) { $i++; continue; } // Counting the subarray length // whose each element is less // than equal to k. $count = 0; while ($i < $n and $arr[$i] <= $k) { $i++; $count++; } // Summing number of subarray whose // maximum element is less than // equal to k. $s += (($count * ($count + 1)) / 2); } return ($n * ($n + 1) / 2 - $s);} // Driven Program $arr = array( 1, 2, 3 ); $k = 2; $n = count($arr); echo countSubarray($arr, $n, $k); // This code is contributed by anuj_67.?> <script> // Javascript program to count number of subarrays // whose maximum element is greater than K. // Return number of subarrays whose maximum // element is less than or equal to K. function countSubarray(arr, n, k) { // To store count of subarrays with all // elements less than or equal to k. let s = 0; // Traversing the array. let i = 0; while (i < n) { // If element is greater than k, ignore. if (arr[i] > k) { i++; continue; } // Counting the subarray length whose // each element is less than equal to k. let count = 0; while (i < n && arr[i] <= k) { i++; count++; } // Summing number of subarray whose // maximum element is less than equal to k. s += parseInt((count * (count + 1)) / 2, 10); } return (n * parseInt((n + 1) / 2, 10) - s); } let arr = [1, 2, 3]; let k = 2; let n = arr.length; document.write(countSubarray(arr, n, k)); </script> Output: 3 Time Complexity: O(n).This article is contributed by Anuj Chauhan. 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 decode2207 adnanirshad158 sweetyty Arrays Dynamic Programming Arrays Dynamic Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Introduction to Arrays Multidimensional Arrays in Java Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Linked List vs Array Python | Using 2D arrays/lists the right way 0-1 Knapsack Problem | DP-10 Program for Fibonacci numbers Longest Common Subsequence | DP-4 Longest Increasing Subsequence | DP-3 Bellman–Ford Algorithm | DP-23
[ { "code": null, "e": 24877, "s": 24849, "text": "\n03 Feb, 2022" }, { "code": null, "e": 25020, "s": 24877, "text": "Given an array of n elements and an integer k. The task is to find the count of subarray which has maximum element greater than K.Examples : " }, { "code": null, "e": 25248, "s": 25020, "text": "Input : arr[] = {1, 2, 3} and k = 2.\nOutput : 3\nAll the possible subarrays of arr[] are \n{ 1 }, { 2 }, { 3 }, { 1, 2 }, { 2, 3 }, \n{ 1, 2, 3 }.\nTheir maximum elements are 1, 2, 3, 2, 3, 3.\nThere are only 3 maximum elements > 2." }, { "code": null, "e": 25932, "s": 25250, "text": "The idea is to approach problem by counting subarrays whose maximum element is less than or equal to k as counting such subarrays is easier. To find the number of subarray whose maximum element is less than or equal to k, remove all the element which is greater than K and find the number of subarray with the left elements. Once we find above count, we can subtract it from n*(n+1)/2 to get our required result. Observe, there can be n*(n+1)/2 possible number of subarray of any array of size n. So, finding the number of subarray whose maximum element is less than or equal to K and subtracting it from n*(n+1)/2 gets us the answer.Below is the implementation of this approach: " }, { "code": null, "e": 25936, "s": 25932, "text": "C++" }, { "code": null, "e": 25941, "s": 25936, "text": "Java" }, { "code": null, "e": 25949, "s": 25941, "text": "Python3" }, { "code": null, "e": 25952, "s": 25949, "text": "C#" }, { "code": null, "e": 25956, "s": 25952, "text": "PHP" }, { "code": null, "e": 25967, "s": 25956, "text": "Javascript" }, { "code": "// C++ program to count number of subarrays// whose maximum element is greater than K.#include <bits/stdc++.h>using namespace std; // Return number of subarrays whose maximum// element is less than or equal to K.int countSubarray(int arr[], int n, int k){ // To store count of subarrays with all // elements less than or equal to k. int s = 0; // Traversing the array. int i = 0; while (i < n) { // If element is greater than k, ignore. if (arr[i] > k) { i++; continue; } // Counting the subarray length whose // each element is less than equal to k. int count = 0; while (i < n && arr[i] <= k) { i++; count++; } // Summing number of subarray whose // maximum element is less than equal to k. s += ((count * (count + 1)) / 2); } return (n * (n + 1) / 2 - s);} // Driven Programint main(){ int arr[] = { 1, 2, 3 }; int k = 2; int n = sizeof(arr) / sizeof(arr[0]); cout << countSubarray(arr, n, k); return 0;}", "e": 27039, "s": 25967, "text": null }, { "code": "// Java program to count number of subarrays// whose maximum element is greater than K.import java.util.*; class GFG { // Return number of subarrays whose maximum // element is less than or equal to K. static int countSubarray(int arr[], int n, int k) { // To store count of subarrays with all // elements less than or equal to k. int s = 0; // Traversing the array. int i = 0; while (i < n) { // If element is greater than k, ignore. if (arr[i] > k) { i++; continue; } // Counting the subarray length whose // each element is less than equal to k. int count = 0; while (i < n && arr[i] <= k) { i++; count++; } // Summing number of subarray whose // maximum element is less than equal to k. s += ((count * (count + 1)) / 2); } return (n * (n + 1) / 2 - s); } // Driver code public static void main(String[] args) { int arr[] = { 1, 2, 3 }; int k = 2; int n = arr.length; System.out.print(countSubarray(arr, n, k)); }} // This code is contributed by Anant Agarwal.", "e": 28304, "s": 27039, "text": null }, { "code": "# Python program to count# number of subarrays# whose maximum element# is greater than K. # Return number of# subarrays whose maximum# element is less than or equal to K.def countSubarray(arr, n, k): # To store count of # subarrays with all # elements less than # or equal to k. s = 0 # Traversing the array. i = 0 while (i < n): # If element is greater # than k, ignore. if (arr[i] > k): i = i + 1 continue # Counting the subarray # length whose # each element is less # than equal to k. count = 0 while (i < n and arr[i] <= k): i = i + 1 count = count + 1 # Summing number of subarray whose # maximum element is less # than equal to k. s = s + ((count*(count + 1))//2) return (n*(n + 1)//2 - s) # Driver code arr = [1, 2, 3]k = 2n = len(arr) print(countSubarray(arr, n, k)) # This code is contributed# by Anant Agarwal.", "e": 29345, "s": 28304, "text": null }, { "code": "// C# program to count number of subarrays// whose maximum element is greater than K.using System; class GFG { // Return number of subarrays whose maximum // element is less than or equal to K. static int countSubarray(int[] arr, int n, int k) { // To store count of subarrays with all // elements less than or equal to k. int s = 0; // Traversing the array. int i = 0; while (i < n) { // If element is greater than k, ignore. if (arr[i] > k) { i++; continue; } // Counting the subarray length whose // each element is less than equal to k. int count = 0; while (i < n && arr[i] <= k) { i++; count++; } // Summing number of subarray whose // maximum element is less than equal to k. s += ((count * (count + 1)) / 2); } return (n * (n + 1) / 2 - s); } // Driver code public static void Main() { int[] arr = {1, 2, 3}; int k = 2; int n = arr.Length; Console.WriteLine(countSubarray(arr, n, k)); }} // This code is contributed by vt_m.", "e": 30577, "s": 29345, "text": null }, { "code": "<?php// PHP program to count number of subarrays// whose maximum element is greater than K. // Return number of subarrays whose maximum// element is less than or equal to K.function countSubarray( $arr, $n, $k){ // To store count of subarrays with all // elements less than or equal to k. $s = 0; // Traversing the array. $i = 0; while ($i < $n) { // If element is greater than k, // ignore. if ($arr[$i] > $k) { $i++; continue; } // Counting the subarray length // whose each element is less // than equal to k. $count = 0; while ($i < $n and $arr[$i] <= $k) { $i++; $count++; } // Summing number of subarray whose // maximum element is less than // equal to k. $s += (($count * ($count + 1)) / 2); } return ($n * ($n + 1) / 2 - $s);} // Driven Program $arr = array( 1, 2, 3 ); $k = 2; $n = count($arr); echo countSubarray($arr, $n, $k); // This code is contributed by anuj_67.?>", "e": 31654, "s": 30577, "text": null }, { "code": "<script> // Javascript program to count number of subarrays // whose maximum element is greater than K. // Return number of subarrays whose maximum // element is less than or equal to K. function countSubarray(arr, n, k) { // To store count of subarrays with all // elements less than or equal to k. let s = 0; // Traversing the array. let i = 0; while (i < n) { // If element is greater than k, ignore. if (arr[i] > k) { i++; continue; } // Counting the subarray length whose // each element is less than equal to k. let count = 0; while (i < n && arr[i] <= k) { i++; count++; } // Summing number of subarray whose // maximum element is less than equal to k. s += parseInt((count * (count + 1)) / 2, 10); } return (n * parseInt((n + 1) / 2, 10) - s); } let arr = [1, 2, 3]; let k = 2; let n = arr.length; document.write(countSubarray(arr, n, k)); </script>", "e": 32811, "s": 31654, "text": null }, { "code": null, "e": 32821, "s": 32811, "text": "Output: " }, { "code": null, "e": 32823, "s": 32821, "text": "3" }, { "code": null, "e": 33266, "s": 32823, "text": "Time Complexity: O(n).This article is contributed by Anuj Chauhan. 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": 33271, "s": 33266, "text": "vt_m" }, { "code": null, "e": 33282, "s": 33271, "text": "decode2207" }, { "code": null, "e": 33297, "s": 33282, "text": "adnanirshad158" }, { "code": null, "e": 33306, "s": 33297, "text": "sweetyty" }, { "code": null, "e": 33313, "s": 33306, "text": "Arrays" }, { "code": null, "e": 33333, "s": 33313, "text": "Dynamic Programming" }, { "code": null, "e": 33340, "s": 33333, "text": "Arrays" }, { "code": null, "e": 33360, "s": 33340, "text": "Dynamic Programming" }, { "code": null, "e": 33458, "s": 33360, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33467, "s": 33458, "text": "Comments" }, { "code": null, "e": 33480, "s": 33467, "text": "Old Comments" }, { "code": null, "e": 33503, "s": 33480, "text": "Introduction to Arrays" }, { "code": null, "e": 33535, "s": 33503, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 33620, "s": 33535, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 33641, "s": 33620, "text": "Linked List vs Array" }, { "code": null, "e": 33686, "s": 33641, "text": "Python | Using 2D arrays/lists the right way" }, { "code": null, "e": 33715, "s": 33686, "text": "0-1 Knapsack Problem | DP-10" }, { "code": null, "e": 33745, "s": 33715, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 33779, "s": 33745, "text": "Longest Common Subsequence | DP-4" }, { "code": null, "e": 33817, "s": 33779, "text": "Longest Increasing Subsequence | DP-3" } ]
JavaScript Variables
Variables are containers for storing data (storing data values). In this example, x, y, and z, are variables, declared with the var keyword: In this example, x, y, and z, are variables, declared with the let keyword: In this example, x, y, and z, are undeclared variables: From all the examples above, you can guess: x stores the value 5 y stores the value 6 z stores the value 11 Always declare JavaScript variables with var,let, orconst. The var keyword is used in all JavaScript code from 1995 to 2015. The let and const keywords were added to JavaScript in 2015. If you want your code to run in older browser, you must use var. If you want a general rule: always declare variables with const. If you think the value of the variable can change, use let. In this example, price1, price2, and total, are variables: The two variables price1 and price2 are declared with the const keyword. These are constant values and cannot be changed. The variable total is declared with the let keyword. This is a value that can be changed. Just like in algebra, variables hold values: Just like in algebra, variables are used in expressions: From the example above, you can guess that the total is calculated to be 11. Variables are containers for storing values. All JavaScript variables must be identified with unique names. These unique names are called identifiers. Identifiers can be short names (like x and y) or more descriptive names (age, sum, totalVolume). The general rules for constructing names for variables (unique identifiers) are: Names can contain letters, digits, underscores, and dollar signs. Names must begin with a letter Names can also begin with $ and _ (but we will not use it in this tutorial) Names are case sensitive (y and Y are different variables) Reserved words (like JavaScript keywords) cannot be used as names JavaScript identifiers are case-sensitive. In JavaScript, the equal sign (=) is an "assignment" operator, not an "equal to" operator. This is different from algebra. The following does not make sense in algebra: In JavaScript, however, it makes perfect sense: it assigns the value of x + 5 to x. (It calculates the value of x + 5 and puts the result into x. The value of x is incremented by 5.) The "equal to" operator is written like == in JavaScript. JavaScript variables can hold numbers like 100 and text values like "John Doe". In programming, text values are called text strings. JavaScript can handle many types of data, but for now, just think of numbers and strings. Strings are written inside double or single quotes. Numbers are written without quotes. If you put a number in quotes, it will be treated as a text string. Creating a variable in JavaScript is called "declaring" a variable. You declare a JavaScript variable with the var or the let keyword: After the declaration, the variable has no value (technically it is undefined). To assign a value to the variable, use the equal sign: You can also assign a value to the variable when you declare it: In the example below, we create a variable called carName and assign the value "Volvo" to it. Then we "output" the value inside an HTML paragraph with id="demo": It's a good programming practice to declare all variables at the beginning of a script. You can declare many variables in one statement. Start the statement with let and separate the variables by comma: A declaration can span multiple lines: In computer programs, variables are often declared without a value. The value can be something that has to be calculated, or something that will be provided later, like user input. A variable declared without a value will have the value undefined. The variable carName will have the value undefined after the execution of this statement: If you re-declare a JavaScript variable declared with var, it will not lose its value. The variable carName will still have the value "Volvo" after the execution of these statements: You cannot re-declare a variable declared with let or const. This will not work: As with algebra, you can do arithmetic with JavaScript variables, using operators like = and +: You can also add strings, but strings will be concatenated: Also try this: If you put a number in quotes, the rest of the numbers will be treated as strings, and concatenated. Now try this: Since JavaScript treats a dollar sign as a letter, identifiers containing $ are valid variable names: Using the dollar sign is not very common in JavaScript, but professional programmers often use it as an alias for the main function in a JavaScript library. In the JavaScript library jQuery, for instance, the main function $ is used to select HTML elements. In jQuery $("p"); means "select all p elements". Since JavaScript treats underscore as a letter, identifiers containing _ are valid variable names: Using the underscore is not very common in JavaScript, but a convention among professional programmers is to use it as an alias for "private (hidden)" variables. Create a variable called carName and assign the value Volvo to it. var = ""; Start the Exercise We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: help@w3schools.com Your message has been sent to W3Schools.
[ { "code": null, "e": 111, "s": 46, "text": "Variables are containers for storing data (storing data values)." }, { "code": null, "e": 187, "s": 111, "text": "In this example, x, y, and z,\nare variables, declared with the var keyword:" }, { "code": null, "e": 263, "s": 187, "text": "In this example, x, y, and z,\nare variables, declared with the let keyword:" }, { "code": null, "e": 319, "s": 263, "text": "In this example, x, y, and z,\nare undeclared variables:" }, { "code": null, "e": 363, "s": 319, "text": "From all the examples above, you can guess:" }, { "code": null, "e": 384, "s": 363, "text": "x stores the value 5" }, { "code": null, "e": 405, "s": 384, "text": "y stores the value 6" }, { "code": null, "e": 427, "s": 405, "text": "z stores the value 11" }, { "code": null, "e": 486, "s": 427, "text": "Always declare JavaScript variables with var,let,\norconst." }, { "code": null, "e": 552, "s": 486, "text": "The var keyword is used in all JavaScript code from 1995 to 2015." }, { "code": null, "e": 613, "s": 552, "text": "The let and const keywords were added to JavaScript in 2015." }, { "code": null, "e": 678, "s": 613, "text": "If you want your code to run in older browser, you must use var." }, { "code": null, "e": 743, "s": 678, "text": "If you want a general rule: always declare variables with const." }, { "code": null, "e": 803, "s": 743, "text": "If you think the value of the variable can change, use let." }, { "code": null, "e": 862, "s": 803, "text": "In this example, price1, price2, and total, are variables:" }, { "code": null, "e": 935, "s": 862, "text": "The two variables price1 and price2\nare declared with the const keyword." }, { "code": null, "e": 984, "s": 935, "text": "These are constant values and cannot be changed." }, { "code": null, "e": 1037, "s": 984, "text": "The variable total is declared with the let keyword." }, { "code": null, "e": 1074, "s": 1037, "text": "This is a value that can be changed." }, { "code": null, "e": 1119, "s": 1074, "text": "Just like in algebra, variables hold values:" }, { "code": null, "e": 1176, "s": 1119, "text": "Just like in algebra, variables are used in expressions:" }, { "code": null, "e": 1253, "s": 1176, "text": "From the example above, you can guess that the total is calculated to be 11." }, { "code": null, "e": 1298, "s": 1253, "text": "Variables are containers for storing values." }, { "code": null, "e": 1361, "s": 1298, "text": "All JavaScript variables must be\nidentified with unique names." }, { "code": null, "e": 1404, "s": 1361, "text": "These unique names are called identifiers." }, { "code": null, "e": 1501, "s": 1404, "text": "Identifiers can be short names (like x and y) or more descriptive names (age, sum, totalVolume)." }, { "code": null, "e": 1582, "s": 1501, "text": "The general rules for constructing names for variables (unique identifiers) are:" }, { "code": null, "e": 1648, "s": 1582, "text": "Names can contain letters, digits, underscores, and dollar signs." }, { "code": null, "e": 1679, "s": 1648, "text": "Names must begin with a letter" }, { "code": null, "e": 1755, "s": 1679, "text": "Names can also begin with $ and _ (but we will not use it in this tutorial)" }, { "code": null, "e": 1814, "s": 1755, "text": "Names are case sensitive (y and Y are different variables)" }, { "code": null, "e": 1880, "s": 1814, "text": "Reserved words (like JavaScript keywords) cannot be used as names" }, { "code": null, "e": 1923, "s": 1880, "text": "JavaScript identifiers are case-sensitive." }, { "code": null, "e": 2015, "s": 1923, "text": "In JavaScript, the equal sign (=) is an \"assignment\" operator, not an \n\"equal to\" operator." }, { "code": null, "e": 2094, "s": 2015, "text": "This is different from algebra. The following does not make sense in \nalgebra:" }, { "code": null, "e": 2179, "s": 2094, "text": "In JavaScript, however, it makes perfect sense: it assigns the value of x + 5 to \nx." }, { "code": null, "e": 2279, "s": 2179, "text": "(It calculates the value of x + 5 and puts the result into x. The value of x \nis incremented by 5.)" }, { "code": null, "e": 2337, "s": 2279, "text": "The \"equal to\" operator is written like == in JavaScript." }, { "code": null, "e": 2418, "s": 2337, "text": "JavaScript variables can hold numbers like 100 and text values like \"John \nDoe\"." }, { "code": null, "e": 2471, "s": 2418, "text": "In programming, text values are called text strings." }, { "code": null, "e": 2562, "s": 2471, "text": "JavaScript can handle many types of data, but for now, just think of numbers and strings. " }, { "code": null, "e": 2651, "s": 2562, "text": "Strings are written inside double or single quotes. Numbers are written \nwithout quotes." }, { "code": null, "e": 2719, "s": 2651, "text": "If you put a number in quotes, it will be treated as a text string." }, { "code": null, "e": 2788, "s": 2719, "text": "Creating a variable in JavaScript is called \"declaring\" a variable. " }, { "code": null, "e": 2855, "s": 2788, "text": "You declare a JavaScript variable with the var or the let keyword:" }, { "code": null, "e": 2935, "s": 2855, "text": "After the declaration, the variable has no value (technically it is undefined)." }, { "code": null, "e": 2990, "s": 2935, "text": "To assign a value to the variable, use the equal sign:" }, { "code": null, "e": 3055, "s": 2990, "text": "You can also assign a value to the variable when you declare it:" }, { "code": null, "e": 3150, "s": 3055, "text": "In the example below, we create a variable called carName and assign the value \n\"Volvo\" to it." }, { "code": null, "e": 3218, "s": 3150, "text": "Then we \"output\" the value inside an HTML paragraph with id=\"demo\":" }, { "code": null, "e": 3306, "s": 3218, "text": "It's a good programming practice to declare all variables at the beginning of a script." }, { "code": null, "e": 3355, "s": 3306, "text": "You can declare many variables in one statement." }, { "code": null, "e": 3422, "s": 3355, "text": "Start the statement \nwith let and separate the variables by comma:" }, { "code": null, "e": 3462, "s": 3422, "text": "A declaration can span multiple lines: " }, { "code": null, "e": 3645, "s": 3462, "text": "In computer programs, variables are often declared without a value. The value \ncan be something that has to be calculated, or something that will be provided \nlater, like user input." }, { "code": null, "e": 3713, "s": 3645, "text": "A variable declared without a value will have the value \nundefined." }, { "code": null, "e": 3803, "s": 3713, "text": "The variable carName will have the value undefined after the execution of this statement:" }, { "code": null, "e": 3890, "s": 3803, "text": "If you re-declare a JavaScript variable declared with var, it will not lose its value." }, { "code": null, "e": 3986, "s": 3890, "text": "The variable carName will still have the value \"Volvo\" after the execution of these statements:" }, { "code": null, "e": 4047, "s": 3986, "text": "You cannot re-declare a variable declared with let or const." }, { "code": null, "e": 4067, "s": 4047, "text": "This will not work:" }, { "code": null, "e": 4165, "s": 4067, "text": "As with algebra, you can do arithmetic with JavaScript variables, using \noperators like = and +: " }, { "code": null, "e": 4225, "s": 4165, "text": "You can also add strings, but strings will be concatenated:" }, { "code": null, "e": 4240, "s": 4225, "text": "Also try this:" }, { "code": null, "e": 4341, "s": 4240, "text": "If you put a number in quotes, the rest of the numbers will be treated as strings, and concatenated." }, { "code": null, "e": 4355, "s": 4341, "text": "Now try this:" }, { "code": null, "e": 4457, "s": 4355, "text": "Since JavaScript treats a dollar sign as a letter, identifiers containing $ are valid variable names:" }, { "code": null, "e": 4615, "s": 4457, "text": "Using the dollar sign is not very common in JavaScript,\nbut professional programmers often use it \nas an alias for the main function in a JavaScript library." }, { "code": null, "e": 4765, "s": 4615, "text": "In the JavaScript library jQuery, for instance, the main function\n$ is used to select HTML elements.\nIn jQuery $(\"p\"); means \"select all p elements\"." }, { "code": null, "e": 4864, "s": 4765, "text": "Since JavaScript treats underscore as a letter, identifiers containing _ are valid variable names:" }, { "code": null, "e": 5027, "s": 4864, "text": "Using the underscore is not very common in JavaScript,\n\nbut a convention among professional programmers is to use it as an alias for\n\"private (hidden)\" variables." }, { "code": null, "e": 5094, "s": 5027, "text": "Create a variable called carName and assign the value Volvo to it." }, { "code": null, "e": 5106, "s": 5094, "text": "var = \"\";\n" }, { "code": null, "e": 5125, "s": 5106, "text": "Start the Exercise" }, { "code": null, "e": 5158, "s": 5125, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 5200, "s": 5158, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 5307, "s": 5200, "text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:" }, { "code": null, "e": 5326, "s": 5307, "text": "help@w3schools.com" } ]
Copy Kaggle data into Google Cloud Storage | Towards Data Science
So, you have picked your Kaggle competition, and you want to start training your model and make yourself known on the Kaggle leaderboard. If like us, you use Google Cloud AI Platform for your data science workloads, one of the first steps in a Kaggle competition is to upload the Kaggle training data into Google Cloud Storage. We will be using this recently announced (late Nov 2020) Kaggle competition as an example. www.kaggle.com This particular competition is an image classification problem with circa 20k training images (jpeg files) in Kaggle. Here’s a simple way to upload these into a Google Cloud Storage bucket. We assume you already have a Google Cloud Project. If not, you can easily create one (for free) using the link below. We assume you already have a Google Cloud Project. If not, you can easily create one (for free) using the link below. cloud.google.com 2. Make sure you have permissions on your Google Cloud Project to create new storage buckets in Google Cloud Storage (GCS) and upload files. You can read the GSC documentation here if you are unsure. 3. We assume you have registered with Kaggle, and have signed up for a competition. In a browser, navigate to kaggle.comCreate a new Kaggle Notebook. To do this, click <> Notebooks on the left sidebar and click + New NotebookGive your notebook a name so you can easily find it again. I called mine “Cassava — Copy Kaggle Data to GCS” In a browser, navigate to kaggle.com Create a new Kaggle Notebook. To do this, click <> Notebooks on the left sidebar and click + New Notebook Give your notebook a name so you can easily find it again. I called mine “Cassava — Copy Kaggle Data to GCS” Tip: I prefix my notebooks in Kaggle with the competition name to make them easy to find later on 4. Add the following imports in a new Notebook cell (click the +Code button to add a new cell: import os from google.cloud import storage Run the cell by clicking into the cell, and then clicking the play button that appears on the left. 3. Add a reference in your Notebook to the Casava Kaggle training images. To do this, click Add data. In the window that appears, select the Competition Data tab, find the Casava competition, and click the Add button. You should now see the Casava data listed under Input in the sidebar: 4. Grant Kaggle access to your Google Cloud Storage service. To do this, select Google Cloud Services from the Add-ons menu: In the window that appears, tick Cloud Storage and then click the Link Account button. 5. Add a new code cell and declare the following two functions; the first will create a storage bucket, and the second will upload all files to a bucket that are found in the source folder path. Replace the GCP_PROJECT_ID with your Google Cloud project id. Once added, run the cell and confirm no errors. storage_client = storage.Client(project=’GCP_PROJECT_ID')def create_bucket(bucket_name): bucket = storage_client.create_bucket(bucket_name)def upload_files(bucket_name, source_folder): bucket = storage_client.get_bucket(bucket_name) for filename in os.listdir(source_folder): blob = bucket.blob(filename) blob.upload_from_filename(source_folder + filename) 6. Add a new cell to create your new GCS bucket. Replace BUCKET_NAME with a suitable, unique name. Run the cell. bucket_name = ‘BUCKET_NAME’ create_bucket(bucket_name) Tip: GCS bucket names must be globally unique. An easy way to ensure this, is to add a suffix of your GCP project id (which is also unique). 7. In a browser, open the Google Cloud Console. Type “storage” in the search bar and click on Storage. Confirm you see your new bucket above in the list. 8. Finally, upload the training resources from Kaggle into your new bucket. To do this, add a new cell with the following code: local_data = ‘../input/cassava-leaf-disease-classification/train_images/’upload_blob(bucket_name, local_data) Replace the string in bold, with the location of your training data. To get this, click on the Copy file path button (shown below). And then add the folder that contains the data you want to copy (mine was in train_images). Run that cell and your data will be copied! It can take a little while, depending on your file volumes and size. The Cassava data took about 15 minutes. Hopefully, you found this walkthrough useful. Since Google acquired Kaggle in 2019 we are seeing tighter integration with Google Cloud, for example, you can now submit models trained in AutoML. Keep an eye out for a follow-up article to this, where I will do just that using Google Cloud AI Platform Unified and AutoML. 1. In Part 2, we will show how to train a model for this competition using Google Cloud AI Platform Unified and AutoML. 2. View the Cassava Kaggle competition used in this walkthrough. 3. Learn more about Ancoris Data, Analytics & AI
[ { "code": null, "e": 310, "s": 172, "text": "So, you have picked your Kaggle competition, and you want to start training your model and make yourself known on the Kaggle leaderboard." }, { "code": null, "e": 500, "s": 310, "text": "If like us, you use Google Cloud AI Platform for your data science workloads, one of the first steps in a Kaggle competition is to upload the Kaggle training data into Google Cloud Storage." }, { "code": null, "e": 591, "s": 500, "text": "We will be using this recently announced (late Nov 2020) Kaggle competition as an example." }, { "code": null, "e": 606, "s": 591, "text": "www.kaggle.com" }, { "code": null, "e": 796, "s": 606, "text": "This particular competition is an image classification problem with circa 20k training images (jpeg files) in Kaggle. Here’s a simple way to upload these into a Google Cloud Storage bucket." }, { "code": null, "e": 914, "s": 796, "text": "We assume you already have a Google Cloud Project. If not, you can easily create one (for free) using the link below." }, { "code": null, "e": 1032, "s": 914, "text": "We assume you already have a Google Cloud Project. If not, you can easily create one (for free) using the link below." }, { "code": null, "e": 1049, "s": 1032, "text": "cloud.google.com" }, { "code": null, "e": 1249, "s": 1049, "text": "2. Make sure you have permissions on your Google Cloud Project to create new storage buckets in Google Cloud Storage (GCS) and upload files. You can read the GSC documentation here if you are unsure." }, { "code": null, "e": 1333, "s": 1249, "text": "3. We assume you have registered with Kaggle, and have signed up for a competition." }, { "code": null, "e": 1583, "s": 1333, "text": "In a browser, navigate to kaggle.comCreate a new Kaggle Notebook. To do this, click <> Notebooks on the left sidebar and click + New NotebookGive your notebook a name so you can easily find it again. I called mine “Cassava — Copy Kaggle Data to GCS”" }, { "code": null, "e": 1620, "s": 1583, "text": "In a browser, navigate to kaggle.com" }, { "code": null, "e": 1726, "s": 1620, "text": "Create a new Kaggle Notebook. To do this, click <> Notebooks on the left sidebar and click + New Notebook" }, { "code": null, "e": 1835, "s": 1726, "text": "Give your notebook a name so you can easily find it again. I called mine “Cassava — Copy Kaggle Data to GCS”" }, { "code": null, "e": 1933, "s": 1835, "text": "Tip: I prefix my notebooks in Kaggle with the competition name to make them easy to find later on" }, { "code": null, "e": 2028, "s": 1933, "text": "4. Add the following imports in a new Notebook cell (click the +Code button to add a new cell:" }, { "code": null, "e": 2071, "s": 2028, "text": "import os from google.cloud import storage" }, { "code": null, "e": 2171, "s": 2071, "text": "Run the cell by clicking into the cell, and then clicking the play button that appears on the left." }, { "code": null, "e": 2273, "s": 2171, "text": "3. Add a reference in your Notebook to the Casava Kaggle training images. To do this, click Add data." }, { "code": null, "e": 2389, "s": 2273, "text": "In the window that appears, select the Competition Data tab, find the Casava competition, and click the Add button." }, { "code": null, "e": 2459, "s": 2389, "text": "You should now see the Casava data listed under Input in the sidebar:" }, { "code": null, "e": 2584, "s": 2459, "text": "4. Grant Kaggle access to your Google Cloud Storage service. To do this, select Google Cloud Services from the Add-ons menu:" }, { "code": null, "e": 2671, "s": 2584, "text": "In the window that appears, tick Cloud Storage and then click the Link Account button." }, { "code": null, "e": 2866, "s": 2671, "text": "5. Add a new code cell and declare the following two functions; the first will create a storage bucket, and the second will upload all files to a bucket that are found in the source folder path." }, { "code": null, "e": 2928, "s": 2866, "text": "Replace the GCP_PROJECT_ID with your Google Cloud project id." }, { "code": null, "e": 2976, "s": 2928, "text": "Once added, run the cell and confirm no errors." }, { "code": null, "e": 3336, "s": 2976, "text": "storage_client = storage.Client(project=’GCP_PROJECT_ID')def create_bucket(bucket_name): bucket = storage_client.create_bucket(bucket_name)def upload_files(bucket_name, source_folder): bucket = storage_client.get_bucket(bucket_name) for filename in os.listdir(source_folder): blob = bucket.blob(filename) blob.upload_from_filename(source_folder + filename)" }, { "code": null, "e": 3449, "s": 3336, "text": "6. Add a new cell to create your new GCS bucket. Replace BUCKET_NAME with a suitable, unique name. Run the cell." }, { "code": null, "e": 3504, "s": 3449, "text": "bucket_name = ‘BUCKET_NAME’ create_bucket(bucket_name)" }, { "code": null, "e": 3645, "s": 3504, "text": "Tip: GCS bucket names must be globally unique. An easy way to ensure this, is to add a suffix of your GCP project id (which is also unique)." }, { "code": null, "e": 3799, "s": 3645, "text": "7. In a browser, open the Google Cloud Console. Type “storage” in the search bar and click on Storage. Confirm you see your new bucket above in the list." }, { "code": null, "e": 3927, "s": 3799, "text": "8. Finally, upload the training resources from Kaggle into your new bucket. To do this, add a new cell with the following code:" }, { "code": null, "e": 4037, "s": 3927, "text": "local_data = ‘../input/cassava-leaf-disease-classification/train_images/’upload_blob(bucket_name, local_data)" }, { "code": null, "e": 4261, "s": 4037, "text": "Replace the string in bold, with the location of your training data. To get this, click on the Copy file path button (shown below). And then add the folder that contains the data you want to copy (mine was in train_images)." }, { "code": null, "e": 4414, "s": 4261, "text": "Run that cell and your data will be copied! It can take a little while, depending on your file volumes and size. The Cassava data took about 15 minutes." }, { "code": null, "e": 4460, "s": 4414, "text": "Hopefully, you found this walkthrough useful." }, { "code": null, "e": 4734, "s": 4460, "text": "Since Google acquired Kaggle in 2019 we are seeing tighter integration with Google Cloud, for example, you can now submit models trained in AutoML. Keep an eye out for a follow-up article to this, where I will do just that using Google Cloud AI Platform Unified and AutoML." }, { "code": null, "e": 4854, "s": 4734, "text": "1. In Part 2, we will show how to train a model for this competition using Google Cloud AI Platform Unified and AutoML." }, { "code": null, "e": 4919, "s": 4854, "text": "2. View the Cassava Kaggle competition used in this walkthrough." } ]
ctime() Function in C/C++
The C library function char *ctime(const time_t *timer) returns a string representing the localtime based on the argument timer. The returned string has the following format − Www Mmm dd hh:mm:ss yyyy, where Www is the weekday, Mmm the month in letters, dd the day of the month, hh:mm:ss the time, and yyyy the year. The syntax is like below − char *ctime(const time_t *timer) This function takes the pointer to a time_t, which is containing the calendar time. It returns a string containing date, time info in human readable format. Live Demo #include <stdio.h> #include <time.h> int main () { time_t curtime; time(&curtime); printf("Current time = %s", ctime(&curtime)); return(0); } Current time = Thu May 23 17:18:43 2019
[ { "code": null, "e": 1191, "s": 1062, "text": "The C library function char *ctime(const time_t *timer) returns a string representing the localtime based on the argument timer." }, { "code": null, "e": 1379, "s": 1191, "text": "The returned string has the following format − Www Mmm dd hh:mm:ss yyyy, where Www is the weekday, Mmm the month in letters, dd the day of the month, hh:mm:ss the time, and yyyy the year." }, { "code": null, "e": 1406, "s": 1379, "text": "The syntax is like below −" }, { "code": null, "e": 1439, "s": 1406, "text": "char *ctime(const time_t *timer)" }, { "code": null, "e": 1596, "s": 1439, "text": "This function takes the pointer to a time_t, which is containing the calendar time. It returns a string containing date, time info in human readable format." }, { "code": null, "e": 1607, "s": 1596, "text": " Live Demo" }, { "code": null, "e": 1761, "s": 1607, "text": "#include <stdio.h>\n#include <time.h>\nint main () {\n time_t curtime;\n time(&curtime);\n printf(\"Current time = %s\", ctime(&curtime));\n return(0);\n}" }, { "code": null, "e": 1801, "s": 1761, "text": "Current time = Thu May 23 17:18:43 2019" } ]
Dynamic method dispatch or Runtime polymorphism in Java
Runtime Polymorphism in Java is achieved by Method overriding in which a child class overrides a method in its parent. An overridden method is essentially hidden in the parent class, and is not invoked unless the child class uses the super keyword within the overriding method. This method call resolution happens at runtime and is termed as Dynamic method dispatch mechanism. Let us look at an example. class Animal { public void move() { System.out.println("Animals can move"); } } class Dog extends Animal { public void move() { System.out.println("Dogs can walk and run"); } } public class TestDog { public static void main(String args[]) { Animal a = new Animal(); // Animal reference and object Animal b = new Dog(); // Animal reference but Dog object a.move(); // runs the method in Animal class b.move(); // runs the method in Dog class } } This will produce the following result − Animals can move Dogs can walk and run In the above example, you can see that even though b is a type of Animal it runs the move method in the Dog class. The reason for this is: In compile time, the check is made on the reference type. However, in the runtime, JVM figures out the object type and would run the method that belongs to that particular object. Therefore, in the above example, the program will compile properly since Animal class has the method move. Then, at the runtime, it runs the method specific for that object.
[ { "code": null, "e": 1439, "s": 1062, "text": "Runtime Polymorphism in Java is achieved by Method overriding in which a child class overrides a method in its parent. An overridden method is essentially hidden in the parent class, and is not invoked unless the child class uses the super keyword within the overriding method. This method call resolution happens at runtime and is termed as Dynamic method dispatch mechanism." }, { "code": null, "e": 1466, "s": 1439, "text": "Let us look at an example." }, { "code": null, "e": 1973, "s": 1466, "text": "class Animal {\n public void move() {\n System.out.println(\"Animals can move\");\n }\n}\n\nclass Dog extends Animal {\n public void move() {\n System.out.println(\"Dogs can walk and run\");\n }\n}\n\npublic class TestDog {\n\n public static void main(String args[]) {\n \n Animal a = new Animal(); // Animal reference and object\n Animal b = new Dog(); // Animal reference but Dog object\n\n a.move(); // runs the method in Animal class\n b.move(); // runs the method in Dog class\n }\n}" }, { "code": null, "e": 2014, "s": 1973, "text": "This will produce the following result −" }, { "code": null, "e": 2053, "s": 2014, "text": "Animals can move\nDogs can walk and run" }, { "code": null, "e": 2372, "s": 2053, "text": "In the above example, you can see that even though b is a type of Animal it runs the move method in the Dog class. The reason for this is: In compile time, the check is made on the reference type. However, in the runtime, JVM figures out the object type and would run the method that belongs to that particular object." }, { "code": null, "e": 2546, "s": 2372, "text": "Therefore, in the above example, the program will compile properly since Animal class has the method move. Then, at the runtime, it runs the method specific for that object." } ]
How to use Swift to detect when AVPlayer video ends playing?
To detect the end of a video in swift we’ll need to create a video player, then use notifications to detect when the video stops playing. We’ll do this with help of an example in swift. Let’s create a project and drag and drop any video with extension “mp4”, select copy resource if required and add to the target of our project. Now we’ll programmatically first create a Video Player, then we’ll create url of the video in our project, and then we’ll play the video. var videoPlayer: AVPlayer! Now, in the viewDidAppear add the following code. override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) let filepath: String? = Bundle.main.path(forResource: "Introduction", ofType: "mp4") if let videoPath = filepath { let url = URL.init(fileURLWithPath: videoPath) videoPlayer = AVPlayer(url: url) let playerLayer = AVPlayerLayer(player: videoPlayer) playerLayer.frame = self.view.bounds self.view.layer.addSublayer(playerLayer) videoPlayer.play() } } The above code will create a video player, and add it as a sublayer to our default view in the view controller. Now we need to add an observer to our player, and also create an observer method that should be called when it detects the end of the video. Add the code block below to the viewDidAppear method. NotificationCenter.default.addObserver(self, selector: #selector(videoDidEnd), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: nil) Now we need to write the videoDidEnd method too, Inside this method you can perform any action you want, for now, we’ll just print “video ended” when the video ends and the notification center calls this method. @objc func videoDidEnd(notification: NSNotification) { print("video ended") } When we run this code we get the following result. Once the video stops playing we get output in our console. Now, the above code does the required thing for us, but for efficient memory usage, we also need to remove the observer, which can be done using the code below. deinit { NotificationCenter.default.removeObserver(self) }
[ { "code": null, "e": 1248, "s": 1062, "text": "To detect the end of a video in swift we’ll need to create a video player, then use notifications to detect when the video stops playing. We’ll do this with help of an example in swift." }, { "code": null, "e": 1392, "s": 1248, "text": "Let’s create a project and drag and drop any video with extension “mp4”, select copy resource if required and add to the target of our project." }, { "code": null, "e": 1530, "s": 1392, "text": "Now we’ll programmatically first create a Video Player, then we’ll create url of the video in our project, and then we’ll play the video." }, { "code": null, "e": 1557, "s": 1530, "text": "var videoPlayer: AVPlayer!" }, { "code": null, "e": 1607, "s": 1557, "text": "Now, in the viewDidAppear add the following code." }, { "code": null, "e": 2082, "s": 1607, "text": "override func viewDidAppear(_ animated: Bool) {\n super.viewDidAppear(animated)\n let filepath: String? = Bundle.main.path(forResource: \"Introduction\", ofType: \"mp4\")\n if let videoPath = filepath {\n let url = URL.init(fileURLWithPath: videoPath)\n videoPlayer = AVPlayer(url: url)\n let playerLayer = AVPlayerLayer(player: videoPlayer)\n playerLayer.frame = self.view.bounds\n self.view.layer.addSublayer(playerLayer)\n videoPlayer.play()\n }\n}" }, { "code": null, "e": 2194, "s": 2082, "text": "The above code will create a video player, and add it as a sublayer to our default view in the view controller." }, { "code": null, "e": 2389, "s": 2194, "text": "Now we need to add an observer to our player, and also create an observer method that should be called when it detects the end of the video. Add the code block below to the viewDidAppear method." }, { "code": null, "e": 2537, "s": 2389, "text": "NotificationCenter.default.addObserver(self, selector: #selector(videoDidEnd), name:\nNSNotification.Name.AVPlayerItemDidPlayToEndTime, object: nil)" }, { "code": null, "e": 2749, "s": 2537, "text": "Now we need to write the videoDidEnd method too, Inside this method you can perform any action you want, for now, we’ll just print “video ended” when the video ends and the notification center calls this method." }, { "code": null, "e": 2830, "s": 2749, "text": "@objc func videoDidEnd(notification: NSNotification) {\n print(\"video ended\")\n}" }, { "code": null, "e": 2881, "s": 2830, "text": "When we run this code we get the following result." }, { "code": null, "e": 2940, "s": 2881, "text": "Once the video stops playing we get output in our console." }, { "code": null, "e": 3101, "s": 2940, "text": "Now, the above code does the required thing for us, but for efficient memory usage, we also need to remove the observer, which can be done using the code below." }, { "code": null, "e": 3163, "s": 3101, "text": "deinit {\n NotificationCenter.default.removeObserver(self)\n}" } ]
Detecting pedestrians and bikers on a drone with Jetson Xavier | by Jaiyam Sharma | Towards Data Science
Drones are one of the coolest technologies every maker and enthusiast wants to lay their hands on. At the same time as drones are becoming common, AI is rapidly advancing and we are now in a state where object detection and semantic segmentation are possible right onboard the drone. In this blog post, I will share how to perform object detection on images taken by a drone. A few basics about the problem at hand First, it is important to realize that we cannot realistically run object detection on general purpose embedded hardware such as the raspberry pi and special purpose hardware built for AI inferencing is required. Second, if you run commonly used object detection models, such as YOLO or SSD trained on COCO and Pascal VOC datasets, they won’t do well at all. This is because the view of an object from a height is quite different from that on the ground. Thus, the distribution of the inference data will be very different from that encountered by the model during training, which will cause it to fail. Some solutions As mentioned in the title In this post, I will be using the highest end embedded processor for autonomous robots available at the time of writing, Jetson AGX Xavier from Nvidia. If you want to use a Jetson TX2 or nano, I will provide some suggestions for improving their performance towards the end of the post. To remedy the problem of differing data distribution, researchers at Stanford University have released a dataset called Stanford Drone dataset, which contains several videos taken from drones along with labels for each frame of each video. There are six classes being detected: Biker, Car, Bus, Cart, Skater and Pedestrian. Any decent object detection model trained the Stanford dataset should do a good job of detecting these six objects. In this post, we will be using RetinaNet, a very good object detection model released by Facebook (FAIR), which shapes the loss function in such a way that the model learns to focus on hard examples during training and thus learns much better. More details about RetinaNet can be found here. Although the Detectron 2 model zoo by FAIR has several models which can be downloaded and used, they are all trained on COCO and Pascal datasets, which as we discussed are not useful for our task. It would be a big task to train a model from scratch on the Stanford dataset. Fortunately, I found that Nvidia provided a model trained on this dataset as a part of one of their webinars on DeepStream SDK. I am not trying to endorse Nvidia in this blog post, but if you want to get started without training your own model, the quickest way would be to register for the webinar and download the model as a part of the webinar resources. The file you are looking for is stanford_resnext50.onnx which is about 150 MB in size. Once you have this file, you can use the C++ API of retinanet-examples repository from GitHub to convert the onnx file to an engineplan file which is compiled specifically for the Jetson device you are using. Here is a walkthrough of these steps: git clone https://github.com/NVIDIA/retinanet-examples.gitcd retinanet-examples/extras/cppapimkdir build && cd buildcmake -DCMAKE_CUDA_FLAGS="--expt-extended-lambda -std=c++11" ..makecp /path/to/onnx/file . #copy onnx file to this directory./export stanford_resnext50.onnx engine.plan After engine.plan has been created successfully, you can use the infer utility to test out the performance of the model on an image: ./infer engine.plan image.jpg This will write a file called detections.png which will have the bounding boxes of the objects detected in the image. I gave an image from one of the videos in the Stanford dataset as input to the model and here is what it spat out: We can see that the model has detected several pedestrians walking on the sidewalk. This would not be possible with Pascal or COCO trained models. The aspect ratio of this image looks odd because the infer utility resizes the image to 1280x1280, which is the input size of the model. Now that we can detect pedestrians in a single image, it is straightforward to extend this to videos by editing the infer.cpp file in cppapi directory. I came up with this: To use this script, save it as infervideo.cpp in the cppapi directory and edit CMakeLists.txt to add the lines to add the infervideo executable and link it to retinanet and other libraries. Once you are done, you can switch over to the build directory and invoke cmake and make as before: cmake -DCMAKE_CUDA_FLAGS="--expt-extended-lambda -std=c++11" ..make Once the targets have been built you will see a new executable in the build directory called infervideo, which can be used as: ./infervideo engine.plan input.mov output.mp4 This will create a new video called output.mp4 which will show the bounding boxes for each object. If you want to perform object detection on a live video stream from the drone, you can simply provide the gstreamer pipeline of your camera as the second argument to the script and it will handle cameras as well. I used the script above to run inference on a video taken at the IIT Delhi campus in New Delhi, my alma mater. I used a low threshold of 0.2 for drawing bounding boxes, which is why there are some false positives in the video below. If you run the script provided above on the Xavier, you will find that each frame of the video takes 150 ms for inference. This is painfully slow on the Xavier and would be even slower on the smaller Jetsons like TX2 or nano. Here are some things we can do to improve the performance: The engine we created in this post was for fp16 precision. You can run this model on integer precision, which will improve its performance significantly. For this, you can use a small subset of the data from the Stanford dataset and the trtexec utility from tensorRT to create an INT8 calibration file and provide that file to export utility in our build directory. In practice, any realtime object detection pipeline does not perform full inference on each frame, but usually mixes it up with computationally inexpensive trackers such as the Kalman filter or optical flow. You can use opencv’s KalmanFilter class to keep track of objects across frames and perform inference only once per 4 or 5 frames. If the drone does not have a sudden jerky motion between inferences, this will work well in practice. The model we are using is very large as it takes in 1280x1280 images. You could train the model on lower resolution images or even a custom dataset to significantly improve the latency and throughput of the model. Instructions for training the model are on retinanet-examples repository, but this is best done on a good x86 workstation with a CUDA enabled GPU. This blog post is meant for anyone who having trouble deploying a retinanet model on Jetson Xavier and to chronicle my efforts towards getting a good object detection pipeline running on a drone. While we get significantly better results than would be possible with a Coco/Pascal model, there are many improvements to be made to make the model run in realtime on a Jetson device. Please use this as a starting point for your own projects and if you have any other suggestions to improve the performance, please do comment below.
[ { "code": null, "e": 548, "s": 172, "text": "Drones are one of the coolest technologies every maker and enthusiast wants to lay their hands on. At the same time as drones are becoming common, AI is rapidly advancing and we are now in a state where object detection and semantic segmentation are possible right onboard the drone. In this blog post, I will share how to perform object detection on images taken by a drone." }, { "code": null, "e": 587, "s": 548, "text": "A few basics about the problem at hand" }, { "code": null, "e": 800, "s": 587, "text": "First, it is important to realize that we cannot realistically run object detection on general purpose embedded hardware such as the raspberry pi and special purpose hardware built for AI inferencing is required." }, { "code": null, "e": 1191, "s": 800, "text": "Second, if you run commonly used object detection models, such as YOLO or SSD trained on COCO and Pascal VOC datasets, they won’t do well at all. This is because the view of an object from a height is quite different from that on the ground. Thus, the distribution of the inference data will be very different from that encountered by the model during training, which will cause it to fail." }, { "code": null, "e": 1206, "s": 1191, "text": "Some solutions" }, { "code": null, "e": 1518, "s": 1206, "text": "As mentioned in the title In this post, I will be using the highest end embedded processor for autonomous robots available at the time of writing, Jetson AGX Xavier from Nvidia. If you want to use a Jetson TX2 or nano, I will provide some suggestions for improving their performance towards the end of the post." }, { "code": null, "e": 1842, "s": 1518, "text": "To remedy the problem of differing data distribution, researchers at Stanford University have released a dataset called Stanford Drone dataset, which contains several videos taken from drones along with labels for each frame of each video. There are six classes being detected: Biker, Car, Bus, Cart, Skater and Pedestrian." }, { "code": null, "e": 2250, "s": 1842, "text": "Any decent object detection model trained the Stanford dataset should do a good job of detecting these six objects. In this post, we will be using RetinaNet, a very good object detection model released by Facebook (FAIR), which shapes the loss function in such a way that the model learns to focus on hard examples during training and thus learns much better. More details about RetinaNet can be found here." }, { "code": null, "e": 2970, "s": 2250, "text": "Although the Detectron 2 model zoo by FAIR has several models which can be downloaded and used, they are all trained on COCO and Pascal datasets, which as we discussed are not useful for our task. It would be a big task to train a model from scratch on the Stanford dataset. Fortunately, I found that Nvidia provided a model trained on this dataset as a part of one of their webinars on DeepStream SDK. I am not trying to endorse Nvidia in this blog post, but if you want to get started without training your own model, the quickest way would be to register for the webinar and download the model as a part of the webinar resources. The file you are looking for is stanford_resnext50.onnx which is about 150 MB in size." }, { "code": null, "e": 3217, "s": 2970, "text": "Once you have this file, you can use the C++ API of retinanet-examples repository from GitHub to convert the onnx file to an engineplan file which is compiled specifically for the Jetson device you are using. Here is a walkthrough of these steps:" }, { "code": null, "e": 3502, "s": 3217, "text": "git clone https://github.com/NVIDIA/retinanet-examples.gitcd retinanet-examples/extras/cppapimkdir build && cd buildcmake -DCMAKE_CUDA_FLAGS=\"--expt-extended-lambda -std=c++11\" ..makecp /path/to/onnx/file . #copy onnx file to this directory./export stanford_resnext50.onnx engine.plan" }, { "code": null, "e": 3635, "s": 3502, "text": "After engine.plan has been created successfully, you can use the infer utility to test out the performance of the model on an image:" }, { "code": null, "e": 3665, "s": 3635, "text": "./infer engine.plan image.jpg" }, { "code": null, "e": 3898, "s": 3665, "text": "This will write a file called detections.png which will have the bounding boxes of the objects detected in the image. I gave an image from one of the videos in the Stanford dataset as input to the model and here is what it spat out:" }, { "code": null, "e": 4182, "s": 3898, "text": "We can see that the model has detected several pedestrians walking on the sidewalk. This would not be possible with Pascal or COCO trained models. The aspect ratio of this image looks odd because the infer utility resizes the image to 1280x1280, which is the input size of the model." }, { "code": null, "e": 4355, "s": 4182, "text": "Now that we can detect pedestrians in a single image, it is straightforward to extend this to videos by editing the infer.cpp file in cppapi directory. I came up with this:" }, { "code": null, "e": 4545, "s": 4355, "text": "To use this script, save it as infervideo.cpp in the cppapi directory and edit CMakeLists.txt to add the lines to add the infervideo executable and link it to retinanet and other libraries." }, { "code": null, "e": 4644, "s": 4545, "text": "Once you are done, you can switch over to the build directory and invoke cmake and make as before:" }, { "code": null, "e": 4712, "s": 4644, "text": "cmake -DCMAKE_CUDA_FLAGS=\"--expt-extended-lambda -std=c++11\" ..make" }, { "code": null, "e": 4839, "s": 4712, "text": "Once the targets have been built you will see a new executable in the build directory called infervideo, which can be used as:" }, { "code": null, "e": 4885, "s": 4839, "text": "./infervideo engine.plan input.mov output.mp4" }, { "code": null, "e": 5197, "s": 4885, "text": "This will create a new video called output.mp4 which will show the bounding boxes for each object. If you want to perform object detection on a live video stream from the drone, you can simply provide the gstreamer pipeline of your camera as the second argument to the script and it will handle cameras as well." }, { "code": null, "e": 5430, "s": 5197, "text": "I used the script above to run inference on a video taken at the IIT Delhi campus in New Delhi, my alma mater. I used a low threshold of 0.2 for drawing bounding boxes, which is why there are some false positives in the video below." }, { "code": null, "e": 5715, "s": 5430, "text": "If you run the script provided above on the Xavier, you will find that each frame of the video takes 150 ms for inference. This is painfully slow on the Xavier and would be even slower on the smaller Jetsons like TX2 or nano. Here are some things we can do to improve the performance:" }, { "code": null, "e": 6081, "s": 5715, "text": "The engine we created in this post was for fp16 precision. You can run this model on integer precision, which will improve its performance significantly. For this, you can use a small subset of the data from the Stanford dataset and the trtexec utility from tensorRT to create an INT8 calibration file and provide that file to export utility in our build directory." }, { "code": null, "e": 6521, "s": 6081, "text": "In practice, any realtime object detection pipeline does not perform full inference on each frame, but usually mixes it up with computationally inexpensive trackers such as the Kalman filter or optical flow. You can use opencv’s KalmanFilter class to keep track of objects across frames and perform inference only once per 4 or 5 frames. If the drone does not have a sudden jerky motion between inferences, this will work well in practice." }, { "code": null, "e": 6882, "s": 6521, "text": "The model we are using is very large as it takes in 1280x1280 images. You could train the model on lower resolution images or even a custom dataset to significantly improve the latency and throughput of the model. Instructions for training the model are on retinanet-examples repository, but this is best done on a good x86 workstation with a CUDA enabled GPU." } ]
LOWESS Regression in Python: How to Discover Clear Patterns in Your Data? | by Saul Dobilas | Towards Data Science
Machine Learning is making huge leaps forward, with an increasing number of algorithms enabling us to solve complex real-world problems. This story is part of a deep dive series explaining the mechanics of Machine Learning algorithms. In addition to giving you an understanding of how ML algorithms work, it also provides you with Python examples to build your own ML models. What category of algorithms does LOWESS belong to? How does Locally Weighted Scatterplot Smoothing work? How can I use LOWESS to identify patterns and predict new data in Python? Locally Weighted Scatterplot Smoothing sits within the family of regression algorithms under the umbrella of Supervised Learning. This means that you need a set of labeled data with a numerical target variable to train your model. The below graph is interactive, so make sure to click on different categories to enlarge and reveal more👇. If you enjoy Data Science and Machine Learning, please subscribe to get an email whenever I publish a new story. Since LOWESS is a non-parametric fitting technique, you do not need to assume that data follows any specific distribution. However, at the same time, non-parametric fitting means that at the end, you will not have a global equation for you to use to predict the values of new data points. Not to worry, though, as I provide a workaround to this issue in the Python section later in this story. Given the above advantages and disadvantages, LOWESS is often used to perform the following analysis: A regression analysis where simple linear regression cannot produce a line of good fit due to data attributes not following a linear relationship. Note, a special case of multiple linear regression known as polynomial regression could also be used in this case. Data exploration and analysis in the social sciences, such as elections and voting behavior. Fitting a line to a scatter plot or time plot where noisy data values, sparse data points, or weak interrelationships interfere with your ability to see a line of best fit. While writing this story, I have assumed that you are already familiar with the ordinary least squares (OLS) regression. Hence, in this section, I only intend to provide an intuitive explanation of how LOWESS splits up the data to perform linear regression on local sections of the data. If you would like a refresher on OLS regression, feel free to take a look at my linear regression story: towardsdatascience.com Said that one important addition to LOWESS over OLS is that it applies weightings as you might have guessed from the algorithm’s name — Locally Weighted Scatterplot Smoothing. Typically, the algorithm uses a tri-cube weight function (see below), although other functions can also be used. Weight functionw(x) = (1 - |d|3)3, where d is is the distance of a given data point from the point on the curve being fitted, scaled to lie in the range between 0 and 1 The weight function gives the most weight to the data points nearest to the point of estimation and the least weight to the data points that are furthest away. It is based on the idea that points near each other in the explanatory variable space are more likely to be related to each other in a simple way than points that are further apart. We will use an example to illustrate how LOWESS works. Let us start by creating a scatterplot where the data points follow a sine wave pattern, but they have some random noise added, making the pattern less obvious. After that, we perform a LOWESS regression analysis a couple of times using different hyperparameters and add LOWESS curves to the plot: As you can see, there is a lot of noise in the data, with the relationship between x and y being non-linear (periodic, in fact). Clearly, simple linear regression would not give us a meaningful result here since it can only produce a straight line (unlike LOWESS or polynomial regression). The first thing that LOWESS does is selects a subset of the data. We can control the size of the subsets by specifying the ‘fraction’ hyperparameter. The two lines that we plotted above have hyperparameter values of 2/3 and 1/5. Let’s take the orange line as an example, with a default hyperparameter value of 2/3. This means that the LOWESS algorithm takes a subset of two-thirds of the entire data and performs a weighted linear least squares regression over the span of that data while moving by one point at a time and repeating the same process until it has gone through every single point. Starting from the very left and going right one point at a time, we can see how the orange line remains straight until x=-2.1. This is because the entire data ranges from -2π to +2π (-6.28 to +6.28) with an initial two-thirds window ranging from -6.28 to +2.1. Hence, only when the algorithm goes beyond -2.1 (midpoint between -6.28 and +2.1), it starts encountering new data points within its window, changing the curve's slope. If we now look at the red line (frac=1/5), we can see how narrowing the window to one-fifth of the data makes the algorithm more sensitive towards local trends. The featured gif image at the beginning of this story illustrates how this red line (frac=1/5) moves across the data performing weighted linear regression. This is the same process as described for the orange line (frac=2/3) except, the window the algorithm sees is narrower. While in this example, making the window smaller helped us get a better approximation of the sine wave, it is not always desirable to make a ‘fraction’ hyperparameter smaller. This largely depends on the data you are analyzing, as making a window smaller runs a risk of overfitting. You will see this in my next example, where 2/3 works much better than 1/5. Now that you have a general understating of how the algorithm works, it is time to have some fun and build a model in Python We will use the following: House price data from Kaggle Scikit-learn library to build a simple linear regression model (so we can compare the result to LOWESS) statsmodels library for LOWESS algorithm Plotly library for visualizations scipy library for data interpolation Pandas and Numpy Let us start by importing the required libraries. Next, we download and ingest the data that we will use to build our LOWESS and linear regression models.(source: https://www.kaggle.com/quantbruce/real-estate-price-prediction?select=Real+estate.csv) We will take ‘X3 distance to the nearest MRT station’ as our input (independent) variable and ‘Y house price of unit area’ as our output (dependent) variable and create a scatterplot to visualize the data. We can clearly see the relationship between x and y with the house price (per unit area) decreasing as the distance from the nearest MRT station increases. Since the relationship is somewhat linear, the question is whether LOWESS can give us a better approximation than simple linear regression. Let us find out by fitting the two models. With fitting done, let us draw simple linear regression and LOWESS lines on the graph. Visually we can see that LOWESS can fit the data better. This is because the price drop is steeper initially, which then starts to flatten out as the distance from the nearest MRT goes beyond 1000. Simple linear regression has only one slope parameter meaning that it has the same steepness of the curve throughout. Meanwhile, LOWESS can adjust the curve's steepness at various points, producing a better fit than that of simple linear regression. Let us now zoom in on the graph to see the difference between the two LOWESS models. We can clearly see that setting the fraction hyperparameter to 1/5 makes LOWESS a bit too sensitive to the local data fluctuations, giving us a model that is overfitting. This is the opposite of the sine wave example, emphasizing that we need to be careful with hyperparameters and ensure that we choose the best values for the given data. Unfortunately, the lowess algorithm from statsmodels does not provide us with a predict() method. Hence, we cannot use the model that we have built to give us y values for the new set of x values (i.e., data points that were not in the original data). Fortunately, we have a solution for that. We can use the interpolation method from the scipy library. First, we create a function using the interp1d method by passing x and y values from the LOWESS output. Then, we use that newly created function to take new x values and generate y values for them. Note, in the below code, we used a couple of different options for interpolation. Differences are explained in the code comments. One of them is drawing a line between the two nearest points and calculating a new y value for a given x value, and the other one simply taking the y value from the nearest available point. At the same time, we have set fill_value to ‘extrapolate,’ which means that if you pass an x value outside of the original range (like 6400 in the example below), you will still get a result based on the extrapolated line. Without it, the algorithm would return ‘NaN.’ However, be careful with extrapolation as you may not always get good results for values far outside the original data range. Printed output of ynew_linear and ynew_nearest:[45.17484583 38.88067785 33.63954152 30.70005122 28.90428712 27.31620311 26.02059902 11.5419846][45.02258129 38.86385487 33.43419447 31.09566559 28.91596696 27.30837281 26.0121316 11.55394747] LOWESS is not something that you may want to use in all of your regression models as it follows a non-parametric approach and is quite computationally intensive. However, it is a good way to model a relationship between two variables that do not fit a predefined distribution and have a non-linear relationship. I hope you enjoyed this story and can use the code and explanations for your own data science projects. If you have any feedback or questions, feel free to reach out. Cheers! 👏Saul Dobilas If you have already spent your learning budget for this month, please remember me next time. My personalized link to join Medium is: solclover.com Related stories you may like:
[ { "code": null, "e": 308, "s": 171, "text": "Machine Learning is making huge leaps forward, with an increasing number of algorithms enabling us to solve complex real-world problems." }, { "code": null, "e": 547, "s": 308, "text": "This story is part of a deep dive series explaining the mechanics of Machine Learning algorithms. In addition to giving you an understanding of how ML algorithms work, it also provides you with Python examples to build your own ML models." }, { "code": null, "e": 598, "s": 547, "text": "What category of algorithms does LOWESS belong to?" }, { "code": null, "e": 652, "s": 598, "text": "How does Locally Weighted Scatterplot Smoothing work?" }, { "code": null, "e": 726, "s": 652, "text": "How can I use LOWESS to identify patterns and predict new data in Python?" }, { "code": null, "e": 957, "s": 726, "text": "Locally Weighted Scatterplot Smoothing sits within the family of regression algorithms under the umbrella of Supervised Learning. This means that you need a set of labeled data with a numerical target variable to train your model." }, { "code": null, "e": 1064, "s": 957, "text": "The below graph is interactive, so make sure to click on different categories to enlarge and reveal more👇." }, { "code": null, "e": 1177, "s": 1064, "text": "If you enjoy Data Science and Machine Learning, please subscribe to get an email whenever I publish a new story." }, { "code": null, "e": 1571, "s": 1177, "text": "Since LOWESS is a non-parametric fitting technique, you do not need to assume that data follows any specific distribution. However, at the same time, non-parametric fitting means that at the end, you will not have a global equation for you to use to predict the values of new data points. Not to worry, though, as I provide a workaround to this issue in the Python section later in this story." }, { "code": null, "e": 1673, "s": 1571, "text": "Given the above advantages and disadvantages, LOWESS is often used to perform the following analysis:" }, { "code": null, "e": 1935, "s": 1673, "text": "A regression analysis where simple linear regression cannot produce a line of good fit due to data attributes not following a linear relationship. Note, a special case of multiple linear regression known as polynomial regression could also be used in this case." }, { "code": null, "e": 2028, "s": 1935, "text": "Data exploration and analysis in the social sciences, such as elections and voting behavior." }, { "code": null, "e": 2201, "s": 2028, "text": "Fitting a line to a scatter plot or time plot where noisy data values, sparse data points, or weak interrelationships interfere with your ability to see a line of best fit." }, { "code": null, "e": 2489, "s": 2201, "text": "While writing this story, I have assumed that you are already familiar with the ordinary least squares (OLS) regression. Hence, in this section, I only intend to provide an intuitive explanation of how LOWESS splits up the data to perform linear regression on local sections of the data." }, { "code": null, "e": 2594, "s": 2489, "text": "If you would like a refresher on OLS regression, feel free to take a look at my linear regression story:" }, { "code": null, "e": 2617, "s": 2594, "text": "towardsdatascience.com" }, { "code": null, "e": 2793, "s": 2617, "text": "Said that one important addition to LOWESS over OLS is that it applies weightings as you might have guessed from the algorithm’s name — Locally Weighted Scatterplot Smoothing." }, { "code": null, "e": 2906, "s": 2793, "text": "Typically, the algorithm uses a tri-cube weight function (see below), although other functions can also be used." }, { "code": null, "e": 3075, "s": 2906, "text": "Weight functionw(x) = (1 - |d|3)3, where d is is the distance of a given data point from the point on the curve being fitted, scaled to lie in the range between 0 and 1" }, { "code": null, "e": 3417, "s": 3075, "text": "The weight function gives the most weight to the data points nearest to the point of estimation and the least weight to the data points that are furthest away. It is based on the idea that points near each other in the explanatory variable space are more likely to be related to each other in a simple way than points that are further apart." }, { "code": null, "e": 3633, "s": 3417, "text": "We will use an example to illustrate how LOWESS works. Let us start by creating a scatterplot where the data points follow a sine wave pattern, but they have some random noise added, making the pattern less obvious." }, { "code": null, "e": 3770, "s": 3633, "text": "After that, we perform a LOWESS regression analysis a couple of times using different hyperparameters and add LOWESS curves to the plot:" }, { "code": null, "e": 4060, "s": 3770, "text": "As you can see, there is a lot of noise in the data, with the relationship between x and y being non-linear (periodic, in fact). Clearly, simple linear regression would not give us a meaningful result here since it can only produce a straight line (unlike LOWESS or polynomial regression)." }, { "code": null, "e": 4289, "s": 4060, "text": "The first thing that LOWESS does is selects a subset of the data. We can control the size of the subsets by specifying the ‘fraction’ hyperparameter. The two lines that we plotted above have hyperparameter values of 2/3 and 1/5." }, { "code": null, "e": 4656, "s": 4289, "text": "Let’s take the orange line as an example, with a default hyperparameter value of 2/3. This means that the LOWESS algorithm takes a subset of two-thirds of the entire data and performs a weighted linear least squares regression over the span of that data while moving by one point at a time and repeating the same process until it has gone through every single point." }, { "code": null, "e": 5086, "s": 4656, "text": "Starting from the very left and going right one point at a time, we can see how the orange line remains straight until x=-2.1. This is because the entire data ranges from -2π to +2π (-6.28 to +6.28) with an initial two-thirds window ranging from -6.28 to +2.1. Hence, only when the algorithm goes beyond -2.1 (midpoint between -6.28 and +2.1), it starts encountering new data points within its window, changing the curve's slope." }, { "code": null, "e": 5523, "s": 5086, "text": "If we now look at the red line (frac=1/5), we can see how narrowing the window to one-fifth of the data makes the algorithm more sensitive towards local trends. The featured gif image at the beginning of this story illustrates how this red line (frac=1/5) moves across the data performing weighted linear regression. This is the same process as described for the orange line (frac=2/3) except, the window the algorithm sees is narrower." }, { "code": null, "e": 5882, "s": 5523, "text": "While in this example, making the window smaller helped us get a better approximation of the sine wave, it is not always desirable to make a ‘fraction’ hyperparameter smaller. This largely depends on the data you are analyzing, as making a window smaller runs a risk of overfitting. You will see this in my next example, where 2/3 works much better than 1/5." }, { "code": null, "e": 6007, "s": 5882, "text": "Now that you have a general understating of how the algorithm works, it is time to have some fun and build a model in Python" }, { "code": null, "e": 6034, "s": 6007, "text": "We will use the following:" }, { "code": null, "e": 6063, "s": 6034, "text": "House price data from Kaggle" }, { "code": null, "e": 6167, "s": 6063, "text": "Scikit-learn library to build a simple linear regression model (so we can compare the result to LOWESS)" }, { "code": null, "e": 6208, "s": 6167, "text": "statsmodels library for LOWESS algorithm" }, { "code": null, "e": 6242, "s": 6208, "text": "Plotly library for visualizations" }, { "code": null, "e": 6279, "s": 6242, "text": "scipy library for data interpolation" }, { "code": null, "e": 6296, "s": 6279, "text": "Pandas and Numpy" }, { "code": null, "e": 6346, "s": 6296, "text": "Let us start by importing the required libraries." }, { "code": null, "e": 6546, "s": 6346, "text": "Next, we download and ingest the data that we will use to build our LOWESS and linear regression models.(source: https://www.kaggle.com/quantbruce/real-estate-price-prediction?select=Real+estate.csv)" }, { "code": null, "e": 6752, "s": 6546, "text": "We will take ‘X3 distance to the nearest MRT station’ as our input (independent) variable and ‘Y house price of unit area’ as our output (dependent) variable and create a scatterplot to visualize the data." }, { "code": null, "e": 6908, "s": 6752, "text": "We can clearly see the relationship between x and y with the house price (per unit area) decreasing as the distance from the nearest MRT station increases." }, { "code": null, "e": 7091, "s": 6908, "text": "Since the relationship is somewhat linear, the question is whether LOWESS can give us a better approximation than simple linear regression. Let us find out by fitting the two models." }, { "code": null, "e": 7178, "s": 7091, "text": "With fitting done, let us draw simple linear regression and LOWESS lines on the graph." }, { "code": null, "e": 7376, "s": 7178, "text": "Visually we can see that LOWESS can fit the data better. This is because the price drop is steeper initially, which then starts to flatten out as the distance from the nearest MRT goes beyond 1000." }, { "code": null, "e": 7626, "s": 7376, "text": "Simple linear regression has only one slope parameter meaning that it has the same steepness of the curve throughout. Meanwhile, LOWESS can adjust the curve's steepness at various points, producing a better fit than that of simple linear regression." }, { "code": null, "e": 7711, "s": 7626, "text": "Let us now zoom in on the graph to see the difference between the two LOWESS models." }, { "code": null, "e": 8051, "s": 7711, "text": "We can clearly see that setting the fraction hyperparameter to 1/5 makes LOWESS a bit too sensitive to the local data fluctuations, giving us a model that is overfitting. This is the opposite of the sine wave example, emphasizing that we need to be careful with hyperparameters and ensure that we choose the best values for the given data." }, { "code": null, "e": 8303, "s": 8051, "text": "Unfortunately, the lowess algorithm from statsmodels does not provide us with a predict() method. Hence, we cannot use the model that we have built to give us y values for the new set of x values (i.e., data points that were not in the original data)." }, { "code": null, "e": 8405, "s": 8303, "text": "Fortunately, we have a solution for that. We can use the interpolation method from the scipy library." }, { "code": null, "e": 8603, "s": 8405, "text": "First, we create a function using the interp1d method by passing x and y values from the LOWESS output. Then, we use that newly created function to take new x values and generate y values for them." }, { "code": null, "e": 8923, "s": 8603, "text": "Note, in the below code, we used a couple of different options for interpolation. Differences are explained in the code comments. One of them is drawing a line between the two nearest points and calculating a new y value for a given x value, and the other one simply taking the y value from the nearest available point." }, { "code": null, "e": 9318, "s": 8923, "text": "At the same time, we have set fill_value to ‘extrapolate,’ which means that if you pass an x value outside of the original range (like 6400 in the example below), you will still get a result based on the extrapolated line. Without it, the algorithm would return ‘NaN.’ However, be careful with extrapolation as you may not always get good results for values far outside the original data range." }, { "code": null, "e": 9559, "s": 9318, "text": "Printed output of ynew_linear and ynew_nearest:[45.17484583 38.88067785 33.63954152 30.70005122 28.90428712 27.31620311 26.02059902 11.5419846][45.02258129 38.86385487 33.43419447 31.09566559 28.91596696 27.30837281 26.0121316 11.55394747]" }, { "code": null, "e": 9871, "s": 9559, "text": "LOWESS is not something that you may want to use in all of your regression models as it follows a non-parametric approach and is quite computationally intensive. However, it is a good way to model a relationship between two variables that do not fit a predefined distribution and have a non-linear relationship." }, { "code": null, "e": 10038, "s": 9871, "text": "I hope you enjoyed this story and can use the code and explanations for your own data science projects. If you have any feedback or questions, feel free to reach out." }, { "code": null, "e": 10060, "s": 10038, "text": "Cheers! 👏Saul Dobilas" }, { "code": null, "e": 10193, "s": 10060, "text": "If you have already spent your learning budget for this month, please remember me next time. My personalized link to join Medium is:" }, { "code": null, "e": 10207, "s": 10193, "text": "solclover.com" } ]
bitset count() in C++ STL - GeeksforGeeks
18 Jun, 2018 bitset::count() is an inbuilt STL in C++ which returns the number of set bits in the binary representation of a number. Syntax: int count() Parameter: The function accepts no parameter. Return Value: The function returns the number of set bits. It returns the total number of ones or the number of set bits in the binary representation of the number if the passed number is an integer. Below programs illustrates the bitset::count() function. Program 1: // CPP program to illustrate the// bitset::count() function#include <bits/stdc++.h>using namespace std; int main(){ // Initialisation of a bitset bitset<4> b1(string("1100")); bitset<6> b2(string("001000")); // Function to count the // number of set bits in b1 int result1 = b1.count(); cout << b1 << " has " << result1 << " set bit\n"; // Function to count the // number of set bits in b2 int result2 = b2.count(); cout << b2 << " has " << result2 << " set bit"; return 0;} 1100 has 2 set bit 001000 has 1 set bit Program 2: // CPP program to illustrate the// bitset::count() function// when the input is an integer#include <bits/stdc++.h>using namespace std; int main(){ // Initialisation of a bitset bitset<4> b1(16); bitset<4> b2(18); // Function to count the // number of set bits in b1 int result1 = b1.count(); cout << b1 << " has " << result1 << " set bit\n"; // Function to count the // number of set bits in b2 int result2 = b2.count(); cout << b2 << " has " << result2 << " set bit"; return 0;} 0000 has 0 set bit 0010 has 1 set bit CPP-bitset CPP-Functions STL C++ C++ Programs STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Iterators in C++ STL Operator Overloading in C++ Friend class and function in C++ Polymorphism in C++ Inline Functions in C++ Header files in C/C++ and its uses How to return multiple values from a function in C or C++? C++ Program for QuickSort C++ program for hashing with chaining delete keyword in C++
[ { "code": null, "e": 24043, "s": 24015, "text": "\n18 Jun, 2018" }, { "code": null, "e": 24163, "s": 24043, "text": "bitset::count() is an inbuilt STL in C++ which returns the number of set bits in the binary representation of a number." }, { "code": null, "e": 24171, "s": 24163, "text": "Syntax:" }, { "code": null, "e": 24185, "s": 24171, "text": "int count() \n" }, { "code": null, "e": 24231, "s": 24185, "text": "Parameter: The function accepts no parameter." }, { "code": null, "e": 24431, "s": 24231, "text": "Return Value: The function returns the number of set bits. It returns the total number of ones or the number of set bits in the binary representation of the number if the passed number is an integer." }, { "code": null, "e": 24488, "s": 24431, "text": "Below programs illustrates the bitset::count() function." }, { "code": null, "e": 24499, "s": 24488, "text": "Program 1:" }, { "code": "// CPP program to illustrate the// bitset::count() function#include <bits/stdc++.h>using namespace std; int main(){ // Initialisation of a bitset bitset<4> b1(string(\"1100\")); bitset<6> b2(string(\"001000\")); // Function to count the // number of set bits in b1 int result1 = b1.count(); cout << b1 << \" has \" << result1 << \" set bit\\n\"; // Function to count the // number of set bits in b2 int result2 = b2.count(); cout << b2 << \" has \" << result2 << \" set bit\"; return 0;}", "e": 25033, "s": 24499, "text": null }, { "code": null, "e": 25074, "s": 25033, "text": "1100 has 2 set bit\n001000 has 1 set bit\n" }, { "code": null, "e": 25085, "s": 25074, "text": "Program 2:" }, { "code": "// CPP program to illustrate the// bitset::count() function// when the input is an integer#include <bits/stdc++.h>using namespace std; int main(){ // Initialisation of a bitset bitset<4> b1(16); bitset<4> b2(18); // Function to count the // number of set bits in b1 int result1 = b1.count(); cout << b1 << \" has \" << result1 << \" set bit\\n\"; // Function to count the // number of set bits in b2 int result2 = b2.count(); cout << b2 << \" has \" << result2 << \" set bit\"; return 0;}", "e": 25624, "s": 25085, "text": null }, { "code": null, "e": 25663, "s": 25624, "text": "0000 has 0 set bit\n0010 has 1 set bit\n" }, { "code": null, "e": 25674, "s": 25663, "text": "CPP-bitset" }, { "code": null, "e": 25688, "s": 25674, "text": "CPP-Functions" }, { "code": null, "e": 25692, "s": 25688, "text": "STL" }, { "code": null, "e": 25696, "s": 25692, "text": "C++" }, { "code": null, "e": 25709, "s": 25696, "text": "C++ Programs" }, { "code": null, "e": 25713, "s": 25709, "text": "STL" }, { "code": null, "e": 25717, "s": 25713, "text": "CPP" }, { "code": null, "e": 25815, "s": 25717, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25824, "s": 25815, "text": "Comments" }, { "code": null, "e": 25837, "s": 25824, "text": "Old Comments" }, { "code": null, "e": 25858, "s": 25837, "text": "Iterators in C++ STL" }, { "code": null, "e": 25886, "s": 25858, "text": "Operator Overloading in C++" }, { "code": null, "e": 25919, "s": 25886, "text": "Friend class and function in C++" }, { "code": null, "e": 25939, "s": 25919, "text": "Polymorphism in C++" }, { "code": null, "e": 25963, "s": 25939, "text": "Inline Functions in C++" }, { "code": null, "e": 25998, "s": 25963, "text": "Header files in C/C++ and its uses" }, { "code": null, "e": 26057, "s": 25998, "text": "How to return multiple values from a function in C or C++?" }, { "code": null, "e": 26083, "s": 26057, "text": "C++ Program for QuickSort" }, { "code": null, "e": 26121, "s": 26083, "text": "C++ program for hashing with chaining" } ]
Perl | Quoted, Interpolated and Escaped Strings
24 Dec, 2021 A string in Perl is a scalar variable and start with a ($) sign and it can contain alphabets, numbers, special characters. The string can consist of a single word, a group of words or a multi-line paragraph. The String is defined by the user within a single quote (‘) or double quote (“). In Perl, strings can be put in between double-quotes (” “) or in between single-quotes (‘ ‘). However, strings defined in single-quotes and those defined in double-quotes are treated differently.Double-quoted strings: Double-quoted strings are interpolated i.e. variable names (scalars, arrays, and hashes) are replaced by their original values and escape sequences (like /t, /n, etc.) do their work. qq operator can also be used in place of double-quoted strings.Single-quoted strings: Single-quoted strings are not interpolated. They are interpreted as is, with no modifications whatsoever. q operator in Perl provides the same use as the single-quoted string.Example: Perl #!/usr/bin/perl # An array of integers from 1 to 10@list = (1..10); # Non-interpolated string$strng1 = 'Using Single quotes: @list'; # Interpolated string$strng2 = "Using Double-quotes: @list";print("$strng1\n$strng2"); Using Single quotes: @list Using Double-quotes: 1 2 3 4 5 6 7 8 9 10 Interpolation of Strings with the use of double quotes can sometimes become tricky because some strings contain symbols which might be of no use when interpolated. For example: ‘@’ symbol used in writing email addresses. When an email address is to be stored in a double-quoted string, then the ‘at’ (@) sign is automatically interpolated and is taken to be the beginning of the name of an array and is substituted by it. If an array with that name is found then it will replace the array name with the array values, or it will be left blank if an array with that name doesn’t exist.Example: Perl #!/usr/bin/perl # Assigning a variable with an email address# using double-quotes$email = "GeeksforGeeks0402@gmail.com"; # Printing the interpolated stringprint($email); GeeksforGeeks0402.com In the above example, the string ($email) is interpolated and @gmail is substituted by an array named ‘@gmail’ but since no array with such name is found, @gmail is removed but is not substituted and hence “GeeksforGeeks0402.com” is printed.In the below example, @gmail has been pre-defined and hence is substituted in place of @gmail. Example: Perl #!/usr/bin/perl # Pre-defining the array@gmail = (a..g); # Assigning a variable with an email# address using double-quotes$email = "GeeksforGeeks0402@gmail.com"; # Printing the interpolated stringprint($email); GeeksforGeeks0402a b c d e f g.com This can be corrected by using single quotes in place of double quotes. Assigning the string to the variable with the use of single quotes will remove the interpolation and hence the ‘@’ will not be considered as array declaration. Example: Perl #!/usr/bin/perl # Assigning a variable with an email address# using single-quotes$email = 'GeeksforGeeks0402@gmail.com'; # Printing the non-interpolated stringprint($email); GeeksforGeeks0402@gmail.com Above solution to the interpolation problem contains a drawback. What if there’s a need to substitute a variable’s value in the string along with the use of ‘@’ symbol. Then this method will be of no use as single quotes won’t allow the substitution of variable’s value. To overcome this situation, the escape character i.e. the backslash(\) is used. The backslash is inserted just before the ‘@’ as shown below: Perl #!/usr/bin/perl # Assigning a variable with an email# address using double-quotes# Note: Using '\' to escape the# interpolation of '@'$email = "GeeksforGeeks0402\@gmail.com"; # Printing the interpolated stringprint($email); # variable to be substituted$name = "GeeksforGeeks"; # variable to store the string$email2 = "\n$name\@gmail.com"; # Printing the interpolated stringprint($email2); GeeksforGeeks0402@gmail.com GeeksforGeeks@gmail.com The backslash is the escape character and is used to make use of escape sequences. When there is a need to insert the escape character in an interpolated string, the same backslash is used, to escape the substitution of escape character with ” (blank). This allows the use of escape character in the interpolated string.Example: Perl #!/usr/bin/perl # Using Two escape characters to avoid# the substitution of escape(\) with blank$string1 = "Using the escape(\\) character"; # Printing the Interpolated stringprint($string1); Using the escape(\) character Use of double quotes in a string signifies the end of the string and hence, cannot be inserted directly. To insert double quotes in an interpolated string, backslash is used just before the double quotes to escape its interpolation.Example: Perl #!/usr/bin/perl # Escaping double-quotes with '\'$string = "This page is \"Geeks For Geeks\"."; # Printing the interpolated stringprint($string); This page is "Geeks For Geeks". sumitgumber28 simmytarika5 Perl-String Picked Perl Perl Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Perl | split() Function Perl | push() Function Perl | chomp() Function Perl | substr() function Perl | grep() Function Perl | exists() Function Perl Tutorial - Learn Perl With Examples Perl | length() Function Perl | Subroutines or Functions Use of print() and say() in Perl
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Dec, 2021" }, { "code": null, "e": 321, "s": 28, "text": "A string in Perl is a scalar variable and start with a ($) sign and it can contain alphabets, numbers, special characters. The string can consist of a single word, a group of words or a multi-line paragraph. The String is defined by the user within a single quote (‘) or double quote (“). " }, { "code": null, "e": 996, "s": 321, "text": " In Perl, strings can be put in between double-quotes (” “) or in between single-quotes (‘ ‘). However, strings defined in single-quotes and those defined in double-quotes are treated differently.Double-quoted strings: Double-quoted strings are interpolated i.e. variable names (scalars, arrays, and hashes) are replaced by their original values and escape sequences (like /t, /n, etc.) do their work. qq operator can also be used in place of double-quoted strings.Single-quoted strings: Single-quoted strings are not interpolated. They are interpreted as is, with no modifications whatsoever. q operator in Perl provides the same use as the single-quoted string.Example: " }, { "code": null, "e": 1001, "s": 996, "text": "Perl" }, { "code": "#!/usr/bin/perl # An array of integers from 1 to 10@list = (1..10); # Non-interpolated string$strng1 = 'Using Single quotes: @list'; # Interpolated string$strng2 = \"Using Double-quotes: @list\";print(\"$strng1\\n$strng2\");", "e": 1221, "s": 1001, "text": null }, { "code": null, "e": 1291, "s": 1221, "text": "Using Single quotes: @list \nUsing Double-quotes: 1 2 3 4 5 6 7 8 9 10" }, { "code": null, "e": 1893, "s": 1297, "text": " Interpolation of Strings with the use of double quotes can sometimes become tricky because some strings contain symbols which might be of no use when interpolated. For example: ‘@’ symbol used in writing email addresses. When an email address is to be stored in a double-quoted string, then the ‘at’ (@) sign is automatically interpolated and is taken to be the beginning of the name of an array and is substituted by it. If an array with that name is found then it will replace the array name with the array values, or it will be left blank if an array with that name doesn’t exist.Example: " }, { "code": null, "e": 1898, "s": 1893, "text": "Perl" }, { "code": "#!/usr/bin/perl # Assigning a variable with an email address# using double-quotes$email = \"GeeksforGeeks0402@gmail.com\"; # Printing the interpolated stringprint($email);", "e": 2068, "s": 1898, "text": null }, { "code": null, "e": 2090, "s": 2068, "text": "GeeksforGeeks0402.com" }, { "code": null, "e": 2439, "s": 2092, "text": "In the above example, the string ($email) is interpolated and @gmail is substituted by an array named ‘@gmail’ but since no array with such name is found, @gmail is removed but is not substituted and hence “GeeksforGeeks0402.com” is printed.In the below example, @gmail has been pre-defined and hence is substituted in place of @gmail. Example: " }, { "code": null, "e": 2444, "s": 2439, "text": "Perl" }, { "code": "#!/usr/bin/perl # Pre-defining the array@gmail = (a..g); # Assigning a variable with an email# address using double-quotes$email = \"GeeksforGeeks0402@gmail.com\"; # Printing the interpolated stringprint($email);", "e": 2655, "s": 2444, "text": null }, { "code": null, "e": 2690, "s": 2655, "text": "GeeksforGeeks0402a b c d e f g.com" }, { "code": null, "e": 2935, "s": 2692, "text": "This can be corrected by using single quotes in place of double quotes. Assigning the string to the variable with the use of single quotes will remove the interpolation and hence the ‘@’ will not be considered as array declaration. Example: " }, { "code": null, "e": 2940, "s": 2935, "text": "Perl" }, { "code": "#!/usr/bin/perl # Assigning a variable with an email address# using single-quotes$email = 'GeeksforGeeks0402@gmail.com'; # Printing the non-interpolated stringprint($email);", "e": 3114, "s": 2940, "text": null }, { "code": null, "e": 3142, "s": 3114, "text": "GeeksforGeeks0402@gmail.com" }, { "code": null, "e": 3559, "s": 3144, "text": "Above solution to the interpolation problem contains a drawback. What if there’s a need to substitute a variable’s value in the string along with the use of ‘@’ symbol. Then this method will be of no use as single quotes won’t allow the substitution of variable’s value. To overcome this situation, the escape character i.e. the backslash(\\) is used. The backslash is inserted just before the ‘@’ as shown below: " }, { "code": null, "e": 3564, "s": 3559, "text": "Perl" }, { "code": "#!/usr/bin/perl # Assigning a variable with an email# address using double-quotes# Note: Using '\\' to escape the# interpolation of '@'$email = \"GeeksforGeeks0402\\@gmail.com\"; # Printing the interpolated stringprint($email); # variable to be substituted$name = \"GeeksforGeeks\"; # variable to store the string$email2 = \"\\n$name\\@gmail.com\"; # Printing the interpolated stringprint($email2);", "e": 3953, "s": 3564, "text": null }, { "code": null, "e": 4005, "s": 3953, "text": "GeeksforGeeks0402@gmail.com\nGeeksforGeeks@gmail.com" }, { "code": null, "e": 4344, "s": 4011, "text": " The backslash is the escape character and is used to make use of escape sequences. When there is a need to insert the escape character in an interpolated string, the same backslash is used, to escape the substitution of escape character with ” (blank). This allows the use of escape character in the interpolated string.Example: " }, { "code": null, "e": 4349, "s": 4344, "text": "Perl" }, { "code": "#!/usr/bin/perl # Using Two escape characters to avoid# the substitution of escape(\\) with blank$string1 = \"Using the escape(\\\\) character\"; # Printing the Interpolated stringprint($string1);", "e": 4541, "s": 4349, "text": null }, { "code": null, "e": 4571, "s": 4541, "text": "Using the escape(\\) character" }, { "code": null, "e": 4822, "s": 4577, "text": " Use of double quotes in a string signifies the end of the string and hence, cannot be inserted directly. To insert double quotes in an interpolated string, backslash is used just before the double quotes to escape its interpolation.Example: " }, { "code": null, "e": 4827, "s": 4822, "text": "Perl" }, { "code": "#!/usr/bin/perl # Escaping double-quotes with '\\'$string = \"This page is \\\"Geeks For Geeks\\\".\"; # Printing the interpolated stringprint($string);", "e": 4973, "s": 4827, "text": null }, { "code": null, "e": 5005, "s": 4973, "text": "This page is \"Geeks For Geeks\"." }, { "code": null, "e": 5021, "s": 5007, "text": "sumitgumber28" }, { "code": null, "e": 5034, "s": 5021, "text": "simmytarika5" }, { "code": null, "e": 5046, "s": 5034, "text": "Perl-String" }, { "code": null, "e": 5053, "s": 5046, "text": "Picked" }, { "code": null, "e": 5058, "s": 5053, "text": "Perl" }, { "code": null, "e": 5063, "s": 5058, "text": "Perl" }, { "code": null, "e": 5161, "s": 5063, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5185, "s": 5161, "text": "Perl | split() Function" }, { "code": null, "e": 5208, "s": 5185, "text": "Perl | push() Function" }, { "code": null, "e": 5232, "s": 5208, "text": "Perl | chomp() Function" }, { "code": null, "e": 5257, "s": 5232, "text": "Perl | substr() function" }, { "code": null, "e": 5280, "s": 5257, "text": "Perl | grep() Function" }, { "code": null, "e": 5305, "s": 5280, "text": "Perl | exists() Function" }, { "code": null, "e": 5346, "s": 5305, "text": "Perl Tutorial - Learn Perl With Examples" }, { "code": null, "e": 5371, "s": 5346, "text": "Perl | length() Function" }, { "code": null, "e": 5403, "s": 5371, "text": "Perl | Subroutines or Functions" } ]
Overview of Just a Bunch Of Disks (JBOD)
07 May, 2021 Just a Bunch Of Disks : JBOD (stands for “Just a Bunch Of Disks”) is referred as the collection of hard disks with one single storage enclosure that are not configured to acts as Redundant Array of Independent Disks (RAID array). The multiple disks in array are connected to a single server that provides higher storage capacity. JBODs make the disk appear to be single one by combining all the disks. Like in RAID system the data is stored redundantly in multiple disks which appear as single disk in operating system. Advantages of JBOD : Some possible benefits from JBOD are : JBOD helps in minimizing data loss, e.g. we can combine 10GB drive and 40GB drive to get a 50GB volume from JBOD. It’s a very small advantage as there may be a issue while expanding the existing system provided nowadays drives are cheap. With JBOD we may recover missing files, if drive falls in JBOD enclosure. This depends on how operating system manages the disk. Considering JBOD recovery can be difficult, it is a negligible disadvantage. The SATA disks and controllers are cheap in nature which makes JBOD cost effective as compared to RAID. Disadvantages in JBOD : With multiple drives acting, there is no increase in drive performance. If by mistake any disk is lost, you should search for backups. If there is no backup the data is permanently gone. JBOD v/s RAID : JBOD and RAID are the two major data storage configurations. Some differences & similarities between JBOD & RAID includes: Similarity : Both are applicable on data storage.Both JBOD and RAID enhance the usage of disk space.In RAID data stored in multiple disks which will appear on operating systems like a single disk, similarly in case of JBOD also the disks are displayed on operating system like a single disk. Both are applicable on data storage. Both JBOD and RAID enhance the usage of disk space. In RAID data stored in multiple disks which will appear on operating systems like a single disk, similarly in case of JBOD also the disks are displayed on operating system like a single disk. Difference : RAID are comparatively expensive than JBOD as RAID uses components like SATA disks and controllers which are highly priced.JBOD allows room for combination of drives of mixed sizes while RAID configurations allow only similar sized disks to be used in array.Mostly JBOD are preferred over RAID as they are easily to scale which is done by just adding another drive.RAID has certain features like supporting hard disk failure, enhancing performance, which are missing in JBOD. RAID are comparatively expensive than JBOD as RAID uses components like SATA disks and controllers which are highly priced. JBOD allows room for combination of drives of mixed sizes while RAID configurations allow only similar sized disks to be used in array. Mostly JBOD are preferred over RAID as they are easily to scale which is done by just adding another drive. RAID has certain features like supporting hard disk failure, enhancing performance, which are missing in JBOD. Which configuration is right for you ? If there is a need of huge amount of local storage for a application, JBOD should be chosen. With NVME SSDs, JBOD jobs are fast in nature. In RAID there is limited data storage as data undergo parity. In case of RAID, RAID 0 is the only level where total storage capacity is preserved, but we have to lose all data from each drive while removing disk drives from RAID 0. RAIDs are more expensive and if any drive dies in RAID array it will take long time to rebuilt. So, with all this in view JBOD might be a right choice for you which allow easy swaps, fast read and write speeds, more data storage etc. DBMS DBMS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Types of Functional dependencies in DBMS MySQL | Regular expressions (Regexp) What is Temporary Table in SQL? Difference between OLAP and OLTP in DBMS Difference between Where and Having Clause in SQL SQL | DDL, DML, TCL and DCL Introduction of Relational Algebra in DBMS Relational Model in DBMS KDD Process in Data Mining Difference between Star Schema and Snowflake Schema
[ { "code": null, "e": 28, "s": 0, "text": "\n07 May, 2021" }, { "code": null, "e": 52, "s": 28, "text": "Just a Bunch Of Disks :" }, { "code": null, "e": 358, "s": 52, "text": "JBOD (stands for “Just a Bunch Of Disks”) is referred as the collection of hard disks with one single storage enclosure that are not configured to acts as Redundant Array of Independent Disks (RAID array). The multiple disks in array are connected to a single server that provides higher storage capacity." }, { "code": null, "e": 548, "s": 358, "text": "JBODs make the disk appear to be single one by combining all the disks. Like in RAID system the data is stored redundantly in multiple disks which appear as single disk in operating system." }, { "code": null, "e": 569, "s": 548, "text": "Advantages of JBOD :" }, { "code": null, "e": 608, "s": 569, "text": "Some possible benefits from JBOD are :" }, { "code": null, "e": 846, "s": 608, "text": "JBOD helps in minimizing data loss, e.g. we can combine 10GB drive and 40GB drive to get a 50GB volume from JBOD. It’s a very small advantage as there may be a issue while expanding the existing system provided nowadays drives are cheap." }, { "code": null, "e": 1052, "s": 846, "text": "With JBOD we may recover missing files, if drive falls in JBOD enclosure. This depends on how operating system manages the disk. Considering JBOD recovery can be difficult, it is a negligible disadvantage." }, { "code": null, "e": 1156, "s": 1052, "text": "The SATA disks and controllers are cheap in nature which makes JBOD cost effective as compared to RAID." }, { "code": null, "e": 1180, "s": 1156, "text": "Disadvantages in JBOD :" }, { "code": null, "e": 1252, "s": 1180, "text": "With multiple drives acting, there is no increase in drive performance." }, { "code": null, "e": 1367, "s": 1252, "text": "If by mistake any disk is lost, you should search for backups. If there is no backup the data is permanently gone." }, { "code": null, "e": 1383, "s": 1367, "text": "JBOD v/s RAID :" }, { "code": null, "e": 1506, "s": 1383, "text": "JBOD and RAID are the two major data storage configurations. Some differences & similarities between JBOD & RAID includes:" }, { "code": null, "e": 1519, "s": 1506, "text": "Similarity :" }, { "code": null, "e": 1798, "s": 1519, "text": "Both are applicable on data storage.Both JBOD and RAID enhance the usage of disk space.In RAID data stored in multiple disks which will appear on operating systems like a single disk, similarly in case of JBOD also the disks are displayed on operating system like a single disk." }, { "code": null, "e": 1835, "s": 1798, "text": "Both are applicable on data storage." }, { "code": null, "e": 1887, "s": 1835, "text": "Both JBOD and RAID enhance the usage of disk space." }, { "code": null, "e": 2079, "s": 1887, "text": "In RAID data stored in multiple disks which will appear on operating systems like a single disk, similarly in case of JBOD also the disks are displayed on operating system like a single disk." }, { "code": null, "e": 2092, "s": 2079, "text": "Difference :" }, { "code": null, "e": 2568, "s": 2092, "text": "RAID are comparatively expensive than JBOD as RAID uses components like SATA disks and controllers which are highly priced.JBOD allows room for combination of drives of mixed sizes while RAID configurations allow only similar sized disks to be used in array.Mostly JBOD are preferred over RAID as they are easily to scale which is done by just adding another drive.RAID has certain features like supporting hard disk failure, enhancing performance, which are missing in JBOD." }, { "code": null, "e": 2692, "s": 2568, "text": "RAID are comparatively expensive than JBOD as RAID uses components like SATA disks and controllers which are highly priced." }, { "code": null, "e": 2828, "s": 2692, "text": "JBOD allows room for combination of drives of mixed sizes while RAID configurations allow only similar sized disks to be used in array." }, { "code": null, "e": 2936, "s": 2828, "text": "Mostly JBOD are preferred over RAID as they are easily to scale which is done by just adding another drive." }, { "code": null, "e": 3047, "s": 2936, "text": "RAID has certain features like supporting hard disk failure, enhancing performance, which are missing in JBOD." }, { "code": null, "e": 3086, "s": 3047, "text": "Which configuration is right for you ?" }, { "code": null, "e": 3691, "s": 3086, "text": "If there is a need of huge amount of local storage for a application, JBOD should be chosen. With NVME SSDs, JBOD jobs are fast in nature. In RAID there is limited data storage as data undergo parity. In case of RAID, RAID 0 is the only level where total storage capacity is preserved, but we have to lose all data from each drive while removing disk drives from RAID 0. RAIDs are more expensive and if any drive dies in RAID array it will take long time to rebuilt. So, with all this in view JBOD might be a right choice for you which allow easy swaps, fast read and write speeds, more data storage etc." }, { "code": null, "e": 3696, "s": 3691, "text": "DBMS" }, { "code": null, "e": 3701, "s": 3696, "text": "DBMS" }, { "code": null, "e": 3799, "s": 3701, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3840, "s": 3799, "text": "Types of Functional dependencies in DBMS" }, { "code": null, "e": 3877, "s": 3840, "text": "MySQL | Regular expressions (Regexp)" }, { "code": null, "e": 3909, "s": 3877, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 3950, "s": 3909, "text": "Difference between OLAP and OLTP in DBMS" }, { "code": null, "e": 4000, "s": 3950, "text": "Difference between Where and Having Clause in SQL" }, { "code": null, "e": 4028, "s": 4000, "text": "SQL | DDL, DML, TCL and DCL" }, { "code": null, "e": 4071, "s": 4028, "text": "Introduction of Relational Algebra in DBMS" }, { "code": null, "e": 4096, "s": 4071, "text": "Relational Model in DBMS" }, { "code": null, "e": 4123, "s": 4096, "text": "KDD Process in Data Mining" } ]
How to pad a string to get the determined length using JavaScript ?
31 Jul, 2019 Method 1: Using the padStart() method: The padStart() method can be used to pad a string with the specified characters to the specified length. It takes two parameters, the target length, and the string to be replaced with. The target length is the length of resulting string after the current string has been padded. The second parameter is the characters that the string would be padded. If a number is to be padded, it has to be first converted into a string by passing it to the String constructor. Then the padStart() method is used on this string. Syntax: String(strToPad).padStart(padLength, padChar) Example: <!DOCTYPE html><html> <head> <title> How to pad a string to get the determined length using JavaScript ? </title></head> <body> <h1 style="color: green">GeeksforGeeks</h1> <b> How to pad a string to get the determined length using JavaScript ? </b> <p> Padding the string 'abcdefg' to 10 characters: <span class="output"></span> </p> <p> Padding the string '1234' to 10 characters: <span class="output-2"></span> </p> <button onclick="pad()">Pad string</button> <script type="text/javascript"> function pad() { example1 = "abcdefg"; example2 = 1234; prepended_out = String(example1).padStart(10, '*'); prepended_out2 = String(example2).padStart(10, '^#'); document.querySelector('.output').textContent = prepended_out; document.querySelector('.output-2').textContent = prepended_out2; } </script></body> </html> Output: Before clicking the button: After clicking the button: Method 2: Custom function using repeat() and slice() method: The function has to be created with three arguments, the characters to be padded with, the length of the final padded string and the string to be padded. The character to be padded with and the string to be padded is first converted into a string. This is done by using the String() constructor and passing both the values to it. These are stored in two variables, padChar and originalString. The actual number of characters to be padded is determined by subtracting the length of the string needed with the length of the characters to be padded with. This is stored in a new variable, padLeft.The pad string that is added in front of the original string is created with the repeat() method. The repeat() method returns a new string which contains the specified number of copies of the string on which it was called. It accepts one parameter which is the number of copies to make. This method is called on the padChar string and the padLeft value is passed in this parameter. It creates the copies required for the string to be added in front of the original string. This is stored in the variable padString.A new string is created by concatenating the padString and the originalString. The slice() method is used on this new string to make the length equal to the length required. This is done by passing a negative value of the padLength. The final string is then returned. Example: <!DOCTYPE html><html> <head> <title> How to pad a string to get the determined length using JavaScript ? </title></head> <body> <h1 style="color: green">GeeksforGeeks</h1> <b> How to pad a string to get the determined length using JavaScript ? </b> <p> Padding the string 'abcdefg' to 10 characters: <span class="output"></span> </p> <p> Padding the string '1234' to 10 characters: <span class="output-2"></span> </p> <button onclick="pad()">Pad string</button> <script type="text/javascript"> function padStr(padChar, padLength, originalString) { // Convert the pad character and original // string to String padChar = String(padChar); originalString = String(originalString); // Calculate the length of padding characters padLeft = padLength - originalString.length; // Create the pad string padString = padChar.repeat(padLeft); // Add the pad string to the original string // slice it to the padLength if it exceeds // the pad length specified newString = (padString + originalString).slice(-padLength); return newString; } function pad() { example1 = "abcdefg"; example2 = 1234; prepended_out = padStr('*', 10, example1); prepended_out2 = padStr('^#', 10, example2); document.querySelector('.output').textContent = prepended_out; document.querySelector('.output-2').textContent = prepended_out2; } </script></body> </html> Output: Before clicking the button: After clicking the button: javascript-string Picked JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n31 Jul, 2019" }, { "code": null, "e": 418, "s": 28, "text": "Method 1: Using the padStart() method: The padStart() method can be used to pad a string with the specified characters to the specified length. It takes two parameters, the target length, and the string to be replaced with. The target length is the length of resulting string after the current string has been padded. The second parameter is the characters that the string would be padded." }, { "code": null, "e": 582, "s": 418, "text": "If a number is to be padded, it has to be first converted into a string by passing it to the String constructor. Then the padStart() method is used on this string." }, { "code": null, "e": 590, "s": 582, "text": "Syntax:" }, { "code": null, "e": 636, "s": 590, "text": "String(strToPad).padStart(padLength, padChar)" }, { "code": null, "e": 645, "s": 636, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title> How to pad a string to get the determined length using JavaScript ? </title></head> <body> <h1 style=\"color: green\">GeeksforGeeks</h1> <b> How to pad a string to get the determined length using JavaScript ? </b> <p> Padding the string 'abcdefg' to 10 characters: <span class=\"output\"></span> </p> <p> Padding the string '1234' to 10 characters: <span class=\"output-2\"></span> </p> <button onclick=\"pad()\">Pad string</button> <script type=\"text/javascript\"> function pad() { example1 = \"abcdefg\"; example2 = 1234; prepended_out = String(example1).padStart(10, '*'); prepended_out2 = String(example2).padStart(10, '^#'); document.querySelector('.output').textContent = prepended_out; document.querySelector('.output-2').textContent = prepended_out2; } </script></body> </html> ", "e": 1749, "s": 645, "text": null }, { "code": null, "e": 1757, "s": 1749, "text": "Output:" }, { "code": null, "e": 1785, "s": 1757, "text": "Before clicking the button:" }, { "code": null, "e": 1812, "s": 1785, "text": "After clicking the button:" }, { "code": null, "e": 2027, "s": 1812, "text": "Method 2: Custom function using repeat() and slice() method: The function has to be created with three arguments, the characters to be padded with, the length of the final padded string and the string to be padded." }, { "code": null, "e": 3249, "s": 2027, "text": "The character to be padded with and the string to be padded is first converted into a string. This is done by using the String() constructor and passing both the values to it. These are stored in two variables, padChar and originalString. The actual number of characters to be padded is determined by subtracting the length of the string needed with the length of the characters to be padded with. This is stored in a new variable, padLeft.The pad string that is added in front of the original string is created with the repeat() method. The repeat() method returns a new string which contains the specified number of copies of the string on which it was called. It accepts one parameter which is the number of copies to make. This method is called on the padChar string and the padLeft value is passed in this parameter. It creates the copies required for the string to be added in front of the original string. This is stored in the variable padString.A new string is created by concatenating the padString and the originalString. The slice() method is used on this new string to make the length equal to the length required. This is done by passing a negative value of the padLength. The final string is then returned." }, { "code": null, "e": 3258, "s": 3249, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title> How to pad a string to get the determined length using JavaScript ? </title></head> <body> <h1 style=\"color: green\">GeeksforGeeks</h1> <b> How to pad a string to get the determined length using JavaScript ? </b> <p> Padding the string 'abcdefg' to 10 characters: <span class=\"output\"></span> </p> <p> Padding the string '1234' to 10 characters: <span class=\"output-2\"></span> </p> <button onclick=\"pad()\">Pad string</button> <script type=\"text/javascript\"> function padStr(padChar, padLength, originalString) { // Convert the pad character and original // string to String padChar = String(padChar); originalString = String(originalString); // Calculate the length of padding characters padLeft = padLength - originalString.length; // Create the pad string padString = padChar.repeat(padLeft); // Add the pad string to the original string // slice it to the padLength if it exceeds // the pad length specified newString = (padString + originalString).slice(-padLength); return newString; } function pad() { example1 = \"abcdefg\"; example2 = 1234; prepended_out = padStr('*', 10, example1); prepended_out2 = padStr('^#', 10, example2); document.querySelector('.output').textContent = prepended_out; document.querySelector('.output-2').textContent = prepended_out2; } </script></body> </html>", "e": 5041, "s": 3258, "text": null }, { "code": null, "e": 5049, "s": 5041, "text": "Output:" }, { "code": null, "e": 5077, "s": 5049, "text": "Before clicking the button:" }, { "code": null, "e": 5104, "s": 5077, "text": "After clicking the button:" }, { "code": null, "e": 5122, "s": 5104, "text": "javascript-string" }, { "code": null, "e": 5129, "s": 5122, "text": "Picked" }, { "code": null, "e": 5140, "s": 5129, "text": "JavaScript" }, { "code": null, "e": 5157, "s": 5140, "text": "Web Technologies" }, { "code": null, "e": 5184, "s": 5157, "text": "Web technologies Questions" } ]
Largest palindrome which is product of two n-digit numbers
04 Jun, 2022 Given a value n, find out the largest palindrome number which is product of two n digit numbers. Examples : Input : n = 2 Output : 9009 9009 is the largest number which is product of two 2-digit numbers. 9009 = 91*99. Input : n = 3 Output : 906609 Below are steps to find the required number. Find a lower limit on n digit numbers. For example, for n = 2, lower_limit is 10.Find an upper limit on n digit numbers. For example, for n = 2, upper_limit is 99.Consider all pairs of numbers where ever number lies in range [lower_limit, upper_limit] Find a lower limit on n digit numbers. For example, for n = 2, lower_limit is 10. Find an upper limit on n digit numbers. For example, for n = 2, upper_limit is 99. Consider all pairs of numbers where ever number lies in range [lower_limit, upper_limit] Below is the implementation of above steps. C++ Java Python3 C# PHP Javascript // C++ problem to find out the// largest palindrome number which// is product of two n digit numbers#include <bits/stdc++.h>using namespace std; // Function to calculate largest// palindrome which is product of// two n-digits numbersint larrgestPalindrome(int n){ int upper_limit = pow(10,n) - 1; // largest number of n-1 digit. // One plus this number is lower // limit which is product of two numbers. int lower_limit = 1 + upper_limit / 10; // Initialize result int max_product = 0; for (int i = upper_limit; i >= lower_limit; i--) { for (int j = i; j >= lower_limit; j--) { // calculating product of // two n-digit numbers int product = i * j; if (product < max_product) break; int number = product; int reverse = 0; // calculating reverse of // product to check whether // it is palindrome or not while (number != 0) { reverse = reverse * 10 + number % 10; number /= 10; } // update new product if exist // and if greater than previous one if (product == reverse && product > max_product) max_product = product; } } return max_product;} // Driver codeint main(){ int n = 2; cout << larrgestPalindrome(n); return 0;} // Java problem to find out the// largest palindrome number// which is product of two// n digit numbers.import java.lang.Math; class GFG{ // Function to calculate largest // palindrome which isproduct of // two n-digits numbers static int larrgestPalindrome(int n) { int upper_limit = (int)Math.pow(10, n) - 1; // largest number of n-1 digit. // One plus this number // is lower limit which is // product of two numbers. int lower_limit = 1 + upper_limit / 10; // Initialize result int max_product = 0; for (int i = upper_limit; i >= lower_limit; i--) { for (int j = i; j >= lower_limit; j--) { // calculating product of two // n-digit numbers int product = i * j; if (product < max_product) break; int number = product; int reverse = 0; // calculating reverse of product // to check whether it is // palindrome or not while (number != 0) { reverse = reverse * 10 + number % 10; number /= 10; } // update new product if exist and if // greater than previous one if (product == reverse && product > max_product) max_product = product; } } return max_product; } // Driver code public static void main (String[] args) { int n = 2; System.out.print(larrgestPalindrome(n)); }} // This code is contributed by Anant Agarwal. # Python problem to find# out the largest palindrome# number which is product of# two n digit numbers. # Function to calculate largest# palindrome which is# product of two n-digits numbers def larrgestPalindrome(n): upper_limit = (10**(n))-1 # largest number of n-1 digit. # One plus this number # is lower limit which is # product of two numbers. lower_limit = 1 + upper_limit//10 max_product = 0 # Initialize result for i in range(upper_limit,lower_limit-1, -1): for j in range(i,lower_limit-1,-1): # calculating product of # two n-digit numbers product = i * j if (product < max_product): break number = product reverse = 0 # calculating reverse of # product to check # whether it is palindrome or not while (number != 0): reverse = reverse * 10 + number % 10 number =number // 10 # update new product if exist and if # greater than previous one if (product == reverse and product > max_product): max_product = product return max_product # Driver code n = 2print(larrgestPalindrome(n)) # This code is contributed# by Anant Agarwal. // C# problem to find out the// largest palindrome number// which is product of two// n digit numbers.using System; class GFG{ // Function to calculate largest // palindrome which isproduct of // two n-digits numbers static int larrgestPalindrome(int n) { int upper_limit = (int)Math.Pow(10, n) - 1; // largest number of n-1 digit. // One plus this number // is lower limit which is // product of two numbers. int lower_limit = 1 + upper_limit / 10; // Initialize result int max_product = 0; for (int i = upper_limit; i >= lower_limit; i--) { for (int j = i; j >= lower_limit; j--) { // calculating product of two // n-digit numbers int product = i * j; if (product < max_product) break; int number = product; int reverse = 0; // calculating reverse of product // to check whether it is // palindrome or not while (number != 0) { reverse = reverse * 10 + number % 10; number /= 10; } // update new product if exist and if // greater than previous one if (product == reverse && product > max_product) max_product = product; } } return max_product; } // Driver code public static void Main () { int n = 2; Console.Write(larrgestPalindrome(n)); }} // This code is contributed by nitin mittal. <?php// PHP problem to find out// the largest palindrome// number which is product// of two n digit numbers // Function to calculate// largest palindrome which// is product of two n-digit numbersfunction larrgestPalindrome($n){ $upper_limit = 0; // Loop to calculate upper bound // (largest number of n-digit) for ($i = 1; $i <= $n; $i++) { $upper_limit *= 10; $upper_limit += 9; } // largest number of n-1 digit // One plus this number // is lower limit which is // product of two numbers. $lower_limit = 1 + (int)($upper_limit / 10); // Initialize result $max_product = 0; for ($i = $upper_limit; $i >= $lower_limit; $i--) { for ($j = $i; $j >= $lower_limit; $j--) { // calculating product of // two n-digit numbers $product = $i * $j; if ($product < $max_product) break; $number = $product; $reverse = 0; // calculating reverse of // product to check whether // it is palindrome or not while ($number != 0) { $reverse = $reverse * 10 + $number % 10; $number = (int)($number / 10); } // update new product if exist // and if greater than previous one if ($product == $reverse && $product > $max_product) $max_product = $product; } } return $max_product;} // Driver code$n = 2;echo(larrgestPalindrome($n)); // This code is contributed by Ajit.?> <script> // Javascript problem to find out the // largest palindrome number // which is product of two // n digit numbers. // Function to calculate largest // palindrome which isproduct of // two n-digits numbers function larrgestPalindrome(n) { let upper_limit = Math.pow(10, n) - 1; // largest number of n-1 digit. // One plus this number // is lower limit which is // product of two numbers. let lower_limit = 1 + parseInt(upper_limit / 10, 10); // Initialize result let max_product = 0; for (let i = upper_limit; i >= lower_limit; i--) { for (let j = i; j >= lower_limit; j--) { // calculating product of two // n-digit numbers let product = i * j; if (product < max_product) break; let number = product; let reverse = 0; // calculating reverse of product // to check whether it is // palindrome or not while (number != 0) { reverse = reverse * 10 + number % 10; number = parseInt(number / 10, 10); } // update new product if exist and if // greater than previous one if (product == reverse && product > max_product) max_product = product; } } return max_product; } let n = 2; document.write(larrgestPalindrome(n)); </script> Output : 9009 Time Complexity: O(n*n*log10(product)), where n is the upper limit calculated and product is (product of two n-digit numbers)Auxiliary Space: O(1), as no extra space is required| The approach used in this post is simple and straightforward. Please comment if you find a better approach.This article is contributed by Shivam Pradhan(anuj_charm). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above nitin mittal jit_t user_zgh4 divyeshrabadiya07 singhh3010 Yahoo Mathematical Yahoo Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n04 Jun, 2022" }, { "code": null, "e": 151, "s": 54, "text": "Given a value n, find out the largest palindrome number which is product of two n digit numbers." }, { "code": null, "e": 163, "s": 151, "text": "Examples : " }, { "code": null, "e": 307, "s": 163, "text": "Input : n = 2\nOutput : 9009 \n9009 is the largest number which is product of two \n2-digit numbers. 9009 = 91*99.\n\nInput : n = 3\nOutput : 906609" }, { "code": null, "e": 353, "s": 307, "text": "Below are steps to find the required number. " }, { "code": null, "e": 605, "s": 353, "text": "Find a lower limit on n digit numbers. For example, for n = 2, lower_limit is 10.Find an upper limit on n digit numbers. For example, for n = 2, upper_limit is 99.Consider all pairs of numbers where ever number lies in range [lower_limit, upper_limit]" }, { "code": null, "e": 687, "s": 605, "text": "Find a lower limit on n digit numbers. For example, for n = 2, lower_limit is 10." }, { "code": null, "e": 770, "s": 687, "text": "Find an upper limit on n digit numbers. For example, for n = 2, upper_limit is 99." }, { "code": null, "e": 859, "s": 770, "text": "Consider all pairs of numbers where ever number lies in range [lower_limit, upper_limit]" }, { "code": null, "e": 904, "s": 859, "text": "Below is the implementation of above steps. " }, { "code": null, "e": 908, "s": 904, "text": "C++" }, { "code": null, "e": 913, "s": 908, "text": "Java" }, { "code": null, "e": 921, "s": 913, "text": "Python3" }, { "code": null, "e": 924, "s": 921, "text": "C#" }, { "code": null, "e": 928, "s": 924, "text": "PHP" }, { "code": null, "e": 939, "s": 928, "text": "Javascript" }, { "code": "// C++ problem to find out the// largest palindrome number which// is product of two n digit numbers#include <bits/stdc++.h>using namespace std; // Function to calculate largest// palindrome which is product of// two n-digits numbersint larrgestPalindrome(int n){ int upper_limit = pow(10,n) - 1; // largest number of n-1 digit. // One plus this number is lower // limit which is product of two numbers. int lower_limit = 1 + upper_limit / 10; // Initialize result int max_product = 0; for (int i = upper_limit; i >= lower_limit; i--) { for (int j = i; j >= lower_limit; j--) { // calculating product of // two n-digit numbers int product = i * j; if (product < max_product) break; int number = product; int reverse = 0; // calculating reverse of // product to check whether // it is palindrome or not while (number != 0) { reverse = reverse * 10 + number % 10; number /= 10; } // update new product if exist // and if greater than previous one if (product == reverse && product > max_product) max_product = product; } } return max_product;} // Driver codeint main(){ int n = 2; cout << larrgestPalindrome(n); return 0;}", "e": 2438, "s": 939, "text": null }, { "code": "// Java problem to find out the// largest palindrome number// which is product of two// n digit numbers.import java.lang.Math; class GFG{ // Function to calculate largest // palindrome which isproduct of // two n-digits numbers static int larrgestPalindrome(int n) { int upper_limit = (int)Math.pow(10, n) - 1; // largest number of n-1 digit. // One plus this number // is lower limit which is // product of two numbers. int lower_limit = 1 + upper_limit / 10; // Initialize result int max_product = 0; for (int i = upper_limit; i >= lower_limit; i--) { for (int j = i; j >= lower_limit; j--) { // calculating product of two // n-digit numbers int product = i * j; if (product < max_product) break; int number = product; int reverse = 0; // calculating reverse of product // to check whether it is // palindrome or not while (number != 0) { reverse = reverse * 10 + number % 10; number /= 10; } // update new product if exist and if // greater than previous one if (product == reverse && product > max_product) max_product = product; } } return max_product; } // Driver code public static void main (String[] args) { int n = 2; System.out.print(larrgestPalindrome(n)); }} // This code is contributed by Anant Agarwal.", "e": 4162, "s": 2438, "text": null }, { "code": "# Python problem to find# out the largest palindrome# number which is product of# two n digit numbers. # Function to calculate largest# palindrome which is# product of two n-digits numbers def larrgestPalindrome(n): upper_limit = (10**(n))-1 # largest number of n-1 digit. # One plus this number # is lower limit which is # product of two numbers. lower_limit = 1 + upper_limit//10 max_product = 0 # Initialize result for i in range(upper_limit,lower_limit-1, -1): for j in range(i,lower_limit-1,-1): # calculating product of # two n-digit numbers product = i * j if (product < max_product): break number = product reverse = 0 # calculating reverse of # product to check # whether it is palindrome or not while (number != 0): reverse = reverse * 10 + number % 10 number =number // 10 # update new product if exist and if # greater than previous one if (product == reverse and product > max_product): max_product = product return max_product # Driver code n = 2print(larrgestPalindrome(n)) # This code is contributed# by Anant Agarwal.", "e": 5507, "s": 4162, "text": null }, { "code": "// C# problem to find out the// largest palindrome number// which is product of two// n digit numbers.using System; class GFG{ // Function to calculate largest // palindrome which isproduct of // two n-digits numbers static int larrgestPalindrome(int n) { int upper_limit = (int)Math.Pow(10, n) - 1; // largest number of n-1 digit. // One plus this number // is lower limit which is // product of two numbers. int lower_limit = 1 + upper_limit / 10; // Initialize result int max_product = 0; for (int i = upper_limit; i >= lower_limit; i--) { for (int j = i; j >= lower_limit; j--) { // calculating product of two // n-digit numbers int product = i * j; if (product < max_product) break; int number = product; int reverse = 0; // calculating reverse of product // to check whether it is // palindrome or not while (number != 0) { reverse = reverse * 10 + number % 10; number /= 10; } // update new product if exist and if // greater than previous one if (product == reverse && product > max_product) max_product = product; } } return max_product; } // Driver code public static void Main () { int n = 2; Console.Write(larrgestPalindrome(n)); }} // This code is contributed by nitin mittal.", "e": 7203, "s": 5507, "text": null }, { "code": "<?php// PHP problem to find out// the largest palindrome// number which is product// of two n digit numbers // Function to calculate// largest palindrome which// is product of two n-digit numbersfunction larrgestPalindrome($n){ $upper_limit = 0; // Loop to calculate upper bound // (largest number of n-digit) for ($i = 1; $i <= $n; $i++) { $upper_limit *= 10; $upper_limit += 9; } // largest number of n-1 digit // One plus this number // is lower limit which is // product of two numbers. $lower_limit = 1 + (int)($upper_limit / 10); // Initialize result $max_product = 0; for ($i = $upper_limit; $i >= $lower_limit; $i--) { for ($j = $i; $j >= $lower_limit; $j--) { // calculating product of // two n-digit numbers $product = $i * $j; if ($product < $max_product) break; $number = $product; $reverse = 0; // calculating reverse of // product to check whether // it is palindrome or not while ($number != 0) { $reverse = $reverse * 10 + $number % 10; $number = (int)($number / 10); } // update new product if exist // and if greater than previous one if ($product == $reverse && $product > $max_product) $max_product = $product; } } return $max_product;} // Driver code$n = 2;echo(larrgestPalindrome($n)); // This code is contributed by Ajit.?>", "e": 8864, "s": 7203, "text": null }, { "code": "<script> // Javascript problem to find out the // largest palindrome number // which is product of two // n digit numbers. // Function to calculate largest // palindrome which isproduct of // two n-digits numbers function larrgestPalindrome(n) { let upper_limit = Math.pow(10, n) - 1; // largest number of n-1 digit. // One plus this number // is lower limit which is // product of two numbers. let lower_limit = 1 + parseInt(upper_limit / 10, 10); // Initialize result let max_product = 0; for (let i = upper_limit; i >= lower_limit; i--) { for (let j = i; j >= lower_limit; j--) { // calculating product of two // n-digit numbers let product = i * j; if (product < max_product) break; let number = product; let reverse = 0; // calculating reverse of product // to check whether it is // palindrome or not while (number != 0) { reverse = reverse * 10 + number % 10; number = parseInt(number / 10, 10); } // update new product if exist and if // greater than previous one if (product == reverse && product > max_product) max_product = product; } } return max_product; } let n = 2; document.write(larrgestPalindrome(n)); </script>", "e": 10527, "s": 8864, "text": null }, { "code": null, "e": 10536, "s": 10527, "text": "Output :" }, { "code": null, "e": 10541, "s": 10536, "text": "9009" }, { "code": null, "e": 10720, "s": 10541, "text": "Time Complexity: O(n*n*log10(product)), where n is the upper limit calculated and product is (product of two n-digit numbers)Auxiliary Space: O(1), as no extra space is required|" }, { "code": null, "e": 11261, "s": 10720, "text": "The approach used in this post is simple and straightforward. Please comment if you find a better approach.This article is contributed by Shivam Pradhan(anuj_charm). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to 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": 11274, "s": 11261, "text": "nitin mittal" }, { "code": null, "e": 11280, "s": 11274, "text": "jit_t" }, { "code": null, "e": 11290, "s": 11280, "text": "user_zgh4" }, { "code": null, "e": 11308, "s": 11290, "text": "divyeshrabadiya07" }, { "code": null, "e": 11319, "s": 11308, "text": "singhh3010" }, { "code": null, "e": 11325, "s": 11319, "text": "Yahoo" }, { "code": null, "e": 11338, "s": 11325, "text": "Mathematical" }, { "code": null, "e": 11344, "s": 11338, "text": "Yahoo" }, { "code": null, "e": 11357, "s": 11344, "text": "Mathematical" } ]
Python – Check whether a string starts and ends with the same character or not (using Regular Expression)
18 May, 2021 Given a string. The task is to write a regular expression to check whether a string starts and ends with the same character.Examples: Input : abba Output : Valid Input : a Output : Valid Input : abc Output : Invalid Solution: The input can be divide into 2 cases: Single character string: All single character strings satisfies the condition that they start and end with the same character. The regex for a string with only 1 character will be- '^[a-z]$' Multiple character string: Here we need to check whether the first and the last character is same or not. We do this using \1. The regex will be- '^([a-z]).*\1$' The two regular expressions can be combined using | '^[a-z]$|^([a-z]).*\1$' In this program, we will use search() method of re module.Below is the implementation. Python3 # Python program to check if a string starts# and ends with the same character # import re module as it provides# support for regular expressionsimport re # the regular expressionregex = r'^[a-z]$|^([a-z]).*\1$' # function for checking the stringdef check(string): # pass the regular expression # and the string in the search() method if(re.search(regex, string)): print("Valid") else: print("Invalid") if __name__ == '__main__' : sample1 = "abba" sample2 = "a" sample3 = "abcd" check(sample1) check(sample2) check(sample3) Output : Valid Valid Invalid surinderdawra388 Python Regex-programs python-regex Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python Program for Fibonacci numbers
[ { "code": null, "e": 28, "s": 0, "text": "\n18 May, 2021" }, { "code": null, "e": 164, "s": 28, "text": "Given a string. The task is to write a regular expression to check whether a string starts and ends with the same character.Examples: " }, { "code": null, "e": 260, "s": 164, "text": "Input : \nabba\nOutput : \nValid\n\nInput : \na\nOutput : \nValid\n\nInput : \nabc\nOutput : \nInvalid" }, { "code": null, "e": 310, "s": 260, "text": "Solution: The input can be divide into 2 cases: " }, { "code": null, "e": 493, "s": 310, "text": "Single character string: All single character strings satisfies the condition that they start and end with the same character. The regex for a string with only 1 character will be- " }, { "code": null, "e": 503, "s": 493, "text": "'^[a-z]$'" }, { "code": null, "e": 651, "s": 503, "text": "Multiple character string: Here we need to check whether the first and the last character is same or not. We do this using \\1. The regex will be- " }, { "code": null, "e": 667, "s": 651, "text": "'^([a-z]).*\\1$'" }, { "code": null, "e": 721, "s": 667, "text": "The two regular expressions can be combined using | " }, { "code": null, "e": 745, "s": 721, "text": "'^[a-z]$|^([a-z]).*\\1$'" }, { "code": null, "e": 833, "s": 745, "text": "In this program, we will use search() method of re module.Below is the implementation. " }, { "code": null, "e": 841, "s": 833, "text": "Python3" }, { "code": "# Python program to check if a string starts# and ends with the same character # import re module as it provides# support for regular expressionsimport re # the regular expressionregex = r'^[a-z]$|^([a-z]).*\\1$' # function for checking the stringdef check(string): # pass the regular expression # and the string in the search() method if(re.search(regex, string)): print(\"Valid\") else: print(\"Invalid\") if __name__ == '__main__' : sample1 = \"abba\" sample2 = \"a\" sample3 = \"abcd\" check(sample1) check(sample2) check(sample3)", "e": 1417, "s": 841, "text": null }, { "code": null, "e": 1428, "s": 1417, "text": "Output : " }, { "code": null, "e": 1448, "s": 1428, "text": "Valid\nValid\nInvalid" }, { "code": null, "e": 1467, "s": 1450, "text": "surinderdawra388" }, { "code": null, "e": 1489, "s": 1467, "text": "Python Regex-programs" }, { "code": null, "e": 1502, "s": 1489, "text": "python-regex" }, { "code": null, "e": 1509, "s": 1502, "text": "Python" }, { "code": null, "e": 1525, "s": 1509, "text": "Python Programs" }, { "code": null, "e": 1623, "s": 1525, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1641, "s": 1623, "text": "Python Dictionary" }, { "code": null, "e": 1683, "s": 1641, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1705, "s": 1683, "text": "Enumerate() in Python" }, { "code": null, "e": 1740, "s": 1705, "text": "Read a file line by line in Python" }, { "code": null, "e": 1766, "s": 1740, "text": "Python String | replace()" }, { "code": null, "e": 1809, "s": 1766, "text": "Python program to convert a list to string" }, { "code": null, "e": 1831, "s": 1809, "text": "Defaultdict in Python" }, { "code": null, "e": 1870, "s": 1831, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 1908, "s": 1870, "text": "Python | Convert a list to dictionary" } ]
Check if it is possible to move from (0, 0) to (x, y) in N steps
25 May, 2022 Given a point (x, y). Find whether it is possible or not to move from (0, 0) to (x, y) in exactly n steps. 4 types of steps are valid, you can move from a point (a, b) to either of (a, b+1), (a, b-1), (a-1, b), (a+1, b)Examples: Input: x = 0, y = 0, n = 2 Output: POSSIBLE Input: x = 1, y = 1, n = 3 Output: IMPOSSIBLE Approach : In the shortest path, one can move from (0, 0) to (x, y) in |x| + |y|. So, it is not possible to move from (0, 0) to (x, y) in less than |x| + |y| steps. After reaching one can take two more steps as (x, y) -> (x, y+1) -> (x, y). So, it is possible if n >= |x| + |y| and ( n-( |x| + |y| ) ) % 2 = 0. Below is the implementation of the above approach: C++ C Java Python3 C# PHP Javascript // CPP program to check whether it is possible// or not to move from (0, 0) to (x, y)// in exactly n steps#include <bits/stdc++.h>using namespace std; // Function to check whether it is possible// or not to move from (0, 0) to (x, y)// in exactly n stepsbool Arrive(int a, int b, int n){ if (n >= abs(a) + abs(b) and (n - (abs(a) + abs(b))) % 2 == 0) return true; return false;} // Driver codeint main(){ int a = 5, b = 5, n = 11; if (Arrive(a, b, n)) cout << "Yes"; else cout << "No"; return 0;} // C program to check whether it is possible// or not to move from (0, 0) to (x, y)// in exactly n steps#include <stdio.h>#include <stdbool.h> int abs(int a){ int abs = a; if(abs < 0) abs = abs * (-1); return abs;} // Function to check whether it is possible// or not to move from (0, 0) to (x, y)// in exactly n stepsbool Arrive(int a, int b, int n){ if (n >= abs(a) + abs(b) && (n - (abs(a) + abs(b))) % 2 == 0) return true; return false;} // Driver codeint main(){ int a = 5, b = 5, n = 11; if (Arrive(a, b, n)) printf("Yes"); else printf("No"); return 0;} // This code is contributed by kothavvsaakash. // Java program to check whether it is possible// or not to move from (0, 0) to (x, y)// in exactly n stepsimport java.io.*; public class GFG { // Function to check whether it is possible// or not to move from (0, 0) to (x, y)// in exactly n stepsstatic boolean Arrive(int a, int b, int n){ if (n >= Math.abs(a) + Math.abs(b) && (n - (Math.abs(a) + Math.abs(b))) % 2 == 0) return true; return false;} // Driver codeint main(){ return 0;} public static void main (String[] args) { int a = 5, b = 5, n = 11; if (Arrive(a, b, n)) System.out.println( "Yes"); else System.out.println( "No"); }}//This code is contributed by shs.. # Python3 program to check whether# it is possible or not to move from# (0, 0) to (x, y) in exactly n steps # Function to check whether it is# possible or not to move from# (0, 0) to (x, y) in exactly n stepsdef Arrive(a, b, n): if (n >= abs(a) + abs(b) and (n - (abs(a) + abs(b))) % 2 == 0): return True return False # Driver codea = 5b = 5n = 11 if (Arrive(a, b, n)): print("Yes")else: print("No") # This code is contributed# by Yatin Gupta // C# program to check whether// it is possible or not to// move from (0, 0) to (x, y)// in exactly n stepsusing System; class GFG{ // Function to check whether it// is possible or not to move// from (0, 0) to (x, y) in// exactly n stepsstatic bool Arrive(int a, int b, int n){ if (n >= Math.Abs(a) + Math.Abs(b) && (n - (Math.Abs(a) + Math.Abs(b))) % 2 == 0) return true; return false;} // Driver codepublic static void Main (){ int a = 5, b = 5, n = 11; if (Arrive(a, b, n)) Console.WriteLine( "Yes"); else Console.WriteLine( "No"); }} // This code is contributed by shashank <?php// PHP program to check whether// it is possible or not to move// from (0, 0) to (x, y) in exactly n steps // Function to check whether it// is possible or not to move// from (0, 0) to (x, y) in exactly n stepsfunction Arrive($a, $b, $n){ if ($n >= abs($a) + abs($b) and ($n - (abs($a) + abs($b))) % 2 == 0) return true; return false;} // Driver code$a = 5; $b = 5; $n = 11; if (Arrive($a, $b, $n)) echo "Yes";else echo "No"; // This code is contributed// by Akanksha Rai(Abby_akku) <script> // JavaScript program to check whether it is// possible or not to move from (0, 0) to (x, y)// in exactly n steps // Function to check whether it is possible// or not to move from (0, 0) to (x, y)// in exactly n stepsfunction Arrive(a, b, n){ if (n >= Math.abs(a) + Math.abs(b) && (n - (Math.abs(a) + Math.abs(b))) % 2 == 0) return true; return false;} // Driver codevar a = 5, b = 5, n = 11; if (Arrive(a, b, n)) document.write("Yes");else document.write("No"); // This code is contributed by Ankita saini </script> No Shashank12 inderDuMCA Akanksha_Rai YatinGupta ankita_saini kothavvsaakash Competitive Programming Geometric Mathematical Mathematical Geometric Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Bits manipulation (Important tactics) What is Competitive Programming and How to Prepare for It? Bitwise Hacks for Competitive Programming Algorithm Library | C++ Magicians STL Algorithm Formatted output in Java Program for distance between two points on earth Closest Pair of Points using Divide and Conquer algorithm How to check if a given point lies inside or outside a polygon? How to check if two given line segments intersect? Optimum location of point to minimize total distance
[ { "code": null, "e": 53, "s": 25, "text": "\n25 May, 2022" }, { "code": null, "e": 284, "s": 53, "text": "Given a point (x, y). Find whether it is possible or not to move from (0, 0) to (x, y) in exactly n steps. 4 types of steps are valid, you can move from a point (a, b) to either of (a, b+1), (a, b-1), (a-1, b), (a+1, b)Examples: " }, { "code": null, "e": 376, "s": 284, "text": "Input: x = 0, y = 0, n = 2\nOutput: POSSIBLE\n\nInput: x = 1, y = 1, n = 3 \nOutput: IMPOSSIBLE" }, { "code": null, "e": 391, "s": 378, "text": "Approach : " }, { "code": null, "e": 623, "s": 391, "text": "In the shortest path, one can move from (0, 0) to (x, y) in |x| + |y|. So, it is not possible to move from (0, 0) to (x, y) in less than |x| + |y| steps. After reaching one can take two more steps as (x, y) -> (x, y+1) -> (x, y). " }, { "code": null, "e": 647, "s": 623, "text": "So, it is possible if " }, { "code": null, "e": 697, "s": 647, "text": "n >= |x| + |y| and ( n-( |x| + |y| ) ) % 2 = 0. " }, { "code": null, "e": 750, "s": 697, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 754, "s": 750, "text": "C++" }, { "code": null, "e": 756, "s": 754, "text": "C" }, { "code": null, "e": 761, "s": 756, "text": "Java" }, { "code": null, "e": 769, "s": 761, "text": "Python3" }, { "code": null, "e": 772, "s": 769, "text": "C#" }, { "code": null, "e": 776, "s": 772, "text": "PHP" }, { "code": null, "e": 787, "s": 776, "text": "Javascript" }, { "code": "// CPP program to check whether it is possible// or not to move from (0, 0) to (x, y)// in exactly n steps#include <bits/stdc++.h>using namespace std; // Function to check whether it is possible// or not to move from (0, 0) to (x, y)// in exactly n stepsbool Arrive(int a, int b, int n){ if (n >= abs(a) + abs(b) and (n - (abs(a) + abs(b))) % 2 == 0) return true; return false;} // Driver codeint main(){ int a = 5, b = 5, n = 11; if (Arrive(a, b, n)) cout << \"Yes\"; else cout << \"No\"; return 0;}", "e": 1326, "s": 787, "text": null }, { "code": "// C program to check whether it is possible// or not to move from (0, 0) to (x, y)// in exactly n steps#include <stdio.h>#include <stdbool.h> int abs(int a){ int abs = a; if(abs < 0) abs = abs * (-1); return abs;} // Function to check whether it is possible// or not to move from (0, 0) to (x, y)// in exactly n stepsbool Arrive(int a, int b, int n){ if (n >= abs(a) + abs(b) && (n - (abs(a) + abs(b))) % 2 == 0) return true; return false;} // Driver codeint main(){ int a = 5, b = 5, n = 11; if (Arrive(a, b, n)) printf(\"Yes\"); else printf(\"No\"); return 0;} // This code is contributed by kothavvsaakash.", "e": 1981, "s": 1326, "text": null }, { "code": "// Java program to check whether it is possible// or not to move from (0, 0) to (x, y)// in exactly n stepsimport java.io.*; public class GFG { // Function to check whether it is possible// or not to move from (0, 0) to (x, y)// in exactly n stepsstatic boolean Arrive(int a, int b, int n){ if (n >= Math.abs(a) + Math.abs(b) && (n - (Math.abs(a) + Math.abs(b))) % 2 == 0) return true; return false;} // Driver codeint main(){ return 0;} public static void main (String[] args) { int a = 5, b = 5, n = 11; if (Arrive(a, b, n)) System.out.println( \"Yes\"); else System.out.println( \"No\"); }}//This code is contributed by shs..", "e": 2664, "s": 1981, "text": null }, { "code": "# Python3 program to check whether# it is possible or not to move from# (0, 0) to (x, y) in exactly n steps # Function to check whether it is# possible or not to move from# (0, 0) to (x, y) in exactly n stepsdef Arrive(a, b, n): if (n >= abs(a) + abs(b) and (n - (abs(a) + abs(b))) % 2 == 0): return True return False # Driver codea = 5b = 5n = 11 if (Arrive(a, b, n)): print(\"Yes\")else: print(\"No\") # This code is contributed# by Yatin Gupta ", "e": 3142, "s": 2664, "text": null }, { "code": "// C# program to check whether// it is possible or not to// move from (0, 0) to (x, y)// in exactly n stepsusing System; class GFG{ // Function to check whether it// is possible or not to move// from (0, 0) to (x, y) in// exactly n stepsstatic bool Arrive(int a, int b, int n){ if (n >= Math.Abs(a) + Math.Abs(b) && (n - (Math.Abs(a) + Math.Abs(b))) % 2 == 0) return true; return false;} // Driver codepublic static void Main (){ int a = 5, b = 5, n = 11; if (Arrive(a, b, n)) Console.WriteLine( \"Yes\"); else Console.WriteLine( \"No\"); }} // This code is contributed by shashank", "e": 3767, "s": 3142, "text": null }, { "code": "<?php// PHP program to check whether// it is possible or not to move// from (0, 0) to (x, y) in exactly n steps // Function to check whether it// is possible or not to move// from (0, 0) to (x, y) in exactly n stepsfunction Arrive($a, $b, $n){ if ($n >= abs($a) + abs($b) and ($n - (abs($a) + abs($b))) % 2 == 0) return true; return false;} // Driver code$a = 5; $b = 5; $n = 11; if (Arrive($a, $b, $n)) echo \"Yes\";else echo \"No\"; // This code is contributed// by Akanksha Rai(Abby_akku)", "e": 4281, "s": 3767, "text": null }, { "code": "<script> // JavaScript program to check whether it is// possible or not to move from (0, 0) to (x, y)// in exactly n steps // Function to check whether it is possible// or not to move from (0, 0) to (x, y)// in exactly n stepsfunction Arrive(a, b, n){ if (n >= Math.abs(a) + Math.abs(b) && (n - (Math.abs(a) + Math.abs(b))) % 2 == 0) return true; return false;} // Driver codevar a = 5, b = 5, n = 11; if (Arrive(a, b, n)) document.write(\"Yes\");else document.write(\"No\"); // This code is contributed by Ankita saini </script>", "e": 4833, "s": 4281, "text": null }, { "code": null, "e": 4836, "s": 4833, "text": "No" }, { "code": null, "e": 4849, "s": 4838, "text": "Shashank12" }, { "code": null, "e": 4860, "s": 4849, "text": "inderDuMCA" }, { "code": null, "e": 4873, "s": 4860, "text": "Akanksha_Rai" }, { "code": null, "e": 4884, "s": 4873, "text": "YatinGupta" }, { "code": null, "e": 4897, "s": 4884, "text": "ankita_saini" }, { "code": null, "e": 4912, "s": 4897, "text": "kothavvsaakash" }, { "code": null, "e": 4936, "s": 4912, "text": "Competitive Programming" }, { "code": null, "e": 4946, "s": 4936, "text": "Geometric" }, { "code": null, "e": 4959, "s": 4946, "text": "Mathematical" }, { "code": null, "e": 4972, "s": 4959, "text": "Mathematical" }, { "code": null, "e": 4982, "s": 4972, "text": "Geometric" }, { "code": null, "e": 5080, "s": 4982, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5118, "s": 5080, "text": "Bits manipulation (Important tactics)" }, { "code": null, "e": 5177, "s": 5118, "text": "What is Competitive Programming and How to Prepare for It?" }, { "code": null, "e": 5219, "s": 5177, "text": "Bitwise Hacks for Competitive Programming" }, { "code": null, "e": 5267, "s": 5219, "text": "Algorithm Library | C++ Magicians STL Algorithm" }, { "code": null, "e": 5292, "s": 5267, "text": "Formatted output in Java" }, { "code": null, "e": 5341, "s": 5292, "text": "Program for distance between two points on earth" }, { "code": null, "e": 5399, "s": 5341, "text": "Closest Pair of Points using Divide and Conquer algorithm" }, { "code": null, "e": 5463, "s": 5399, "text": "How to check if a given point lies inside or outside a polygon?" }, { "code": null, "e": 5514, "s": 5463, "text": "How to check if two given line segments intersect?" } ]
Program to creating Doraemon cartoon character using Computer Graphics
14 Jul, 2021 Computer Graphics is an important subject to improve coding skills. Many things can be implemented using computer graphics. For example- car animation, cartoon characters, and many more things. In this article, the cartoon character Doraemon is created using computer graphics. Implementation in C In C, the graphics.h functions are used to draw different shapes(like a circle, rectangle, etc), display text(any message) in different formats (different fonts and colors). By using graphics.h it is possible to make programs, animations and also games. These can be useful for beginners. Functions Used: setcolor(n): A function from graphics.h header file which sets the color of the pointer(cursor). line(int x1, int y1, int x2, int y2): Line function is used to draw a line from a point(x1, y1) to a point(x2, y2) i.e. (x1, y1) and (x2, y2) are endpoints of the line.The code given below draws a line. setfillstyle(pattern, color): The header file graphics.h contains setfillstyle() function which sets the current fill pattern and fills color. floodfill(pattern, color): function is used to fill an enclosed area. The current fill pattern and fill color are used to fill the area. Below is the implementation of drawing the cartoon character Doraemon using graphics in C: C // C program to implement// the above approach#include <conio.h>#include <graphics.h>#include <stdio.h> // Driver codeint main(){ int gd = DETECT, gm; initgraph(&gd, &gm, "C:\\turboc3\\bgi"); setfillstyle(SOLID_FILL, CYAN); // Head Outer Circle circle(500, 200, 100); // Head Inner Circle circle(500, 212, 88); floodfill(502, 102, 15); setfillstyle(SOLID_FILL, CYAN); // Body Outer Circle circle(500, 400, 100); // Body Inner Circle circle(500, 388, 88); floodfill(502, 498, 15); setfillstyle(SOLID_FILL, RED); // NOSE circle(502, 214, 10); floodfill(504, 216, 15); // Left Eye circle(460, 170, 15); // Right Eye circle(540, 170, 15); // Left Mustache Middle // Line line(430, 214, 380, 214); // Left Mustache Upper // Line line(430, 214, 380, 196); // Left Mustache Lower // Line line(430, 214, 380, 234); // Right Mustache Middle // Line line(570, 214, 620, 214); // Right Mustache Upper // Line line(570, 214, 620, 196); // Right Mustache Lower // Line line(570, 214, 620, 234); // Nose-Mouth Connector line(502, 224, 502, 240); // Mouth Horizental Line line(465, 240, 535, 240); // Mouth Tangent Line line(465, 240, 502, 260); // Mouth Tangent Line line(502, 260, 535, 240); setfillstyle(SOLID_FILL, CYAN); // Right Up Hand line(500, 300, 650, 320); // Right Low Hand line(500, 300, 650, 340); // Right Hand Joining line(650, 320, 650, 340); floodfill(645, 332, 15); setfillstyle(SOLID_FILL, CYAN); // Left Up Hand line(500, 300, 350, 320); // Left Down Hand line(500, 300, 350, 340); // Left Hand Join line(350, 320, 350, 340); floodfill(355, 332, 15); circle(665, 331, 15); circle(335, 331, 15); // Pocket Horizental line(445, 380, 555, 380); // Pocket Tangent line(445, 380, 500, 420); // Pocket Tangent line(500, 420, 555, 380); setfillstyle(SOLID_FILL, RED); // Bell Pad Upper Horizental line(430, 298, 570, 298); // Bell Pad Lower Horizental line(430, 308, 570, 308); // Bell Pad Left Join line(430, 298, 430, 308); // Bell Pad Right Join line(570, 298, 570, 308); floodfill(432, 302, 15); floodfill(568, 302, 15); floodfill(500, 307, 15); setfillstyle(SOLID_FILL, YELLOW); // Bell circle(500, 323, 15); floodfill(502, 325, 15); setcolor(BLACK); // Inner Bell Upper Line line(485, 323, 515, 323); // Inner Bell Upper Line line(485, 328, 515, 328); setcolor(WHITE); // Left Leg Left Line line(450, 480, 450, 550); // Left Leg Right Line line(470, 490, 470, 550); // Right Leg Right Line line(550, 480, 550, 550); // Right Leg Left Line line(530, 490, 530, 550); // Left Leg Pad rectangle(440, 550, 480, 570); // Right Leg Pad rectangle(520, 550, 560, 570); // Left Leg Color setfillstyle(SOLID_FILL, CYAN); floodfill(460, 500, 15); // Right Leg Color setfillstyle(SOLID_FILL, CYAN); floodfill(540, 500, 15); getch(); closegraph(); return 0;} Output: c-graphics computer-graphics C Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n14 Jul, 2021" }, { "code": null, "e": 306, "s": 28, "text": "Computer Graphics is an important subject to improve coding skills. Many things can be implemented using computer graphics. For example- car animation, cartoon characters, and many more things. In this article, the cartoon character Doraemon is created using computer graphics." }, { "code": null, "e": 326, "s": 306, "text": "Implementation in C" }, { "code": null, "e": 616, "s": 326, "text": "In C, the graphics.h functions are used to draw different shapes(like a circle, rectangle, etc), display text(any message) in different formats (different fonts and colors). By using graphics.h it is possible to make programs, animations and also games. These can be useful for beginners." }, { "code": null, "e": 632, "s": 616, "text": "Functions Used:" }, { "code": null, "e": 729, "s": 632, "text": "setcolor(n): A function from graphics.h header file which sets the color of the pointer(cursor)." }, { "code": null, "e": 932, "s": 729, "text": "line(int x1, int y1, int x2, int y2): Line function is used to draw a line from a point(x1, y1) to a point(x2, y2) i.e. (x1, y1) and (x2, y2) are endpoints of the line.The code given below draws a line." }, { "code": null, "e": 1075, "s": 932, "text": "setfillstyle(pattern, color): The header file graphics.h contains setfillstyle() function which sets the current fill pattern and fills color." }, { "code": null, "e": 1212, "s": 1075, "text": "floodfill(pattern, color): function is used to fill an enclosed area. The current fill pattern and fill color are used to fill the area." }, { "code": null, "e": 1303, "s": 1212, "text": "Below is the implementation of drawing the cartoon character Doraemon using graphics in C:" }, { "code": null, "e": 1305, "s": 1303, "text": "C" }, { "code": "// C program to implement// the above approach#include <conio.h>#include <graphics.h>#include <stdio.h> // Driver codeint main(){ int gd = DETECT, gm; initgraph(&gd, &gm, \"C:\\\\turboc3\\\\bgi\"); setfillstyle(SOLID_FILL, CYAN); // Head Outer Circle circle(500, 200, 100); // Head Inner Circle circle(500, 212, 88); floodfill(502, 102, 15); setfillstyle(SOLID_FILL, CYAN); // Body Outer Circle circle(500, 400, 100); // Body Inner Circle circle(500, 388, 88); floodfill(502, 498, 15); setfillstyle(SOLID_FILL, RED); // NOSE circle(502, 214, 10); floodfill(504, 216, 15); // Left Eye circle(460, 170, 15); // Right Eye circle(540, 170, 15); // Left Mustache Middle // Line line(430, 214, 380, 214); // Left Mustache Upper // Line line(430, 214, 380, 196); // Left Mustache Lower // Line line(430, 214, 380, 234); // Right Mustache Middle // Line line(570, 214, 620, 214); // Right Mustache Upper // Line line(570, 214, 620, 196); // Right Mustache Lower // Line line(570, 214, 620, 234); // Nose-Mouth Connector line(502, 224, 502, 240); // Mouth Horizental Line line(465, 240, 535, 240); // Mouth Tangent Line line(465, 240, 502, 260); // Mouth Tangent Line line(502, 260, 535, 240); setfillstyle(SOLID_FILL, CYAN); // Right Up Hand line(500, 300, 650, 320); // Right Low Hand line(500, 300, 650, 340); // Right Hand Joining line(650, 320, 650, 340); floodfill(645, 332, 15); setfillstyle(SOLID_FILL, CYAN); // Left Up Hand line(500, 300, 350, 320); // Left Down Hand line(500, 300, 350, 340); // Left Hand Join line(350, 320, 350, 340); floodfill(355, 332, 15); circle(665, 331, 15); circle(335, 331, 15); // Pocket Horizental line(445, 380, 555, 380); // Pocket Tangent line(445, 380, 500, 420); // Pocket Tangent line(500, 420, 555, 380); setfillstyle(SOLID_FILL, RED); // Bell Pad Upper Horizental line(430, 298, 570, 298); // Bell Pad Lower Horizental line(430, 308, 570, 308); // Bell Pad Left Join line(430, 298, 430, 308); // Bell Pad Right Join line(570, 298, 570, 308); floodfill(432, 302, 15); floodfill(568, 302, 15); floodfill(500, 307, 15); setfillstyle(SOLID_FILL, YELLOW); // Bell circle(500, 323, 15); floodfill(502, 325, 15); setcolor(BLACK); // Inner Bell Upper Line line(485, 323, 515, 323); // Inner Bell Upper Line line(485, 328, 515, 328); setcolor(WHITE); // Left Leg Left Line line(450, 480, 450, 550); // Left Leg Right Line line(470, 490, 470, 550); // Right Leg Right Line line(550, 480, 550, 550); // Right Leg Left Line line(530, 490, 530, 550); // Left Leg Pad rectangle(440, 550, 480, 570); // Right Leg Pad rectangle(520, 550, 560, 570); // Left Leg Color setfillstyle(SOLID_FILL, CYAN); floodfill(460, 500, 15); // Right Leg Color setfillstyle(SOLID_FILL, CYAN); floodfill(540, 500, 15); getch(); closegraph(); return 0;}", "e": 4503, "s": 1305, "text": null }, { "code": null, "e": 4511, "s": 4503, "text": "Output:" }, { "code": null, "e": 4522, "s": 4511, "text": "c-graphics" }, { "code": null, "e": 4540, "s": 4522, "text": "computer-graphics" }, { "code": null, "e": 4551, "s": 4540, "text": "C Programs" } ]
Unordered, Ordered, and Description Lists in HTML
09 Feb, 2022 Lists are used to store data or information in web pages in ordered or unordered form. HTML supports several types of list elements that can be included in the <BODY>tag of the document. These elements may also be nested, i.e, the onset of elements can be embedded within another. There are three types of list are available in HTML: Unordered List Ordered List Description list Now before moving to the list first of all we understands what is a list item tag. List item tag is used to define each item of a list. Once we define list items with the <li> tag, the list appears in Web browsers in the bulleted form (by default). It is used inside both ordered and unordered list. Syntax: <li> content </li> Attribute of item tag: value: The value attribute of the<li> tag is used to specify the value of the first item. The value must be a number and this can be used in case of ordered list only. The subsequent list items will increment the value form the number. Syntax: <li value = number> Example 1: HTML <html ><head> <title>inline style attribute</title></head><body> <li>sachin</li> <li>sujay</li> <li>Amraditya</li> <li>shivam</li> <li>Parth</li></body></html> Output: Example 2: HTML <html ><head> <title>inline style attribute</title></head><body> <ol> <li value="51">English</li> <li>Hindi</li> <li>Maths</li> <li>Science</li> <li>social science</li> </ol></body></html> Output: Now we will discuss all the list provided by the HTML one-by-one in detail: An ordered list defines a list of items in which the order of the items are matters. An ordered list is also called a number list. The ordering is given by a numbering scheme, using Arabic numbers, letters, roman numerals. Or in other words, ordered list tag is used to create ordered list. Syntax: <ol> content </ol> Attributes of ordered list: 1. reversed: This attribute is used to specifies that the ordered of the list should be reversed. Syntax: <ol reversed> 2. start: This attribute is used to specifies the start value of the list. Syntax: <ol start = “number”> 3. type: This attribute is used to specifies the type of list item maker. The value of this attribute is decimal(Default)/lower-roman/upper roman/lower-alpha/upper alpha Syntax: <ol type = “1|b|A|i|I”> Example 1: HTML <html><head> <title>ordered list</title></head><body> <h1>Example of ordered list in default</h1> <ol > <li>Sachin</li> <li>Manoj</li> <li>Parth</li> <li>sujay</li> <li>Amraditya</li> </ol></body></html> Output: Example 2: HTML <html><head> <title>ordered list</title></head><body> <h1>Example of ordered list whose type = "A"</h1> <ol type="A"> <li>Sachin</li> <li>Manoj</li> </ol> <h1>Example of reverse ordered list</h1> <ol reversed> <li>Parth</li> <li>sujay</li> </ol> <h1>Example of ordered list start from 10</h1> <ol start = "10"> <li>Pushpa</li> <li>Purvi</li> </ol> </body></html> Output: An unordered list defines a list of items in which the order of the items does not. Or in other words, unordered list tag is used to create a unordered list. It is also known as bulleted list. In unordered list each element in the list is defined using <li> tag. Syntax: <ul> content </ul> Attributes of unordered list: List-style-type: This attribute is used to specifies the bullet style that will be used as the list item marker. The value of this attribute is None/disc(default)/circle/square. Syntax: <ul style=”list-style-type:square|disc|none;”> Example 1: HTML <html><head> <title>unordered list</title></head><body> <h1>Example of unordered list in default</h1> <ul> <li>Sachin</li> <li>Manoj</li> <li>Parth</li> <li>sujay</li> <li>Amraditya</li> </ul></body></html> Output: Example 2: HTML <html><head> <title>unordered list</title></head><body> <h2>Example of unordered list in circle</h2> <ul style="list-style-type:circle;"> <li>sachin</li> <li>manoj</li> </ul> <h2>Example of unordered list in disk</h2> <ul style="list-style-type:disk;"> <li>Priya</li> <li>Mohit</li> </ul> <h2>Example of unordered list in square</h2> <ul style="list-style-type:square;"> <li>Pinky</li> <li>Punam</li> </ul> <h2>Example of unordered list in none</h2> <ul style="list-style-type:none;"> <li>Mukti</li> <li>Dhama</li> </ul></body></html> Output: Description list is a list in which each term contain its description. This tag contain <dt> and <dd> tag. <dt></dt>: This tag is used to define the name or term <dd><dd>: this tag is used to describe the term. Syntax: <dl> content </dl> Example: HTML <html><head> <title>Description list</title></head><body> <h2>Example of description list</h2> <dl> <dt>Python:</dt> <dd>It is a programming language</dd> <dt>C++:</dt> <dd>It is also a programming language</dd> </dl> </body></html> Output: gulshankumarar231 rs1686740 varshagumber28 Picked class 7 School Learning School Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Flora and Fauna of Ladakh Akbar's Policies Working of the Government in India Components of Environment Equality in Indian Democracy Libraries in Python What are Different Output Devices? Generations of Computers - Computer Fundamentals GeeksforGeeks School Reading Rows from a CSV File in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n09 Feb, 2022" }, { "code": null, "e": 362, "s": 28, "text": "Lists are used to store data or information in web pages in ordered or unordered form. HTML supports several types of list elements that can be included in the <BODY>tag of the document. These elements may also be nested, i.e, the onset of elements can be embedded within another. There are three types of list are available in HTML:" }, { "code": null, "e": 377, "s": 362, "text": "Unordered List" }, { "code": null, "e": 390, "s": 377, "text": "Ordered List" }, { "code": null, "e": 407, "s": 390, "text": "Description list" }, { "code": null, "e": 490, "s": 407, "text": "Now before moving to the list first of all we understands what is a list item tag." }, { "code": null, "e": 707, "s": 490, "text": "List item tag is used to define each item of a list. Once we define list items with the <li> tag, the list appears in Web browsers in the bulleted form (by default). It is used inside both ordered and unordered list." }, { "code": null, "e": 715, "s": 707, "text": "Syntax:" }, { "code": null, "e": 734, "s": 715, "text": "<li> content </li>" }, { "code": null, "e": 757, "s": 734, "text": "Attribute of item tag:" }, { "code": null, "e": 994, "s": 757, "text": "value: The value attribute of the<li> tag is used to specify the value of the first item. The value must be a number and this can be used in case of ordered list only. The subsequent list items will increment the value form the number." }, { "code": null, "e": 1002, "s": 994, "text": "Syntax:" }, { "code": null, "e": 1023, "s": 1002, "text": "<li value = number>" }, { "code": null, "e": 1034, "s": 1023, "text": "Example 1:" }, { "code": null, "e": 1039, "s": 1034, "text": "HTML" }, { "code": "<html ><head> <title>inline style attribute</title></head><body> <li>sachin</li> <li>sujay</li> <li>Amraditya</li> <li>shivam</li> <li>Parth</li></body></html>", "e": 1217, "s": 1039, "text": null }, { "code": null, "e": 1225, "s": 1217, "text": "Output:" }, { "code": null, "e": 1236, "s": 1225, "text": "Example 2:" }, { "code": null, "e": 1241, "s": 1236, "text": "HTML" }, { "code": "<html ><head> <title>inline style attribute</title></head><body> <ol> <li value=\"51\">English</li> <li>Hindi</li> <li>Maths</li> <li>Science</li> <li>social science</li> </ol></body></html>", "e": 1474, "s": 1241, "text": null }, { "code": null, "e": 1482, "s": 1474, "text": "Output:" }, { "code": null, "e": 1558, "s": 1482, "text": "Now we will discuss all the list provided by the HTML one-by-one in detail:" }, { "code": null, "e": 1850, "s": 1558, "text": "An ordered list defines a list of items in which the order of the items are matters. An ordered list is also called a number list. The ordering is given by a numbering scheme, using Arabic numbers, letters, roman numerals. Or in other words, ordered list tag is used to create ordered list." }, { "code": null, "e": 1858, "s": 1850, "text": "Syntax:" }, { "code": null, "e": 1877, "s": 1858, "text": "<ol> content </ol>" }, { "code": null, "e": 1905, "s": 1877, "text": "Attributes of ordered list:" }, { "code": null, "e": 2003, "s": 1905, "text": "1. reversed: This attribute is used to specifies that the ordered of the list should be reversed." }, { "code": null, "e": 2011, "s": 2003, "text": "Syntax:" }, { "code": null, "e": 2025, "s": 2011, "text": "<ol reversed>" }, { "code": null, "e": 2100, "s": 2025, "text": "2. start: This attribute is used to specifies the start value of the list." }, { "code": null, "e": 2108, "s": 2100, "text": "Syntax:" }, { "code": null, "e": 2130, "s": 2108, "text": "<ol start = “number”>" }, { "code": null, "e": 2300, "s": 2130, "text": "3. type: This attribute is used to specifies the type of list item maker. The value of this attribute is decimal(Default)/lower-roman/upper roman/lower-alpha/upper alpha" }, { "code": null, "e": 2308, "s": 2300, "text": "Syntax:" }, { "code": null, "e": 2332, "s": 2308, "text": "<ol type = “1|b|A|i|I”>" }, { "code": null, "e": 2343, "s": 2332, "text": "Example 1:" }, { "code": null, "e": 2348, "s": 2343, "text": "HTML" }, { "code": "<html><head> <title>ordered list</title></head><body> <h1>Example of ordered list in default</h1> <ol > <li>Sachin</li> <li>Manoj</li> <li>Parth</li> <li>sujay</li> <li>Amraditya</li> </ol></body></html>", "e": 2600, "s": 2348, "text": null }, { "code": null, "e": 2608, "s": 2600, "text": "Output:" }, { "code": null, "e": 2619, "s": 2608, "text": "Example 2:" }, { "code": null, "e": 2624, "s": 2619, "text": "HTML" }, { "code": "<html><head> <title>ordered list</title></head><body> <h1>Example of ordered list whose type = \"A\"</h1> <ol type=\"A\"> <li>Sachin</li> <li>Manoj</li> </ol> <h1>Example of reverse ordered list</h1> <ol reversed> <li>Parth</li> <li>sujay</li> </ol> <h1>Example of ordered list start from 10</h1> <ol start = \"10\"> <li>Pushpa</li> <li>Purvi</li> </ol> </body></html>", "e": 3073, "s": 2624, "text": null }, { "code": null, "e": 3081, "s": 3073, "text": "Output:" }, { "code": null, "e": 3346, "s": 3081, "text": " An unordered list defines a list of items in which the order of the items does not. Or in other words, unordered list tag is used to create a unordered list. It is also known as bulleted list. In unordered list each element in the list is defined using <li> tag. " }, { "code": null, "e": 3354, "s": 3346, "text": "Syntax:" }, { "code": null, "e": 3374, "s": 3354, "text": "<ul> content </ul> " }, { "code": null, "e": 3404, "s": 3374, "text": "Attributes of unordered list:" }, { "code": null, "e": 3582, "s": 3404, "text": "List-style-type: This attribute is used to specifies the bullet style that will be used as the list item marker. The value of this attribute is None/disc(default)/circle/square." }, { "code": null, "e": 3590, "s": 3582, "text": "Syntax:" }, { "code": null, "e": 3637, "s": 3590, "text": "<ul style=”list-style-type:square|disc|none;”>" }, { "code": null, "e": 3648, "s": 3637, "text": "Example 1:" }, { "code": null, "e": 3653, "s": 3648, "text": "HTML" }, { "code": "<html><head> <title>unordered list</title></head><body> <h1>Example of unordered list in default</h1> <ul> <li>Sachin</li> <li>Manoj</li> <li>Parth</li> <li>sujay</li> <li>Amraditya</li> </ul></body></html>", "e": 3908, "s": 3653, "text": null }, { "code": null, "e": 3916, "s": 3908, "text": "Output:" }, { "code": null, "e": 3927, "s": 3916, "text": "Example 2:" }, { "code": null, "e": 3932, "s": 3927, "text": "HTML" }, { "code": "<html><head> <title>unordered list</title></head><body> <h2>Example of unordered list in circle</h2> <ul style=\"list-style-type:circle;\"> <li>sachin</li> <li>manoj</li> </ul> <h2>Example of unordered list in disk</h2> <ul style=\"list-style-type:disk;\"> <li>Priya</li> <li>Mohit</li> </ul> <h2>Example of unordered list in square</h2> <ul style=\"list-style-type:square;\"> <li>Pinky</li> <li>Punam</li> </ul> <h2>Example of unordered list in none</h2> <ul style=\"list-style-type:none;\"> <li>Mukti</li> <li>Dhama</li> </ul></body></html>", "e": 4563, "s": 3932, "text": null }, { "code": null, "e": 4571, "s": 4563, "text": "Output:" }, { "code": null, "e": 4678, "s": 4571, "text": "Description list is a list in which each term contain its description. This tag contain <dt> and <dd> tag." }, { "code": null, "e": 4733, "s": 4678, "text": "<dt></dt>: This tag is used to define the name or term" }, { "code": null, "e": 4782, "s": 4733, "text": "<dd><dd>: this tag is used to describe the term." }, { "code": null, "e": 4790, "s": 4782, "text": "Syntax:" }, { "code": null, "e": 4809, "s": 4790, "text": "<dl> content </dl>" }, { "code": null, "e": 4818, "s": 4809, "text": "Example:" }, { "code": null, "e": 4823, "s": 4818, "text": "HTML" }, { "code": "<html><head> <title>Description list</title></head><body> <h2>Example of description list</h2> <dl> <dt>Python:</dt> <dd>It is a programming language</dd> <dt>C++:</dt> <dd>It is also a programming language</dd> </dl> </body></html>", "e": 5101, "s": 4823, "text": null }, { "code": null, "e": 5109, "s": 5101, "text": "Output:" }, { "code": null, "e": 5127, "s": 5109, "text": "gulshankumarar231" }, { "code": null, "e": 5137, "s": 5127, "text": "rs1686740" }, { "code": null, "e": 5152, "s": 5137, "text": "varshagumber28" }, { "code": null, "e": 5159, "s": 5152, "text": "Picked" }, { "code": null, "e": 5167, "s": 5159, "text": "class 7" }, { "code": null, "e": 5183, "s": 5167, "text": "School Learning" }, { "code": null, "e": 5202, "s": 5183, "text": "School Programming" }, { "code": null, "e": 5300, "s": 5202, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5326, "s": 5300, "text": "Flora and Fauna of Ladakh" }, { "code": null, "e": 5343, "s": 5326, "text": "Akbar's Policies" }, { "code": null, "e": 5378, "s": 5343, "text": "Working of the Government in India" }, { "code": null, "e": 5404, "s": 5378, "text": "Components of Environment" }, { "code": null, "e": 5433, "s": 5404, "text": "Equality in Indian Democracy" }, { "code": null, "e": 5453, "s": 5433, "text": "Libraries in Python" }, { "code": null, "e": 5488, "s": 5453, "text": "What are Different Output Devices?" }, { "code": null, "e": 5537, "s": 5488, "text": "Generations of Computers - Computer Fundamentals" }, { "code": null, "e": 5558, "s": 5537, "text": "GeeksforGeeks School" } ]
HTMLCollection for Loop
10 Jan, 2022 It is not recommended to use a for/in loop to loop through an HTMLCollection because this type of loop is used for iterating through properties of an object. The HTMLCollection contains other properties that may be returned along with the required elements. There are 3 methods that can be used to properly loop through an HTMLCollection. Method 1: Using the for/of loop: The for/of loop is used to loop over values of an iterable object. This includes arrays, strings, nodeLists, and HTMLCollections.The syntax of this loop is similar to the for/in loop. The object must be iterable to be used with this loop.Syntax:for (item of iterable) { // code to be executed}Example:<!DOCTYPE html><html> <head> <title>For loop for HTMLCollection elements</title></head> <body> <h1 style="color: green">GeeksforGeeks</h1> <b>For loop for HTMLCollection elements</b> <p>This is paragraph 1.</p> <p>This is paragraph 2.</p> <script type="text/javascript"> // get a HTMLCollection of elements in the page let collection = document.getElementsByTagName("p"); // regular for loop for (let i = 0; i < collection.length; i++) { console.log(collection[i]); } </script></body> </html>Console Output: The syntax of this loop is similar to the for/in loop. The object must be iterable to be used with this loop. Syntax: for (item of iterable) { // code to be executed} Example: <!DOCTYPE html><html> <head> <title>For loop for HTMLCollection elements</title></head> <body> <h1 style="color: green">GeeksforGeeks</h1> <b>For loop for HTMLCollection elements</b> <p>This is paragraph 1.</p> <p>This is paragraph 2.</p> <script type="text/javascript"> // get a HTMLCollection of elements in the page let collection = document.getElementsByTagName("p"); // regular for loop for (let i = 0; i < collection.length; i++) { console.log(collection[i]); } </script></body> </html> Console Output: Method 2: Using the Array.from() method to convert the HTMLCollection to an ArrayThe Array.from() method is used to create a new Array from an array-like or iterable object. The HTMLCollection is passed to this method to convert it into an Array.The forEach() method can now be used to iterate over the elements like an array and display them.Syntax:Array.from(collection).forEach(function (element) { console.log(element) });Example:<!DOCTYPE html><html> <head> <title>For loop for HTMLCollection elements</title></head> <body> <h1 style="color: green">GeeksforGeeks</h1> <b>For loop for HTMLCollection elements</b> <p>This is paragraph 1.</p> <p>This is paragraph 2.</p> <script type="text/javascript"> // get a HTMLCollection of elements in the page let collection = document.getElementsByTagName("p"); // convert to an array using Array.from() Array.from(collection).forEach(function(element) { console.log(element) }); </script></body> </html>Output: The forEach() method can now be used to iterate over the elements like an array and display them. Syntax: Array.from(collection).forEach(function (element) { console.log(element) }); Example: <!DOCTYPE html><html> <head> <title>For loop for HTMLCollection elements</title></head> <body> <h1 style="color: green">GeeksforGeeks</h1> <b>For loop for HTMLCollection elements</b> <p>This is paragraph 1.</p> <p>This is paragraph 2.</p> <script type="text/javascript"> // get a HTMLCollection of elements in the page let collection = document.getElementsByTagName("p"); // convert to an array using Array.from() Array.from(collection).forEach(function(element) { console.log(element) }); </script></body> </html> Output: Method 3: Using a normal for loopThe elements can be iterated through by using a normal for loop. The number of elements in the HTMLCollection can be found out by using the length property of the collection. A for loop is then run to the number of elements.Each of the items can be accessed by using square brackets with their respective index.Syntax:for (let i = 0; i < collection.length; i++) { console.log(collection[i]); }Example:<!DOCTYPE html><html> <head> <title>For loop for HTMLCollection elements</title></head> <body> <h1 style="color: green">GeeksforGeeks</h1> <b>For loop for HTMLCollection elements</b> <p>This is paragraph 1.</p> <p>This is paragraph 2.</p> <script type="text/javascript"> // get a HTMLCollection of elements in the page let collection = document.getElementsByTagName("p"); // using for loop for (let i = 0; i < collection.length; i++) { console.log(collection[i]); }); </script></body> </html>Output: Each of the items can be accessed by using square brackets with their respective index. Syntax: for (let i = 0; i < collection.length; i++) { console.log(collection[i]); } Example: <!DOCTYPE html><html> <head> <title>For loop for HTMLCollection elements</title></head> <body> <h1 style="color: green">GeeksforGeeks</h1> <b>For loop for HTMLCollection elements</b> <p>This is paragraph 1.</p> <p>This is paragraph 2.</p> <script type="text/javascript"> // get a HTMLCollection of elements in the page let collection = document.getElementsByTagName("p"); // using for loop for (let i = 0; i < collection.length; i++) { console.log(collection[i]); }); </script></body> </html> Output: JavaScript-Misc Picked JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array How to append HTML code to a div using JavaScript ? Difference Between PUT and PATCH Request Top 10 Projects For Beginners To Practice HTML and CSS Skills Installation of Node.js on Linux Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n10 Jan, 2022" }, { "code": null, "e": 286, "s": 28, "text": "It is not recommended to use a for/in loop to loop through an HTMLCollection because this type of loop is used for iterating through properties of an object. The HTMLCollection contains other properties that may be returned along with the required elements." }, { "code": null, "e": 367, "s": 286, "text": "There are 3 methods that can be used to properly loop through an HTMLCollection." }, { "code": null, "e": 1282, "s": 367, "text": "Method 1: Using the for/of loop: The for/of loop is used to loop over values of an iterable object. This includes arrays, strings, nodeLists, and HTMLCollections.The syntax of this loop is similar to the for/in loop. The object must be iterable to be used with this loop.Syntax:for (item of iterable) { // code to be executed}Example:<!DOCTYPE html><html> <head> <title>For loop for HTMLCollection elements</title></head> <body> <h1 style=\"color: green\">GeeksforGeeks</h1> <b>For loop for HTMLCollection elements</b> <p>This is paragraph 1.</p> <p>This is paragraph 2.</p> <script type=\"text/javascript\"> // get a HTMLCollection of elements in the page let collection = document.getElementsByTagName(\"p\"); // regular for loop for (let i = 0; i < collection.length; i++) { console.log(collection[i]); } </script></body> </html>Console Output:" }, { "code": null, "e": 1392, "s": 1282, "text": "The syntax of this loop is similar to the for/in loop. The object must be iterable to be used with this loop." }, { "code": null, "e": 1400, "s": 1392, "text": "Syntax:" }, { "code": "for (item of iterable) { // code to be executed}", "e": 1450, "s": 1400, "text": null }, { "code": null, "e": 1459, "s": 1450, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title>For loop for HTMLCollection elements</title></head> <body> <h1 style=\"color: green\">GeeksforGeeks</h1> <b>For loop for HTMLCollection elements</b> <p>This is paragraph 1.</p> <p>This is paragraph 2.</p> <script type=\"text/javascript\"> // get a HTMLCollection of elements in the page let collection = document.getElementsByTagName(\"p\"); // regular for loop for (let i = 0; i < collection.length; i++) { console.log(collection[i]); } </script></body> </html>", "e": 2024, "s": 1459, "text": null }, { "code": null, "e": 2040, "s": 2024, "text": "Console Output:" }, { "code": null, "e": 3080, "s": 2040, "text": "Method 2: Using the Array.from() method to convert the HTMLCollection to an ArrayThe Array.from() method is used to create a new Array from an array-like or iterable object. The HTMLCollection is passed to this method to convert it into an Array.The forEach() method can now be used to iterate over the elements like an array and display them.Syntax:Array.from(collection).forEach(function (element) { console.log(element) });Example:<!DOCTYPE html><html> <head> <title>For loop for HTMLCollection elements</title></head> <body> <h1 style=\"color: green\">GeeksforGeeks</h1> <b>For loop for HTMLCollection elements</b> <p>This is paragraph 1.</p> <p>This is paragraph 2.</p> <script type=\"text/javascript\"> // get a HTMLCollection of elements in the page let collection = document.getElementsByTagName(\"p\"); // convert to an array using Array.from() Array.from(collection).forEach(function(element) { console.log(element) }); </script></body> </html>Output:" }, { "code": null, "e": 3178, "s": 3080, "text": "The forEach() method can now be used to iterate over the elements like an array and display them." }, { "code": null, "e": 3186, "s": 3178, "text": "Syntax:" }, { "code": "Array.from(collection).forEach(function (element) { console.log(element) });", "e": 3275, "s": 3186, "text": null }, { "code": null, "e": 3284, "s": 3275, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title>For loop for HTMLCollection elements</title></head> <body> <h1 style=\"color: green\">GeeksforGeeks</h1> <b>For loop for HTMLCollection elements</b> <p>This is paragraph 1.</p> <p>This is paragraph 2.</p> <script type=\"text/javascript\"> // get a HTMLCollection of elements in the page let collection = document.getElementsByTagName(\"p\"); // convert to an array using Array.from() Array.from(collection).forEach(function(element) { console.log(element) }); </script></body> </html>", "e": 3871, "s": 3284, "text": null }, { "code": null, "e": 3879, "s": 3871, "text": "Output:" }, { "code": null, "e": 4885, "s": 3879, "text": "Method 3: Using a normal for loopThe elements can be iterated through by using a normal for loop. The number of elements in the HTMLCollection can be found out by using the length property of the collection. A for loop is then run to the number of elements.Each of the items can be accessed by using square brackets with their respective index.Syntax:for (let i = 0; i < collection.length; i++) { console.log(collection[i]); }Example:<!DOCTYPE html><html> <head> <title>For loop for HTMLCollection elements</title></head> <body> <h1 style=\"color: green\">GeeksforGeeks</h1> <b>For loop for HTMLCollection elements</b> <p>This is paragraph 1.</p> <p>This is paragraph 2.</p> <script type=\"text/javascript\"> // get a HTMLCollection of elements in the page let collection = document.getElementsByTagName(\"p\"); // using for loop for (let i = 0; i < collection.length; i++) { console.log(collection[i]); }); </script></body> </html>Output:" }, { "code": null, "e": 4973, "s": 4885, "text": "Each of the items can be accessed by using square brackets with their respective index." }, { "code": null, "e": 4981, "s": 4973, "text": "Syntax:" }, { "code": "for (let i = 0; i < collection.length; i++) { console.log(collection[i]); }", "e": 5069, "s": 4981, "text": null }, { "code": null, "e": 5078, "s": 5069, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title>For loop for HTMLCollection elements</title></head> <body> <h1 style=\"color: green\">GeeksforGeeks</h1> <b>For loop for HTMLCollection elements</b> <p>This is paragraph 1.</p> <p>This is paragraph 2.</p> <script type=\"text/javascript\"> // get a HTMLCollection of elements in the page let collection = document.getElementsByTagName(\"p\"); // using for loop for (let i = 0; i < collection.length; i++) { console.log(collection[i]); }); </script></body> </html>", "e": 5631, "s": 5078, "text": null }, { "code": null, "e": 5639, "s": 5631, "text": "Output:" }, { "code": null, "e": 5655, "s": 5639, "text": "JavaScript-Misc" }, { "code": null, "e": 5662, "s": 5655, "text": "Picked" }, { "code": null, "e": 5673, "s": 5662, "text": "JavaScript" }, { "code": null, "e": 5690, "s": 5673, "text": "Web Technologies" }, { "code": null, "e": 5717, "s": 5690, "text": "Web technologies Questions" }, { "code": null, "e": 5815, "s": 5717, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5876, "s": 5815, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 5948, "s": 5876, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 5988, "s": 5948, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 6040, "s": 5988, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 6081, "s": 6040, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 6143, "s": 6081, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 6176, "s": 6143, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 6237, "s": 6176, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 6287, "s": 6237, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
JavaFX | Cursor class with examples
08 Aug, 2018 Cursor class is a part of JavaFX. Cursor class is used to encapsulate the bitmap representation of the mouse cursor. The cursor class has several predefined cursors that can be used according to the needs of the programmer. Commonly used Methods: Below programs will illustrate the use of the cursor class: Java program to set some predefined cursor to the by passing string identifier as arguments: This program creates a Cursor named cursor_. The cursor will be set to the scene using the function setCursor().we will create a label. The label will be created inside a scene, which in turn will be hosted inside a stage. The function setTitle() is used to provide title to the stage. Then a tile pane is created, on which addChildren() method is called to attach the label inside the scene. Finally, the show() method is called to display the final results.// Java program to set some predefined cursor// to the by passing string identifier as argumentsimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.control.Label;import javafx.stage.Stage;import javafx.scene.Cursor; public class cursor_0 extends Application { // launch the application public void start(Stage stage) { // set title for the stage stage.setTitle("Creating Cursor"); // create a stack pane TilePane tilepane = new TilePane(); // create a label Label label = new Label("Cursor Example"); // add button tilepane.getChildren().add(label); // create a scene Scene scene = new Scene(tilepane, 200, 200); // create a cursor Cursor cursor_ = Cursor.cursor("WAIT"); // set cursor for the scene scene.setCursor(cursor_); // set the scene stage.setScene(scene); stage.show(); } // Main Method public static void main(String args[]) { // launch the application launch(args); }}Output:Video Playerhttps://media.geeksforgeeks.org/wp-content/uploads/Cursor_1.mp400:0000:0000:51Use Up/Down Arrow keys to increase or decrease volume.Java program to set some predefined cursor to the scene: This program creates a Button indicated by the name button respectively. We will create an array of predefined cursors named cursor_. The cursor will be set to the scene using the function setCursor() from the list of predefined cursor cursor_. The button will be created inside a scene, which in turn will be hosted inside a stage. We would create a label. The function setTitle() is used to provide title to the stage. Then a tile pane is created, on which addChildren() method is called to attach the button and label inside the scene. Finally, the show() method is called to display the final results.we would create an event handler to handle the button events. The event handler would be added to the button using setOnAction() function. When the button will be pressed the cursor of the scene will be changed by using the function setCursor().// Java program to set some predefined// cursor to the sceneimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.control.Label;import javafx.stage.Stage;import javafx.scene.Cursor; public class cursor_1 extends Application { // counter of cursorint i = 0; // launch the applicationpublic void start(Stage stage){ // set title for the stage stage.setTitle("Creating Cursor"); // create a button Button button = new Button("cursor"); // create a stack pane TilePane tilepane = new TilePane(); // create a label Label label = new Label("Cursor Example"); // create a cursor with predefined cursor Cursor cursor_[] = {Cursor.CLOSED_HAND, Cursor.CROSSHAIR, Cursor.DEFAULT, Cursor.DISAPPEAR, Cursor.E_RESIZE, Cursor.H_RESIZE, Cursor.HAND, Cursor.MOVE, Cursor.N_RESIZE, Cursor.NE_RESIZE, Cursor.NONE, Cursor.NW_RESIZE, Cursor.OPEN_HAND, Cursor.SE_RESIZE, Cursor.SW_RESIZE, Cursor.TEXT, Cursor.V_RESIZE, Cursor.W_RESIZE, Cursor.WAIT}; // add button tilepane.getChildren().add(button); tilepane.getChildren().add(label); // create a scene Scene scene = new Scene(tilepane, 200, 200); // set cursor for the scene scene.setCursor(cursor_[0]); // action event EventHandler<ActionEvent> event = new EventHandler<ActionEvent>() { public void handle(ActionEvent e) { if (i == cursor_.length - 1) i = -1; // change the cursor scene.setCursor(cursor_[++i]); } }; // when button is pressed button.setOnAction(event); // set the scene stage.setScene(scene); stage.show();} // Main Methodpublic static void main(String args[]){ // launch the application launch(args);}}Output:Video Playerhttps://media.geeksforgeeks.org/wp-content/uploads/Cursor_1.mp400:0000:0000:51Use Up/Down Arrow keys to increase or decrease volume. Java program to set some predefined cursor to the by passing string identifier as arguments: This program creates a Cursor named cursor_. The cursor will be set to the scene using the function setCursor().we will create a label. The label will be created inside a scene, which in turn will be hosted inside a stage. The function setTitle() is used to provide title to the stage. Then a tile pane is created, on which addChildren() method is called to attach the label inside the scene. Finally, the show() method is called to display the final results.// Java program to set some predefined cursor// to the by passing string identifier as argumentsimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.control.Label;import javafx.stage.Stage;import javafx.scene.Cursor; public class cursor_0 extends Application { // launch the application public void start(Stage stage) { // set title for the stage stage.setTitle("Creating Cursor"); // create a stack pane TilePane tilepane = new TilePane(); // create a label Label label = new Label("Cursor Example"); // add button tilepane.getChildren().add(label); // create a scene Scene scene = new Scene(tilepane, 200, 200); // create a cursor Cursor cursor_ = Cursor.cursor("WAIT"); // set cursor for the scene scene.setCursor(cursor_); // set the scene stage.setScene(scene); stage.show(); } // Main Method public static void main(String args[]) { // launch the application launch(args); }}Output:Video Playerhttps://media.geeksforgeeks.org/wp-content/uploads/Cursor_1.mp400:0000:0000:51Use Up/Down Arrow keys to increase or decrease volume. // Java program to set some predefined cursor// to the by passing string identifier as argumentsimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.control.Label;import javafx.stage.Stage;import javafx.scene.Cursor; public class cursor_0 extends Application { // launch the application public void start(Stage stage) { // set title for the stage stage.setTitle("Creating Cursor"); // create a stack pane TilePane tilepane = new TilePane(); // create a label Label label = new Label("Cursor Example"); // add button tilepane.getChildren().add(label); // create a scene Scene scene = new Scene(tilepane, 200, 200); // create a cursor Cursor cursor_ = Cursor.cursor("WAIT"); // set cursor for the scene scene.setCursor(cursor_); // set the scene stage.setScene(scene); stage.show(); } // Main Method public static void main(String args[]) { // launch the application launch(args); }} Output: Java program to set some predefined cursor to the scene: This program creates a Button indicated by the name button respectively. We will create an array of predefined cursors named cursor_. The cursor will be set to the scene using the function setCursor() from the list of predefined cursor cursor_. The button will be created inside a scene, which in turn will be hosted inside a stage. We would create a label. The function setTitle() is used to provide title to the stage. Then a tile pane is created, on which addChildren() method is called to attach the button and label inside the scene. Finally, the show() method is called to display the final results.we would create an event handler to handle the button events. The event handler would be added to the button using setOnAction() function. When the button will be pressed the cursor of the scene will be changed by using the function setCursor().// Java program to set some predefined// cursor to the sceneimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.control.Label;import javafx.stage.Stage;import javafx.scene.Cursor; public class cursor_1 extends Application { // counter of cursorint i = 0; // launch the applicationpublic void start(Stage stage){ // set title for the stage stage.setTitle("Creating Cursor"); // create a button Button button = new Button("cursor"); // create a stack pane TilePane tilepane = new TilePane(); // create a label Label label = new Label("Cursor Example"); // create a cursor with predefined cursor Cursor cursor_[] = {Cursor.CLOSED_HAND, Cursor.CROSSHAIR, Cursor.DEFAULT, Cursor.DISAPPEAR, Cursor.E_RESIZE, Cursor.H_RESIZE, Cursor.HAND, Cursor.MOVE, Cursor.N_RESIZE, Cursor.NE_RESIZE, Cursor.NONE, Cursor.NW_RESIZE, Cursor.OPEN_HAND, Cursor.SE_RESIZE, Cursor.SW_RESIZE, Cursor.TEXT, Cursor.V_RESIZE, Cursor.W_RESIZE, Cursor.WAIT}; // add button tilepane.getChildren().add(button); tilepane.getChildren().add(label); // create a scene Scene scene = new Scene(tilepane, 200, 200); // set cursor for the scene scene.setCursor(cursor_[0]); // action event EventHandler<ActionEvent> event = new EventHandler<ActionEvent>() { public void handle(ActionEvent e) { if (i == cursor_.length - 1) i = -1; // change the cursor scene.setCursor(cursor_[++i]); } }; // when button is pressed button.setOnAction(event); // set the scene stage.setScene(scene); stage.show();} // Main Methodpublic static void main(String args[]){ // launch the application launch(args);}}Output:Video Playerhttps://media.geeksforgeeks.org/wp-content/uploads/Cursor_1.mp400:0000:0000:51Use Up/Down Arrow keys to increase or decrease volume. // Java program to set some predefined// cursor to the sceneimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.control.Label;import javafx.stage.Stage;import javafx.scene.Cursor; public class cursor_1 extends Application { // counter of cursorint i = 0; // launch the applicationpublic void start(Stage stage){ // set title for the stage stage.setTitle("Creating Cursor"); // create a button Button button = new Button("cursor"); // create a stack pane TilePane tilepane = new TilePane(); // create a label Label label = new Label("Cursor Example"); // create a cursor with predefined cursor Cursor cursor_[] = {Cursor.CLOSED_HAND, Cursor.CROSSHAIR, Cursor.DEFAULT, Cursor.DISAPPEAR, Cursor.E_RESIZE, Cursor.H_RESIZE, Cursor.HAND, Cursor.MOVE, Cursor.N_RESIZE, Cursor.NE_RESIZE, Cursor.NONE, Cursor.NW_RESIZE, Cursor.OPEN_HAND, Cursor.SE_RESIZE, Cursor.SW_RESIZE, Cursor.TEXT, Cursor.V_RESIZE, Cursor.W_RESIZE, Cursor.WAIT}; // add button tilepane.getChildren().add(button); tilepane.getChildren().add(label); // create a scene Scene scene = new Scene(tilepane, 200, 200); // set cursor for the scene scene.setCursor(cursor_[0]); // action event EventHandler<ActionEvent> event = new EventHandler<ActionEvent>() { public void handle(ActionEvent e) { if (i == cursor_.length - 1) i = -1; // change the cursor scene.setCursor(cursor_[++i]); } }; // when button is pressed button.setOnAction(event); // set the scene stage.setScene(scene); stage.show();} // Main Methodpublic static void main(String args[]){ // launch the application launch(args);}} Output: Note: The above programs might not run in an online IDE. Please use an offline compiler. Reference: https://docs.oracle.com/javafx/2/api/javafx/scene/Cursor.html JavaFX Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n08 Aug, 2018" }, { "code": null, "e": 252, "s": 28, "text": "Cursor class is a part of JavaFX. Cursor class is used to encapsulate the bitmap representation of the mouse cursor. The cursor class has several predefined cursors that can be used according to the needs of the programmer." }, { "code": null, "e": 275, "s": 252, "text": "Commonly used Methods:" }, { "code": null, "e": 335, "s": 275, "text": "Below programs will illustrate the use of the cursor class:" }, { "code": null, "e": 5453, "s": 335, "text": "Java program to set some predefined cursor to the by passing string identifier as arguments: This program creates a Cursor named cursor_. The cursor will be set to the scene using the function setCursor().we will create a label. The label will be created inside a scene, which in turn will be hosted inside a stage. The function setTitle() is used to provide title to the stage. Then a tile pane is created, on which addChildren() method is called to attach the label inside the scene. Finally, the show() method is called to display the final results.// Java program to set some predefined cursor// to the by passing string identifier as argumentsimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.control.Label;import javafx.stage.Stage;import javafx.scene.Cursor; public class cursor_0 extends Application { // launch the application public void start(Stage stage) { // set title for the stage stage.setTitle(\"Creating Cursor\"); // create a stack pane TilePane tilepane = new TilePane(); // create a label Label label = new Label(\"Cursor Example\"); // add button tilepane.getChildren().add(label); // create a scene Scene scene = new Scene(tilepane, 200, 200); // create a cursor Cursor cursor_ = Cursor.cursor(\"WAIT\"); // set cursor for the scene scene.setCursor(cursor_); // set the scene stage.setScene(scene); stage.show(); } // Main Method public static void main(String args[]) { // launch the application launch(args); }}Output:Video Playerhttps://media.geeksforgeeks.org/wp-content/uploads/Cursor_1.mp400:0000:0000:51Use Up/Down Arrow keys to increase or decrease volume.Java program to set some predefined cursor to the scene: This program creates a Button indicated by the name button respectively. We will create an array of predefined cursors named cursor_. The cursor will be set to the scene using the function setCursor() from the list of predefined cursor cursor_. The button will be created inside a scene, which in turn will be hosted inside a stage. We would create a label. The function setTitle() is used to provide title to the stage. Then a tile pane is created, on which addChildren() method is called to attach the button and label inside the scene. Finally, the show() method is called to display the final results.we would create an event handler to handle the button events. The event handler would be added to the button using setOnAction() function. When the button will be pressed the cursor of the scene will be changed by using the function setCursor().// Java program to set some predefined// cursor to the sceneimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.control.Label;import javafx.stage.Stage;import javafx.scene.Cursor; public class cursor_1 extends Application { // counter of cursorint i = 0; // launch the applicationpublic void start(Stage stage){ // set title for the stage stage.setTitle(\"Creating Cursor\"); // create a button Button button = new Button(\"cursor\"); // create a stack pane TilePane tilepane = new TilePane(); // create a label Label label = new Label(\"Cursor Example\"); // create a cursor with predefined cursor Cursor cursor_[] = {Cursor.CLOSED_HAND, Cursor.CROSSHAIR, Cursor.DEFAULT, Cursor.DISAPPEAR, Cursor.E_RESIZE, Cursor.H_RESIZE, Cursor.HAND, Cursor.MOVE, Cursor.N_RESIZE, Cursor.NE_RESIZE, Cursor.NONE, Cursor.NW_RESIZE, Cursor.OPEN_HAND, Cursor.SE_RESIZE, Cursor.SW_RESIZE, Cursor.TEXT, Cursor.V_RESIZE, Cursor.W_RESIZE, Cursor.WAIT}; // add button tilepane.getChildren().add(button); tilepane.getChildren().add(label); // create a scene Scene scene = new Scene(tilepane, 200, 200); // set cursor for the scene scene.setCursor(cursor_[0]); // action event EventHandler<ActionEvent> event = new EventHandler<ActionEvent>() { public void handle(ActionEvent e) { if (i == cursor_.length - 1) i = -1; // change the cursor scene.setCursor(cursor_[++i]); } }; // when button is pressed button.setOnAction(event); // set the scene stage.setScene(scene); stage.show();} // Main Methodpublic static void main(String args[]){ // launch the application launch(args);}}Output:Video Playerhttps://media.geeksforgeeks.org/wp-content/uploads/Cursor_1.mp400:0000:0000:51Use Up/Down Arrow keys to increase or decrease volume." }, { "code": null, "e": 7396, "s": 5453, "text": "Java program to set some predefined cursor to the by passing string identifier as arguments: This program creates a Cursor named cursor_. The cursor will be set to the scene using the function setCursor().we will create a label. The label will be created inside a scene, which in turn will be hosted inside a stage. The function setTitle() is used to provide title to the stage. Then a tile pane is created, on which addChildren() method is called to attach the label inside the scene. Finally, the show() method is called to display the final results.// Java program to set some predefined cursor// to the by passing string identifier as argumentsimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.control.Label;import javafx.stage.Stage;import javafx.scene.Cursor; public class cursor_0 extends Application { // launch the application public void start(Stage stage) { // set title for the stage stage.setTitle(\"Creating Cursor\"); // create a stack pane TilePane tilepane = new TilePane(); // create a label Label label = new Label(\"Cursor Example\"); // add button tilepane.getChildren().add(label); // create a scene Scene scene = new Scene(tilepane, 200, 200); // create a cursor Cursor cursor_ = Cursor.cursor(\"WAIT\"); // set cursor for the scene scene.setCursor(cursor_); // set the scene stage.setScene(scene); stage.show(); } // Main Method public static void main(String args[]) { // launch the application launch(args); }}Output:Video Playerhttps://media.geeksforgeeks.org/wp-content/uploads/Cursor_1.mp400:0000:0000:51Use Up/Down Arrow keys to increase or decrease volume." }, { "code": "// Java program to set some predefined cursor// to the by passing string identifier as argumentsimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.control.Label;import javafx.stage.Stage;import javafx.scene.Cursor; public class cursor_0 extends Application { // launch the application public void start(Stage stage) { // set title for the stage stage.setTitle(\"Creating Cursor\"); // create a stack pane TilePane tilepane = new TilePane(); // create a label Label label = new Label(\"Cursor Example\"); // add button tilepane.getChildren().add(label); // create a scene Scene scene = new Scene(tilepane, 200, 200); // create a cursor Cursor cursor_ = Cursor.cursor(\"WAIT\"); // set cursor for the scene scene.setCursor(cursor_); // set the scene stage.setScene(scene); stage.show(); } // Main Method public static void main(String args[]) { // launch the application launch(args); }}", "e": 8636, "s": 7396, "text": null }, { "code": null, "e": 8644, "s": 8636, "text": "Output:" }, { "code": null, "e": 11820, "s": 8644, "text": "Java program to set some predefined cursor to the scene: This program creates a Button indicated by the name button respectively. We will create an array of predefined cursors named cursor_. The cursor will be set to the scene using the function setCursor() from the list of predefined cursor cursor_. The button will be created inside a scene, which in turn will be hosted inside a stage. We would create a label. The function setTitle() is used to provide title to the stage. Then a tile pane is created, on which addChildren() method is called to attach the button and label inside the scene. Finally, the show() method is called to display the final results.we would create an event handler to handle the button events. The event handler would be added to the button using setOnAction() function. When the button will be pressed the cursor of the scene will be changed by using the function setCursor().// Java program to set some predefined// cursor to the sceneimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.control.Label;import javafx.stage.Stage;import javafx.scene.Cursor; public class cursor_1 extends Application { // counter of cursorint i = 0; // launch the applicationpublic void start(Stage stage){ // set title for the stage stage.setTitle(\"Creating Cursor\"); // create a button Button button = new Button(\"cursor\"); // create a stack pane TilePane tilepane = new TilePane(); // create a label Label label = new Label(\"Cursor Example\"); // create a cursor with predefined cursor Cursor cursor_[] = {Cursor.CLOSED_HAND, Cursor.CROSSHAIR, Cursor.DEFAULT, Cursor.DISAPPEAR, Cursor.E_RESIZE, Cursor.H_RESIZE, Cursor.HAND, Cursor.MOVE, Cursor.N_RESIZE, Cursor.NE_RESIZE, Cursor.NONE, Cursor.NW_RESIZE, Cursor.OPEN_HAND, Cursor.SE_RESIZE, Cursor.SW_RESIZE, Cursor.TEXT, Cursor.V_RESIZE, Cursor.W_RESIZE, Cursor.WAIT}; // add button tilepane.getChildren().add(button); tilepane.getChildren().add(label); // create a scene Scene scene = new Scene(tilepane, 200, 200); // set cursor for the scene scene.setCursor(cursor_[0]); // action event EventHandler<ActionEvent> event = new EventHandler<ActionEvent>() { public void handle(ActionEvent e) { if (i == cursor_.length - 1) i = -1; // change the cursor scene.setCursor(cursor_[++i]); } }; // when button is pressed button.setOnAction(event); // set the scene stage.setScene(scene); stage.show();} // Main Methodpublic static void main(String args[]){ // launch the application launch(args);}}Output:Video Playerhttps://media.geeksforgeeks.org/wp-content/uploads/Cursor_1.mp400:0000:0000:51Use Up/Down Arrow keys to increase or decrease volume." }, { "code": "// Java program to set some predefined// cursor to the sceneimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.control.Label;import javafx.stage.Stage;import javafx.scene.Cursor; public class cursor_1 extends Application { // counter of cursorint i = 0; // launch the applicationpublic void start(Stage stage){ // set title for the stage stage.setTitle(\"Creating Cursor\"); // create a button Button button = new Button(\"cursor\"); // create a stack pane TilePane tilepane = new TilePane(); // create a label Label label = new Label(\"Cursor Example\"); // create a cursor with predefined cursor Cursor cursor_[] = {Cursor.CLOSED_HAND, Cursor.CROSSHAIR, Cursor.DEFAULT, Cursor.DISAPPEAR, Cursor.E_RESIZE, Cursor.H_RESIZE, Cursor.HAND, Cursor.MOVE, Cursor.N_RESIZE, Cursor.NE_RESIZE, Cursor.NONE, Cursor.NW_RESIZE, Cursor.OPEN_HAND, Cursor.SE_RESIZE, Cursor.SW_RESIZE, Cursor.TEXT, Cursor.V_RESIZE, Cursor.W_RESIZE, Cursor.WAIT}; // add button tilepane.getChildren().add(button); tilepane.getChildren().add(label); // create a scene Scene scene = new Scene(tilepane, 200, 200); // set cursor for the scene scene.setCursor(cursor_[0]); // action event EventHandler<ActionEvent> event = new EventHandler<ActionEvent>() { public void handle(ActionEvent e) { if (i == cursor_.length - 1) i = -1; // change the cursor scene.setCursor(cursor_[++i]); } }; // when button is pressed button.setOnAction(event); // set the scene stage.setScene(scene); stage.show();} // Main Methodpublic static void main(String args[]){ // launch the application launch(args);}}", "e": 13938, "s": 11820, "text": null }, { "code": null, "e": 13946, "s": 13938, "text": "Output:" }, { "code": null, "e": 14035, "s": 13946, "text": "Note: The above programs might not run in an online IDE. Please use an offline compiler." }, { "code": null, "e": 14108, "s": 14035, "text": "Reference: https://docs.oracle.com/javafx/2/api/javafx/scene/Cursor.html" }, { "code": null, "e": 14115, "s": 14108, "text": "JavaFX" }, { "code": null, "e": 14120, "s": 14115, "text": "Java" }, { "code": null, "e": 14125, "s": 14120, "text": "Java" } ]
PyQt5 – Getting the current index of selected item in ComboBox
22 Apr, 2020 In this article we will see how we can get the current index of the selected item the combo box. In order to do this we will use the currentIndex method. Syntax : combo_box.currentIndex() Argument : It takes no argument Return : It return integer i.e index of selected item Steps for implementation – 1. Create a combo box2. Add items to combo box3. Create push button4. Add action to the push button5. Create label to show count5. Inside the action get the index of current item selected in combo box with the help of currentIndex method and store it in variable6. Show the index in label with the help of setText method. Below is the implementation – # importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("Python ") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating a combo box widget self.combo_box = QComboBox(self) # setting geometry of combo box self.combo_box.setGeometry(200, 150, 120, 30) # geek list geek_list = ["Geek", "Geeky Geek", "Legend Geek", "Ultra Legend Geek"] # adding list of items to combo box self.combo_box.addItems(geek_list) # creating push button button = QPushButton("Show content ", self) print(self.combo_box.count()) # adding action to button button.pressed.connect(self.find) # creating label self.label = QLabel(self) # setting geometry of the label self.label.setGeometry(200, 200, 200, 30) def find(self): # finding the current item index in combo box index = self.combo_box.currentIndex() # showing content on the screen though label self.label.setText("Index : " + str(index)) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec()) Output : Python PyQt5-ComboBox Python-gui Python-PyQt Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Different ways to create Pandas Dataframe How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Python OOPs Concepts Introduction To PYTHON Convert integer to string in Python How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method Create a Pandas DataFrame from Lists
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Apr, 2020" }, { "code": null, "e": 182, "s": 28, "text": "In this article we will see how we can get the current index of the selected item the combo box. In order to do this we will use the currentIndex method." }, { "code": null, "e": 216, "s": 182, "text": "Syntax : combo_box.currentIndex()" }, { "code": null, "e": 248, "s": 216, "text": "Argument : It takes no argument" }, { "code": null, "e": 302, "s": 248, "text": "Return : It return integer i.e index of selected item" }, { "code": null, "e": 329, "s": 302, "text": "Steps for implementation –" }, { "code": null, "e": 651, "s": 329, "text": "1. Create a combo box2. Add items to combo box3. Create push button4. Add action to the push button5. Create label to show count5. Inside the action get the index of current item selected in combo box with the help of currentIndex method and store it in variable6. Show the index in label with the help of setText method." }, { "code": null, "e": 681, "s": 651, "text": "Below is the implementation –" }, { "code": "# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"Python \") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating a combo box widget self.combo_box = QComboBox(self) # setting geometry of combo box self.combo_box.setGeometry(200, 150, 120, 30) # geek list geek_list = [\"Geek\", \"Geeky Geek\", \"Legend Geek\", \"Ultra Legend Geek\"] # adding list of items to combo box self.combo_box.addItems(geek_list) # creating push button button = QPushButton(\"Show content \", self) print(self.combo_box.count()) # adding action to button button.pressed.connect(self.find) # creating label self.label = QLabel(self) # setting geometry of the label self.label.setGeometry(200, 200, 200, 30) def find(self): # finding the current item index in combo box index = self.combo_box.currentIndex() # showing content on the screen though label self.label.setText(\"Index : \" + str(index)) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())", "e": 2276, "s": 681, "text": null }, { "code": null, "e": 2285, "s": 2276, "text": "Output :" }, { "code": null, "e": 2307, "s": 2285, "text": "Python PyQt5-ComboBox" }, { "code": null, "e": 2318, "s": 2307, "text": "Python-gui" }, { "code": null, "e": 2330, "s": 2318, "text": "Python-PyQt" }, { "code": null, "e": 2337, "s": 2330, "text": "Python" }, { "code": null, "e": 2435, "s": 2337, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2477, "s": 2435, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2509, "s": 2477, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2538, "s": 2509, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2565, "s": 2538, "text": "Python Classes and Objects" }, { "code": null, "e": 2586, "s": 2565, "text": "Python OOPs Concepts" }, { "code": null, "e": 2609, "s": 2586, "text": "Introduction To PYTHON" }, { "code": null, "e": 2645, "s": 2609, "text": "Convert integer to string in Python" }, { "code": null, "e": 2701, "s": 2645, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2732, "s": 2701, "text": "Python | os.path.join() method" } ]
Python – Itertools.chain.from_iterable()
09 Mar, 2020 Python’s Itertool is a module that provides various functions that work on iterators to produce complex iterators. This module works as a fast, memory-efficient tool that is used either by themselves or in combination to form iterator algebra. Note: For more information, refer to Python Itertools The functions under itertools can be classified into 3 categories Functions producing Infinite IteratorsFunctions producing Iterators terminating on the shortest input sequenceFunctions producing Combinatoric generators Functions producing Infinite Iterators Functions producing Iterators terminating on the shortest input sequence Functions producing Combinatoric generators The function chain.from_iterable() comes under the category of terminating iterators. This function takes a single iterable as an argument and all the elements of the input iterable should also be iterable and it returns a flattened iterable containing all the elements of the input iterable. Syntax : chain.from_iterable(iterable) Example #1: # Importing chain class from itertoolsfrom itertools import chain # Single iterable containing iterable# elements(strings) is passed as inputfrom_iterable = chain.from_iterable(['geeks', 'for', 'geeks']) # printing the flattened iterableprint(list(from_iterable)) Output : [‘g’, ‘e’, ‘e’, ‘k’, ‘s’, ‘f’, ‘o’, ‘r’, ‘g’, ‘e’, ‘e’, ‘k’, ‘s’] Example #2: # Importing chain class from itertoolsfrom itertools import chain # Single iterable containing iterable# elements(strings and list) is passed# as inputfrom_iterable = chain.from_iterable(['geeks', 'for', 'geeks', ['w', 'i', 'n', 's']]) # printing the flattened iterableprint(list(from_iterable)) Output : [‘g’, ‘e’, ‘e’, ‘k’, ‘s’, ‘f’, ‘o’, ‘r’, ‘g’, ‘e’, ‘e’, ‘k’, ‘s’, ‘w’, ‘i’, ‘n’, ‘s’] Python-itertools Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python | os.path.join() method Introduction To PYTHON Python OOPs Concepts How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Get unique values from a list Create a directory in Python
[ { "code": null, "e": 54, "s": 26, "text": "\n09 Mar, 2020" }, { "code": null, "e": 298, "s": 54, "text": "Python’s Itertool is a module that provides various functions that work on iterators to produce complex iterators. This module works as a fast, memory-efficient tool that is used either by themselves or in combination to form iterator algebra." }, { "code": null, "e": 352, "s": 298, "text": "Note: For more information, refer to Python Itertools" }, { "code": null, "e": 418, "s": 352, "text": "The functions under itertools can be classified into 3 categories" }, { "code": null, "e": 572, "s": 418, "text": "Functions producing Infinite IteratorsFunctions producing Iterators terminating on the shortest input sequenceFunctions producing Combinatoric generators" }, { "code": null, "e": 611, "s": 572, "text": "Functions producing Infinite Iterators" }, { "code": null, "e": 684, "s": 611, "text": "Functions producing Iterators terminating on the shortest input sequence" }, { "code": null, "e": 728, "s": 684, "text": "Functions producing Combinatoric generators" }, { "code": null, "e": 1021, "s": 728, "text": "The function chain.from_iterable() comes under the category of terminating iterators. This function takes a single iterable as an argument and all the elements of the input iterable should also be iterable and it returns a flattened iterable containing all the elements of the input iterable." }, { "code": null, "e": 1061, "s": 1021, "text": "Syntax :\nchain.from_iterable(iterable)\n" }, { "code": null, "e": 1073, "s": 1061, "text": "Example #1:" }, { "code": "# Importing chain class from itertoolsfrom itertools import chain # Single iterable containing iterable# elements(strings) is passed as inputfrom_iterable = chain.from_iterable(['geeks', 'for', 'geeks']) # printing the flattened iterableprint(list(from_iterable))", "e": 1414, "s": 1073, "text": null }, { "code": null, "e": 1423, "s": 1414, "text": "Output :" }, { "code": null, "e": 1489, "s": 1423, "text": "[‘g’, ‘e’, ‘e’, ‘k’, ‘s’, ‘f’, ‘o’, ‘r’, ‘g’, ‘e’, ‘e’, ‘k’, ‘s’]" }, { "code": null, "e": 1501, "s": 1489, "text": "Example #2:" }, { "code": "# Importing chain class from itertoolsfrom itertools import chain # Single iterable containing iterable# elements(strings and list) is passed# as inputfrom_iterable = chain.from_iterable(['geeks', 'for', 'geeks', ['w', 'i', 'n', 's']]) # printing the flattened iterableprint(list(from_iterable))", "e": 1910, "s": 1501, "text": null }, { "code": null, "e": 1919, "s": 1910, "text": "Output :" }, { "code": null, "e": 2005, "s": 1919, "text": "[‘g’, ‘e’, ‘e’, ‘k’, ‘s’, ‘f’, ‘o’, ‘r’, ‘g’, ‘e’, ‘e’, ‘k’, ‘s’, ‘w’, ‘i’, ‘n’, ‘s’]" }, { "code": null, "e": 2022, "s": 2005, "text": "Python-itertools" }, { "code": null, "e": 2029, "s": 2022, "text": "Python" }, { "code": null, "e": 2127, "s": 2029, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2159, "s": 2127, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2186, "s": 2159, "text": "Python Classes and Objects" }, { "code": null, "e": 2217, "s": 2186, "text": "Python | os.path.join() method" }, { "code": null, "e": 2240, "s": 2217, "text": "Introduction To PYTHON" }, { "code": null, "e": 2261, "s": 2240, "text": "Python OOPs Concepts" }, { "code": null, "e": 2317, "s": 2261, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2359, "s": 2317, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2401, "s": 2359, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2440, "s": 2401, "text": "Python | Get unique values from a list" } ]
C++ Program To Check Whether The Length Of Given Linked List Is Even Or Odd
10 Jan, 2022 Given a linked list, the task is to make a function which checks whether the length of the linked list is even or odd. Examples: Input : 1->2->3->4->NULL Output : Even Input : 1->2->3->4->5->NULL Output : Odd Method 1: Count the codes linearly Traverse the entire Linked List and keep counting the number of nodes. As soon as the loop is finished, we can check if the count is even or odd. You may try it yourself.Method 2: Stepping 2 nodes at a time Approach: 1. Take a pointer and move that pointer two nodes at a time 2. At the end, if the pointer is NULL then length is Even, else Odd. C++ // C++ program to check length // of a given linklist #include <bits/stdc++.h>using namespace std; // Defining structure class Node { public: int data; Node* next; }; // Function to check the length // of linklist int LinkedListLength(Node* head) { while (head && head->next) { head = head->next->next; } if (!head) return 0; return 1; } // Push function void push(Node** head, int info) { // Allocating node Node* node = new Node(); // Info into node node->data = info; // Next of new node to head node->next = (*head); // head points to new node (*head) = node; } // Driver code int main(void) { Node* head = NULL; // Adding elements to Linked List push(&head, 4); push(&head, 5); push(&head, 7); push(&head, 2); push(&head, 9); push(&head, 6); push(&head, 1); push(&head, 2); push(&head, 0); push(&head, 5); push(&head, 5); int check = LinkedListLength(head); // Checking for length of // linklist if(check == 0) { cout << "Even"; } else { cout << "Odd"; } return 0; } // This is code is contributed by rathbhupendra Output: Odd Time Complexity: O(n) Space Complexity: O(1) Please refer complete article on Check whether the length of given linked list is Even or Odd for more details! C++ Programs Linked List Linked List Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Passing a function as a parameter in C++ Const keyword in C++ cout in C++ Program to implement Singly Linked List in C++ using class Different ways to print elements of vector Linked List | Set 1 (Introduction) Linked List | Set 2 (Inserting a node) Reverse a linked list Stack Data Structure (Introduction and Program) Linked List | Set 3 (Deleting a node)
[ { "code": null, "e": 28, "s": 0, "text": "\n10 Jan, 2022" }, { "code": null, "e": 157, "s": 28, "text": "Given a linked list, the task is to make a function which checks whether the length of the linked list is even or odd. Examples:" }, { "code": null, "e": 237, "s": 157, "text": "Input : 1->2->3->4->NULL\nOutput : Even\nInput : 1->2->3->4->5->NULL\nOutput : Odd" }, { "code": null, "e": 489, "s": 237, "text": "Method 1: Count the codes linearly Traverse the entire Linked List and keep counting the number of nodes. As soon as the loop is finished, we can check if the count is even or odd. You may try it yourself.Method 2: Stepping 2 nodes at a time Approach:" }, { "code": null, "e": 618, "s": 489, "text": "1. Take a pointer and move that pointer two nodes at a time\n2. At the end, if the pointer is NULL then length is Even, else Odd." }, { "code": null, "e": 622, "s": 618, "text": "C++" }, { "code": "// C++ program to check length // of a given linklist #include <bits/stdc++.h>using namespace std; // Defining structure class Node { public: int data; Node* next; }; // Function to check the length // of linklist int LinkedListLength(Node* head) { while (head && head->next) { head = head->next->next; } if (!head) return 0; return 1; } // Push function void push(Node** head, int info) { // Allocating node Node* node = new Node(); // Info into node node->data = info; // Next of new node to head node->next = (*head); // head points to new node (*head) = node; } // Driver code int main(void) { Node* head = NULL; // Adding elements to Linked List push(&head, 4); push(&head, 5); push(&head, 7); push(&head, 2); push(&head, 9); push(&head, 6); push(&head, 1); push(&head, 2); push(&head, 0); push(&head, 5); push(&head, 5); int check = LinkedListLength(head); // Checking for length of // linklist if(check == 0) { cout << \"Even\"; } else { cout << \"Odd\"; } return 0; } // This is code is contributed by rathbhupendra", "e": 1865, "s": 622, "text": null }, { "code": null, "e": 1875, "s": 1865, "text": "Output: " }, { "code": null, "e": 1879, "s": 1875, "text": "Odd" }, { "code": null, "e": 1924, "s": 1879, "text": "Time Complexity: O(n) Space Complexity: O(1)" }, { "code": null, "e": 2036, "s": 1924, "text": "Please refer complete article on Check whether the length of given linked list is Even or Odd for more details!" }, { "code": null, "e": 2049, "s": 2036, "text": "C++ Programs" }, { "code": null, "e": 2061, "s": 2049, "text": "Linked List" }, { "code": null, "e": 2073, "s": 2061, "text": "Linked List" }, { "code": null, "e": 2171, "s": 2073, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2212, "s": 2171, "text": "Passing a function as a parameter in C++" }, { "code": null, "e": 2233, "s": 2212, "text": "Const keyword in C++" }, { "code": null, "e": 2245, "s": 2233, "text": "cout in C++" }, { "code": null, "e": 2304, "s": 2245, "text": "Program to implement Singly Linked List in C++ using class" }, { "code": null, "e": 2347, "s": 2304, "text": "Different ways to print elements of vector" }, { "code": null, "e": 2382, "s": 2347, "text": "Linked List | Set 1 (Introduction)" }, { "code": null, "e": 2421, "s": 2382, "text": "Linked List | Set 2 (Inserting a node)" }, { "code": null, "e": 2443, "s": 2421, "text": "Reverse a linked list" }, { "code": null, "e": 2491, "s": 2443, "text": "Stack Data Structure (Introduction and Program)" } ]
What are Java Records and How to Use them Alongside Constructors and Methods?
22 Jun, 2022 As developers and software engineers, our aim is to always design ways to obtain maximum efficiency and if we need to write less code for it, then that’s a blessing. In Java, a record is a special type of class declaration aimed at reducing the boilerplate code. Java records were introduced with the intention to be used as a fast way to create data carrier classes, i.e. the classes whose objective is to simply contain data and carry it between modules, also known as POJOs (Plain Old Java Objects) and DTOs (Data Transfer Objects). Record was introduced in Java SE 14 as a preview feature, which is a feature whose design, implementation, and specification are complete but it is not a permanent addition to the language, which means that the feature may or may not exist in the future versions of the language. Java SE 15 extends the preview feature with additional capabilities such as local record classes. Let us first do discuss why we need records prior to implementing them. Let us consider an illustration for this. Illustration: Consider a simple class Employee, whose objective is to contain an employee’s data such as its ID and name and act as a data carrier to be transferred across modules. To create such a simple class, you’d need to define its constructor, getter, and setter methods, and if you want to use the object with data structures like HashMap or print the contents of its objects as a string, we would need to override methods such as equals(), hashCode(), and toString(). Example Java // Java Program Illustrating Program Without usage of// Records // A sample Employee classclass Employee { // Member variables of this class private String firstName; private String lastName; private int Id; // Constructor of this class public Employee(String firstName, String lastName, int Id) { // This keyword refers to current instance itself this.firstName = firstName; this.lastName = lastName; this.Id = Id; } // Setter and Getter methods // Setter-getter Method 1 public void setFirstName(String firstName) { this.firstName = firstName; } // Setter-getter Method 2 // to get the first name of employee public String getFirstName() { return firstName; } // Setter-getter Method 3 // To set the last name of employees public void setLastName(String lasstName) { // This keyword refers to current object itself this.lastName = lastName; } // Setter-getter Method 3 // To set the last name of employees public String getLastName() { return lastName; } // Setter-getter Method 4 // To set the last name of employees public void setId(int Id) { this.Id = Id; } // Setter-getter Method 5 // To set the last name of employees public int getId() { return Id; } // Setter-getter Method 6 public String toString() { // Return the attributes return "Employee [firstName=" + firstName + ", lastName=" + lastName + ", Id=" + Id + "]"; } // Method 7 // Overriding hashCode method @Override public int hashCode() { // Final variable final int prime = 31; int result = 1; result = prime * result + Id; result = prime * result + ((firstName == null) ? 0 : firstName.hashCode()); result = prime * result + ((lastName == null) ? 0 : lastName.hashCode()); return result; } // Method 8 // Overriding equals method to // implement with data structures @Override public boolean equals(Object obj) { // This refers to current instance itself if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Employee other = (Employee)obj; if (Id != other.Id) return false; if (firstName == null) { if (other.firstName != null) return false; } else if (!firstName.equals(other.firstName)) return false; if (lastName == null) { if (other.lastName != null) return false; } else if (!lastName.equals(other.lastName)) return false; return true; }} Note: It is over 100 of lines of code just to create a class that carries some data. Now let’s look at what it would take to create a similar class using Record to get its usage prior to discussing properties of a records which are given below: Some more Properties of Records You can use nested classes and interfaces inside a record. You can have nested records too, which will implicitly be static. A record can implement interfaces. You can create a generic record class. It is possible to use local record classes (since Java SE 15). Records are serializable. As tempting as it might be to use records for data carrier objects, records are still a preview feature in Java. Furthermore, as they are intended to be used only as a carrier of data, defining our own access methods and other instance methods would defy the purpose. Records can be used to reduce the work done by the developer, but internally the performance difference between a record and a class is not that wide public record Employee(int id, String firstName, String lastName) {} That’s it! Only 2 lines of code, that is all you need to implement those 80 lines of code using Record. To know how Java implements such a feature, we are going to learn how to set it up ourselves first. Now let us discuss the steps with visual aids demonstrating java records. Since Records is a feature of Java SE 14 we would need JDK 14 on our machine. Download Oracle JDK 14 from this archive for your machine. After downloading and installing JDK-14 to the Java folder along with any other java versions follow the below steps. Note: For this tutorial Eclipse IDE is used. Steps in setting up java records Step 1: Create a new Java project and select JavaSE-14 as the execution environment. Step 2: If this is your first time using JDK-14 then there will be some more steps that you’ll need to follow in order to configure for records to work. You might see this type of exception mark on your project folder. Step 3: To fix that, on the top, go to Window -> Preferences. Step 4: In the Preferences window, click on Installed JREs and then click on Add as shown below: Step 5: Now on the Add JRE window that opens, select Standard VM and click Next. You’ll see a new window open to select a JRE, now click on Directory and navigate to where your jdk-14 is installed and select that folder. Click on Finish. Step 6: Checkmark the JDK-14 that you just added and Apply it. Step 7: We are not done yet. Since records are a preview feature, we need to enable them to use it. On your Project Explorer window on the left side, select your project and right-click and go to its Properties. Step 8: On the window that opens, to the right of it, from the various options select Java Compiler. After that on the left side, uncheck the settings marked with red arrows in the image, and check mark the setting highlighted with green. Doing that will enable the preview features. Step 9: After clicking on Apply and Close, you’ll see a prompt asking whether you want to rebuild the project. Select Yes. After configuring the environment we can now proceed to write code for records. Coding Records are declared by writing records instead of class in the class declaration. While defining a record, all the instance fields are written as parameters. The constructor, getter methods, toString(), equals(), and hashCode() are generated by the Java compiler during compile time. One thing to note here is that records do not provide setter methods, as it is expected that the value to instance variables is provided while creating the object. // A simple Employee class to be used as a DTO public record Employee(int id, String firstName, String lastName) { } Example 1 // Creating Employee object and showcasing its use cases // Main class class GFG { // Main driver method public static void main(String args[]) { // Creating object with default constructor Employee e1 = new Employee(1001, "Derok", "Dranf"); // Auto generated getter methods System.out.println(e1.id() + " " + e1.firstName() + " " + e1.lastName()); // Auto-generated toString() method System.out.println(e1.toString()); } } Output: 1001 Derok Dranf Employee[id=1001, firstName=Derok, lastName=Dranf] We will notice that the getter methods are not similar in naming convention to the normal getter methods that are created (ex: getFirstName()), instead they are simply denoted by the name of the field (ex: firstName()). Now let us expand our previous example to test out these functionalities. That is not all that a record can do. Records also provide us the capability to: Create our own constructors. In records, you can create a parameterized constructor, which calls the default constructor with the provided parameters inside its body. You can also create compact constructors which are similar to default constructors with the twist that you can add some extra functionality such as checks inside the constructor body. Create instance methods. Like any other class, you can create and call instance methods for the record class. Create static fields. Records restrict us to write the instance variables only as parameters but enable the use of static variables and static methods. Example 1 // Java Program Illustrating a Record class // defining constructors, instance methods // and static fields // Record class public record Employee(int id, String firstName, String lastName) { // Instance fields need to be present in the record's // parameters but record can define static fields. static int empToken; // Constructor 1 of this class // Compact Constructor public Employee { if (id < 100) { throw new IllegalArgumentException( "Employee Id cannot be below 100."); } if (firstName.length() < 2) { throw new IllegalArgumentException( "First name must be 2 characters or more."); } } // Constructor 2 of this class // Alternative Constructor public Employee(int id, String firstName) { this(id, firstName, null); } // Instance methods public void getFullName() { if (lastName == null) System.out.println(firstName()); else System.out.println(firstName() + " " + lastName()); } // Static methods public static int generateEmployeeToken() { return ++empToken; } } Example 2 Java // Java Program to Illustrate Record's functionalities // Main classclass GFG { // Main driver method public static void main(String args[]) { // Creating object with default constructor Employee e1 = new Employee(1001, "Derok", "Dranf"); // auto generated getter methods System.out.println(e1.id() + " " + e1.firstName() + " " + e1.lastName()); // Auto-generated toString() method System.out.println(e1.toString()); // Creating object with parameterized constructor Employee e2 = new Employee(1002, "Seren"); // Using instance methods e2.getFullName(); // Using static methods System.out.println("Employee " + e2.id() + " Token = " + e2.generateEmployeeToken()); // Using the equals() method System.out.print("Is e1 equal to e2: " + e1.equals(e2)); }} Output: 1001 Derok Dranf Employee[id=1001, firstName=Derok, lastName=Dranf] Seren Employee 1002 Token = 1 Is e1 equal to e2: false Geek, have you ever wondered what magic does the Compiler does? As discussed above record is just a special declaration of a class and internally the compiler converts it into a normal class with some restrictions, which makes it different from the typical classes. When the Java file is compiled by the Java compiler to the bytecode, the .class file produced contains the extended declaration of the record class. By looking at that file we can make out more about records. Bytecode produced for the Employee record that we created above is as follows: public final class Employee extends java.lang.Record { private final int id; private final java.lang.String firstName; private final java.lang.String lastName; static int empToken; public Employee(int id, java.lang.String firstName, java.lang.String lastName) { /* compiled code */ } public Employee(int id, java.lang.String firstName) { /* compiled code */ } public void getFullName() { /* compiled code */ } public static int generateEmployeeToken() { /* compiled code */ } public int id() { /* compiled code */ } public java.lang.String firstName() { /* compiled code */ } public java.lang.String lastName() { /* compiled code */ } public java.lang.String toString() { /* compiled code */ } public final int hashCode() { /* compiled code */ } public final boolean equals(java.lang.Object o) { /* compiled code */ } } Conclusion: If we take some time to observe the bytecode, you will notice the following: The record has been replaced by class. The class and its data members have been declared as final. This implies that this class cannot be extended, i.e. cannot be inherited, and is immutable as well. The class extends java.lang.Record. This means that all records are a subclass of Record defined in java.lang package. There is a default constructor and a parameterized constructor. You’ll notice that there is no separate declaration for the compact constructor that we defined. This is because the compact constructor does not generate a separate constructor but adds its code to the start of the default constructor’s body. The instance and static methods are declared as they were. The toString(), hashCode(), and equals() methods have been auto-generated by the compiler.. sagartomar9927 rkbhola5 hajianmohammadmahdi582 Java-Constructors Picked Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Introduction to Java Constructors in Java Exceptions in Java Generics in Java Functional Interfaces in Java Java Programming Examples Strings in Java Differences between JDK, JRE and JVM Abstraction in Java
[ { "code": null, "e": 52, "s": 24, "text": "\n22 Jun, 2022" }, { "code": null, "e": 219, "s": 52, "text": "As developers and software engineers, our aim is to always design ways to obtain maximum efficiency and if we need to write less code for it, then that’s a blessing. " }, { "code": null, "e": 967, "s": 219, "text": "In Java, a record is a special type of class declaration aimed at reducing the boilerplate code. Java records were introduced with the intention to be used as a fast way to create data carrier classes, i.e. the classes whose objective is to simply contain data and carry it between modules, also known as POJOs (Plain Old Java Objects) and DTOs (Data Transfer Objects). Record was introduced in Java SE 14 as a preview feature, which is a feature whose design, implementation, and specification are complete but it is not a permanent addition to the language, which means that the feature may or may not exist in the future versions of the language. Java SE 15 extends the preview feature with additional capabilities such as local record classes." }, { "code": null, "e": 1081, "s": 967, "text": "Let us first do discuss why we need records prior to implementing them. Let us consider an illustration for this." }, { "code": null, "e": 1095, "s": 1081, "text": "Illustration:" }, { "code": null, "e": 1557, "s": 1095, "text": "Consider a simple class Employee, whose objective is to contain an employee’s data such as its ID and name and act as a data carrier to be transferred across modules. To create such a simple class, you’d need to define its constructor, getter, and setter methods, and if you want to use the object with data structures like HashMap or print the contents of its objects as a string, we would need to override methods such as equals(), hashCode(), and toString()." }, { "code": null, "e": 1565, "s": 1557, "text": "Example" }, { "code": null, "e": 1570, "s": 1565, "text": "Java" }, { "code": "// Java Program Illustrating Program Without usage of// Records // A sample Employee classclass Employee { // Member variables of this class private String firstName; private String lastName; private int Id; // Constructor of this class public Employee(String firstName, String lastName, int Id) { // This keyword refers to current instance itself this.firstName = firstName; this.lastName = lastName; this.Id = Id; } // Setter and Getter methods // Setter-getter Method 1 public void setFirstName(String firstName) { this.firstName = firstName; } // Setter-getter Method 2 // to get the first name of employee public String getFirstName() { return firstName; } // Setter-getter Method 3 // To set the last name of employees public void setLastName(String lasstName) { // This keyword refers to current object itself this.lastName = lastName; } // Setter-getter Method 3 // To set the last name of employees public String getLastName() { return lastName; } // Setter-getter Method 4 // To set the last name of employees public void setId(int Id) { this.Id = Id; } // Setter-getter Method 5 // To set the last name of employees public int getId() { return Id; } // Setter-getter Method 6 public String toString() { // Return the attributes return \"Employee [firstName=\" + firstName + \", lastName=\" + lastName + \", Id=\" + Id + \"]\"; } // Method 7 // Overriding hashCode method @Override public int hashCode() { // Final variable final int prime = 31; int result = 1; result = prime * result + Id; result = prime * result + ((firstName == null) ? 0 : firstName.hashCode()); result = prime * result + ((lastName == null) ? 0 : lastName.hashCode()); return result; } // Method 8 // Overriding equals method to // implement with data structures @Override public boolean equals(Object obj) { // This refers to current instance itself if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Employee other = (Employee)obj; if (Id != other.Id) return false; if (firstName == null) { if (other.firstName != null) return false; } else if (!firstName.equals(other.firstName)) return false; if (lastName == null) { if (other.lastName != null) return false; } else if (!lastName.equals(other.lastName)) return false; return true; }}", "e": 4480, "s": 1570, "text": null }, { "code": null, "e": 4565, "s": 4480, "text": "Note: It is over 100 of lines of code just to create a class that carries some data." }, { "code": null, "e": 4725, "s": 4565, "text": "Now let’s look at what it would take to create a similar class using Record to get its usage prior to discussing properties of a records which are given below:" }, { "code": null, "e": 4757, "s": 4725, "text": "Some more Properties of Records" }, { "code": null, "e": 4816, "s": 4757, "text": "You can use nested classes and interfaces inside a record." }, { "code": null, "e": 4882, "s": 4816, "text": "You can have nested records too, which will implicitly be static." }, { "code": null, "e": 4917, "s": 4882, "text": "A record can implement interfaces." }, { "code": null, "e": 4956, "s": 4917, "text": "You can create a generic record class." }, { "code": null, "e": 5019, "s": 4956, "text": "It is possible to use local record classes (since Java SE 15)." }, { "code": null, "e": 5045, "s": 5019, "text": "Records are serializable." }, { "code": null, "e": 5463, "s": 5045, "text": "As tempting as it might be to use records for data carrier objects, records are still a preview feature in Java. Furthermore, as they are intended to be used only as a carrier of data, defining our own access methods and other instance methods would defy the purpose. Records can be used to reduce the work done by the developer, but internally the performance difference between a record and a class is not that wide" }, { "code": null, "e": 5532, "s": 5463, "text": "public record Employee(int id, String firstName, String lastName) {}" }, { "code": null, "e": 6065, "s": 5532, "text": "That’s it! Only 2 lines of code, that is all you need to implement those 80 lines of code using Record. To know how Java implements such a feature, we are going to learn how to set it up ourselves first. Now let us discuss the steps with visual aids demonstrating java records. Since Records is a feature of Java SE 14 we would need JDK 14 on our machine. Download Oracle JDK 14 from this archive for your machine. After downloading and installing JDK-14 to the Java folder along with any other java versions follow the below steps." }, { "code": null, "e": 6111, "s": 6065, "text": "Note: For this tutorial Eclipse IDE is used. " }, { "code": null, "e": 6145, "s": 6111, "text": "Steps in setting up java records " }, { "code": null, "e": 6230, "s": 6145, "text": "Step 1: Create a new Java project and select JavaSE-14 as the execution environment." }, { "code": null, "e": 6449, "s": 6230, "text": "Step 2: If this is your first time using JDK-14 then there will be some more steps that you’ll need to follow in order to configure for records to work. You might see this type of exception mark on your project folder." }, { "code": null, "e": 6511, "s": 6449, "text": "Step 3: To fix that, on the top, go to Window -> Preferences." }, { "code": null, "e": 6608, "s": 6511, "text": "Step 4: In the Preferences window, click on Installed JREs and then click on Add as shown below:" }, { "code": null, "e": 6846, "s": 6608, "text": "Step 5: Now on the Add JRE window that opens, select Standard VM and click Next. You’ll see a new window open to select a JRE, now click on Directory and navigate to where your jdk-14 is installed and select that folder. Click on Finish." }, { "code": null, "e": 6909, "s": 6846, "text": "Step 6: Checkmark the JDK-14 that you just added and Apply it." }, { "code": null, "e": 7121, "s": 6909, "text": "Step 7: We are not done yet. Since records are a preview feature, we need to enable them to use it. On your Project Explorer window on the left side, select your project and right-click and go to its Properties." }, { "code": null, "e": 7405, "s": 7121, "text": "Step 8: On the window that opens, to the right of it, from the various options select Java Compiler. After that on the left side, uncheck the settings marked with red arrows in the image, and check mark the setting highlighted with green. Doing that will enable the preview features." }, { "code": null, "e": 7528, "s": 7405, "text": "Step 9: After clicking on Apply and Close, you’ll see a prompt asking whether you want to rebuild the project. Select Yes." }, { "code": null, "e": 7608, "s": 7528, "text": "After configuring the environment we can now proceed to write code for records." }, { "code": null, "e": 8064, "s": 7608, "text": "Coding Records are declared by writing records instead of class in the class declaration. While defining a record, all the instance fields are written as parameters. The constructor, getter methods, toString(), equals(), and hashCode() are generated by the Java compiler during compile time. One thing to note here is that records do not provide setter methods, as it is expected that the value to instance variables is provided while creating the object." }, { "code": null, "e": 8205, "s": 8064, "text": "// A simple Employee class to be used as a DTO\n\npublic record Employee(int id, String firstName,\n String lastName) {\n}" }, { "code": null, "e": 8215, "s": 8205, "text": "Example 1" }, { "code": null, "e": 8697, "s": 8215, "text": "// Creating Employee object and showcasing its use cases\n\n// Main class\nclass GFG {\n\n // Main driver method\n public static void main(String args[]) {\n\n // Creating object with default constructor\n Employee e1 = new Employee(1001, \"Derok\", \"Dranf\");\n\n // Auto generated getter methods\n System.out.println(e1.id() + \" \" + e1.firstName()\n + \" \" + e1.lastName());\n\n // Auto-generated toString() method\n System.out.println(e1.toString());\n }\n}" }, { "code": null, "e": 8705, "s": 8697, "text": "Output:" }, { "code": null, "e": 8773, "s": 8705, "text": "1001 Derok Dranf\nEmployee[id=1001, firstName=Derok, lastName=Dranf]" }, { "code": null, "e": 9067, "s": 8773, "text": "We will notice that the getter methods are not similar in naming convention to the normal getter methods that are created (ex: getFirstName()), instead they are simply denoted by the name of the field (ex: firstName()). Now let us expand our previous example to test out these functionalities." }, { "code": null, "e": 9148, "s": 9067, "text": "That is not all that a record can do. Records also provide us the capability to:" }, { "code": null, "e": 9499, "s": 9148, "text": "Create our own constructors. In records, you can create a parameterized constructor, which calls the default constructor with the provided parameters inside its body. You can also create compact constructors which are similar to default constructors with the twist that you can add some extra functionality such as checks inside the constructor body." }, { "code": null, "e": 9609, "s": 9499, "text": "Create instance methods. Like any other class, you can create and call instance methods for the record class." }, { "code": null, "e": 9761, "s": 9609, "text": "Create static fields. Records restrict us to write the instance variables only as parameters but enable the use of static variables and static methods." }, { "code": null, "e": 9771, "s": 9761, "text": "Example 1" }, { "code": null, "e": 11034, "s": 9771, "text": "// Java Program Illustrating a Record class\n// defining constructors, instance methods\n// and static fields\n\n// Record class\npublic record Employee(int id, String firstName,\n String lastName)\n{\n\n // Instance fields need to be present in the record's\n // parameters but record can define static fields.\n static int empToken;\n\n // Constructor 1 of this class\n // Compact Constructor\n public Employee\n {\n if (id < 100) {\n throw new IllegalArgumentException(\n \"Employee Id cannot be below 100.\");\n }\n if (firstName.length() < 2) {\n throw new IllegalArgumentException(\n \"First name must be 2 characters or more.\");\n }\n }\n\n // Constructor 2 of this class\n // Alternative Constructor\n public Employee(int id, String firstName)\n {\n this(id, firstName, null);\n }\n\n // Instance methods\n public void getFullName()\n {\n if (lastName == null)\n System.out.println(firstName());\n\n else\n System.out.println(firstName() + \" \"\n + lastName());\n }\n\n // Static methods\n public static int generateEmployeeToken()\n {\n return ++empToken;\n }\n}" }, { "code": null, "e": 11044, "s": 11034, "text": "Example 2" }, { "code": null, "e": 11049, "s": 11044, "text": "Java" }, { "code": "// Java Program to Illustrate Record's functionalities // Main classclass GFG { // Main driver method public static void main(String args[]) { // Creating object with default constructor Employee e1 = new Employee(1001, \"Derok\", \"Dranf\"); // auto generated getter methods System.out.println(e1.id() + \" \" + e1.firstName() + \" \" + e1.lastName()); // Auto-generated toString() method System.out.println(e1.toString()); // Creating object with parameterized constructor Employee e2 = new Employee(1002, \"Seren\"); // Using instance methods e2.getFullName(); // Using static methods System.out.println(\"Employee \" + e2.id() + \" Token = \" + e2.generateEmployeeToken()); // Using the equals() method System.out.print(\"Is e1 equal to e2: \" + e1.equals(e2)); }}", "e": 11941, "s": 11049, "text": null }, { "code": null, "e": 11949, "s": 11941, "text": "Output:" }, { "code": null, "e": 12072, "s": 11949, "text": "1001 Derok Dranf\nEmployee[id=1001, firstName=Derok, lastName=Dranf]\nSeren\nEmployee 1002 Token = 1\nIs e1 equal to e2: false" }, { "code": null, "e": 12136, "s": 12072, "text": "Geek, have you ever wondered what magic does the Compiler does?" }, { "code": null, "e": 12626, "s": 12136, "text": "As discussed above record is just a special declaration of a class and internally the compiler converts it into a normal class with some restrictions, which makes it different from the typical classes. When the Java file is compiled by the Java compiler to the bytecode, the .class file produced contains the extended declaration of the record class. By looking at that file we can make out more about records. Bytecode produced for the Employee record that we created above is as follows:" }, { "code": null, "e": 13498, "s": 12626, "text": "public final class Employee extends java.lang.Record {\n private final int id;\n private final java.lang.String firstName;\n private final java.lang.String lastName;\n static int empToken;\n\n public Employee(int id, java.lang.String firstName, java.lang.String lastName) { /* compiled code */ }\n\n public Employee(int id, java.lang.String firstName) { /* compiled code */ }\n\n public void getFullName() { /* compiled code */ }\n\n public static int generateEmployeeToken() { /* compiled code */ }\n\n public int id() { /* compiled code */ }\n\n public java.lang.String firstName() { /* compiled code */ }\n\n public java.lang.String lastName() { /* compiled code */ }\n\n public java.lang.String toString() { /* compiled code */ }\n\n public final int hashCode() { /* compiled code */ }\n\n public final boolean equals(java.lang.Object o) { /* compiled code */ }\n}" }, { "code": null, "e": 13587, "s": 13498, "text": "Conclusion: If we take some time to observe the bytecode, you will notice the following:" }, { "code": null, "e": 13626, "s": 13587, "text": "The record has been replaced by class." }, { "code": null, "e": 13787, "s": 13626, "text": "The class and its data members have been declared as final. This implies that this class cannot be extended, i.e. cannot be inherited, and is immutable as well." }, { "code": null, "e": 13906, "s": 13787, "text": "The class extends java.lang.Record. This means that all records are a subclass of Record defined in java.lang package." }, { "code": null, "e": 14214, "s": 13906, "text": "There is a default constructor and a parameterized constructor. You’ll notice that there is no separate declaration for the compact constructor that we defined. This is because the compact constructor does not generate a separate constructor but adds its code to the start of the default constructor’s body." }, { "code": null, "e": 14273, "s": 14214, "text": "The instance and static methods are declared as they were." }, { "code": null, "e": 14366, "s": 14273, "text": "The toString(), hashCode(), and equals() methods have been auto-generated by the compiler.. " }, { "code": null, "e": 14381, "s": 14366, "text": "sagartomar9927" }, { "code": null, "e": 14390, "s": 14381, "text": "rkbhola5" }, { "code": null, "e": 14413, "s": 14390, "text": "hajianmohammadmahdi582" }, { "code": null, "e": 14431, "s": 14413, "text": "Java-Constructors" }, { "code": null, "e": 14438, "s": 14431, "text": "Picked" }, { "code": null, "e": 14443, "s": 14438, "text": "Java" }, { "code": null, "e": 14448, "s": 14443, "text": "Java" }, { "code": null, "e": 14546, "s": 14448, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 14561, "s": 14546, "text": "Stream In Java" }, { "code": null, "e": 14582, "s": 14561, "text": "Introduction to Java" }, { "code": null, "e": 14603, "s": 14582, "text": "Constructors in Java" }, { "code": null, "e": 14622, "s": 14603, "text": "Exceptions in Java" }, { "code": null, "e": 14639, "s": 14622, "text": "Generics in Java" }, { "code": null, "e": 14669, "s": 14639, "text": "Functional Interfaces in Java" }, { "code": null, "e": 14695, "s": 14669, "text": "Java Programming Examples" }, { "code": null, "e": 14711, "s": 14695, "text": "Strings in Java" }, { "code": null, "e": 14748, "s": 14711, "text": "Differences between JDK, JRE and JVM" } ]
Can we declare the main () method as final in Java?
Yes, we can declare the main () method as final in Java. The compiler does not throw any error. If we declare any method as final by placing the final keyword then that method becomes the final method. The main use of the final method in Java is they are not overridden. We can not override final methods in subclasses. If we are using inheritance and we need some methods not to overridden in subclasses then we need to make it final so that those methods can't be overridden by subclasses. We can access final methods in the subclass but we can not override final methods. class BaseClass { public final void show(Object o) { System.out.println("BaseClass method"); } } class DerivedClass extends BaseClass { public void show(Integer i) { System.out.println("DerivedClass method"); } } public class Test { public static final void main(String[] args) { // declaring main () method with final keyword. BaseClass b = new BaseClass(); DerivedClass d = new DerivedClass(); b.show(new Integer(0)); d.show(new Integer(0)); } } BaseClass method DerivedClass method
[ { "code": null, "e": 1158, "s": 1062, "text": "Yes, we can declare the main () method as final in Java. The compiler does not throw any error." }, { "code": null, "e": 1264, "s": 1158, "text": "If we declare any method as final by placing the final keyword then that method becomes the final method." }, { "code": null, "e": 1333, "s": 1264, "text": "The main use of the final method in Java is they are not overridden." }, { "code": null, "e": 1382, "s": 1333, "text": "We can not override final methods in subclasses." }, { "code": null, "e": 1554, "s": 1382, "text": "If we are using inheritance and we need some methods not to overridden in subclasses then we need to make it final so that those methods can't be overridden by subclasses." }, { "code": null, "e": 1637, "s": 1554, "text": "We can access final methods in the subclass but we can not override final methods." }, { "code": null, "e": 2139, "s": 1637, "text": "class BaseClass {\n public final void show(Object o) {\n System.out.println(\"BaseClass method\");\n }\n}\nclass DerivedClass extends BaseClass {\n public void show(Integer i) {\n System.out.println(\"DerivedClass method\");\n }\n}\npublic class Test {\n public static final void main(String[] args) { // declaring main () method with final keyword.\n BaseClass b = new BaseClass();\n DerivedClass d = new DerivedClass();\n b.show(new Integer(0));\n d.show(new Integer(0));\n }\n}" }, { "code": null, "e": 2176, "s": 2139, "text": "BaseClass method\nDerivedClass method" } ]
How do I find all documents with a field that is NaN in MongoDB?
To find all documents with a field that is NAN in MongoDB, use the following syntax db.yourCollectionName.find( { yourFieldName: NaN }) Let us first create a collection with documents > db.nanDemo.insertOne({"Score":0/0}); { "acknowledged" : true, "insertedId" : ObjectId("5ca251a26304881c5ce84b8a") } > db.nanDemo.insertOne({"Score":10/5}); { "acknowledged" : true, "insertedId" : ObjectId("5ca2520e6304881c5ce84b8b") } > db.nanDemo.insertOne({"Score":20/0}); { "acknowledged" : true, "insertedId" : ObjectId("5ca252156304881c5ce84b8c") } > db.nanDemo.insertOne({"Score":0/20}); { "acknowledged" : true, "insertedId" : ObjectId("5ca2521e6304881c5ce84b8d") } Following is the query to display all documents from a collection with the help of find() method > db.nanDemo.find().pretty(); This will produce the following output { "_id" : ObjectId("5ca251a26304881c5ce84b8a"), "Score" : NaN } { "_id" : ObjectId("5ca2520e6304881c5ce84b8b"), "Score" : 2 } { "_id" : ObjectId("5ca252156304881c5ce84b8c"), "Score" : Infinity } { "_id" : ObjectId("5ca2521e6304881c5ce84b8d"), "Score" : 0 } Following is the query to find all documents with a field that is NAN in MongoDB > db.nanDemo.find( { Score: 0/0 }); This will produce the following output { "_id" : ObjectId("5ca251a26304881c5ce84b8a"), "Score" : NaN } The alternate query is as follows > db.nanDemo.find( { Score: NaN }) This will produce the following output { "_id" : ObjectId("5ca251a26304881c5ce84b8a"), "Score" : NaN }
[ { "code": null, "e": 1146, "s": 1062, "text": "To find all documents with a field that is NAN in MongoDB, use the following syntax" }, { "code": null, "e": 1198, "s": 1146, "text": "db.yourCollectionName.find( { yourFieldName: NaN })" }, { "code": null, "e": 1246, "s": 1198, "text": "Let us first create a collection with documents" }, { "code": null, "e": 1745, "s": 1246, "text": "> db.nanDemo.insertOne({\"Score\":0/0});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5ca251a26304881c5ce84b8a\")\n}\n> db.nanDemo.insertOne({\"Score\":10/5});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5ca2520e6304881c5ce84b8b\")\n}\n> db.nanDemo.insertOne({\"Score\":20/0});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5ca252156304881c5ce84b8c\")\n}\n> db.nanDemo.insertOne({\"Score\":0/20});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5ca2521e6304881c5ce84b8d\")\n}" }, { "code": null, "e": 1842, "s": 1745, "text": "Following is the query to display all documents from a collection with the help of find() method" }, { "code": null, "e": 1872, "s": 1842, "text": "> db.nanDemo.find().pretty();" }, { "code": null, "e": 1911, "s": 1872, "text": "This will produce the following output" }, { "code": null, "e": 2168, "s": 1911, "text": "{ \"_id\" : ObjectId(\"5ca251a26304881c5ce84b8a\"), \"Score\" : NaN }\n{ \"_id\" : ObjectId(\"5ca2520e6304881c5ce84b8b\"), \"Score\" : 2 }\n{ \"_id\" : ObjectId(\"5ca252156304881c5ce84b8c\"), \"Score\" : Infinity }\n{ \"_id\" : ObjectId(\"5ca2521e6304881c5ce84b8d\"), \"Score\" : 0 }" }, { "code": null, "e": 2249, "s": 2168, "text": "Following is the query to find all documents with a field that is NAN in MongoDB" }, { "code": null, "e": 2285, "s": 2249, "text": "> db.nanDemo.find( { Score: 0/0 });" }, { "code": null, "e": 2324, "s": 2285, "text": "This will produce the following output" }, { "code": null, "e": 2388, "s": 2324, "text": "{ \"_id\" : ObjectId(\"5ca251a26304881c5ce84b8a\"), \"Score\" : NaN }" }, { "code": null, "e": 2422, "s": 2388, "text": "The alternate query is as follows" }, { "code": null, "e": 2457, "s": 2422, "text": "> db.nanDemo.find( { Score: NaN })" }, { "code": null, "e": 2496, "s": 2457, "text": "This will produce the following output" }, { "code": null, "e": 2560, "s": 2496, "text": "{ \"_id\" : ObjectId(\"5ca251a26304881c5ce84b8a\"), \"Score\" : NaN }" } ]
Floodfill Image using Python-Pillow - GeeksforGeeks
10 Jul, 2020 Seed Fill also known as flood fill, is an algorithm used to identify connected paths in a definite enclosed region. The algorithm has an array of practical applications, such as – Optimized pathfinding Paint Bucket Tool a generic tool found in several image processing packages, uses the algorithm internally Mazesolving uses floodfill (paired with traversing algorithms like breadth-first, depth-first and pathfinding algorithms such as A Star, Dijkstra) Used in Image Processing There are various ways in which the algorithm could be implemented such as – Scanline Floodfill (row/column based floodfill) Four/Eight Way Floodfill Threshold less Floodfill (using only identical pixel values) We will be utilizing floodfill algorithm in order to do image processing tasks. For this purpose, we will be using pillow library. To install the library, execute the following command in the command-line:- pip install pillow Note: Several Linux distributions tend to have Python and Pillow preinstalled into them Syntax: ImageDraw.floodfill(image, seed_pos, replace_val, border-None, thresh=0) Parameters:image – Open Image Object (obtained via Image.open, Image.fromarray etc).seed_pos – Seed position (coordinates of the pixel from where the seed value would be obtained).replace_val – Fill color (the color value which would be used for replacement).border – Optional border value (modifies path selection according to border color)thresh – Optional Threshold Value (used to provide tolerance in floodfill, to incorporate similar valued pixel regions) Return: NoneType (modifies the image in place, rather then returning then modified image) Example: Image Used: # Importing the pillow library's # desired modulesfrom PIL import Image, ImageDraw # Opening the image (R prefixed to# string in order to deal with '\'# in paths)img = Image.open(R"sample.png") # Converting the image to RGB modeimg1 = img.convert("RGB") # Coordinates of the pixel whose value# would be used as seedseed = (263, 70) # Pixel Value which would be used for# replacement rep_value = (255, 255, 0) # Calling the floodfill() function and # passing it image, seed, value and # thresh as argumentsImageDraw.floodfill(img, seed, rep_value, thresh=50) # Displaying the imageimg.show() Output: Explanation: After importing the necessary modules required for the task, we firstly create an image object ('PIL.Image.Image'). This image objects acts as an separate in-core copy of the Image file, which could be used separately. Then assign a coordinate value (inside dimensions of the image) for the seed variable. The Coordinates are picked manually, i.e. the user should put in the value of coordinate which is picked intentionally (the value of the pixel coordinate could be verified by using img.getpixel(coord)). The pixel value obtained from these coordinates would be the one which is to be replaced inside the image. Then assign rep_value variable with a RGB color value (yellow in this case). The value is being assigned as a RGB Tuple, which is specific for our particular case as our input image is of RGB color space (img.mode == 'RGB').Note: The rep_value variable will contain value according to the Image mode of the current image, i.e. if img.mode == "L" then rep value will not be of tuple with 3 components, but rather would be of integer. Note: The rep_value variable will contain value according to the Image mode of the current image, i.e. if img.mode == "L" then rep value will not be of tuple with 3 components, but rather would be of integer. Then call the ImageDraw.floodfill() function by passing img, seed, rep_value and thresh as arguments. Since the ImageDraw.floodfill() function modifies the passed image object at place, we don’t need to store the return value (Nonetype) of the function. In the end we display the modified image, using img.show() (Image.show()). Python-pil Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python program to convert a list to string Python String | replace() Reading and Writing to text files in Python sum() function in Python
[ { "code": null, "e": 24415, "s": 24387, "text": "\n10 Jul, 2020" }, { "code": null, "e": 24595, "s": 24415, "text": "Seed Fill also known as flood fill, is an algorithm used to identify connected paths in a definite enclosed region. The algorithm has an array of practical applications, such as –" }, { "code": null, "e": 24617, "s": 24595, "text": "Optimized pathfinding" }, { "code": null, "e": 24724, "s": 24617, "text": "Paint Bucket Tool a generic tool found in several image processing packages, uses the algorithm internally" }, { "code": null, "e": 24871, "s": 24724, "text": "Mazesolving uses floodfill (paired with traversing algorithms like breadth-first, depth-first and pathfinding algorithms such as A Star, Dijkstra)" }, { "code": null, "e": 24896, "s": 24871, "text": "Used in Image Processing" }, { "code": null, "e": 24973, "s": 24896, "text": "There are various ways in which the algorithm could be implemented such as –" }, { "code": null, "e": 25021, "s": 24973, "text": "Scanline Floodfill (row/column based floodfill)" }, { "code": null, "e": 25046, "s": 25021, "text": "Four/Eight Way Floodfill" }, { "code": null, "e": 25107, "s": 25046, "text": "Threshold less Floodfill (using only identical pixel values)" }, { "code": null, "e": 25314, "s": 25107, "text": "We will be utilizing floodfill algorithm in order to do image processing tasks. For this purpose, we will be using pillow library. To install the library, execute the following command in the command-line:-" }, { "code": null, "e": 25334, "s": 25314, "text": "pip install pillow\n" }, { "code": null, "e": 25422, "s": 25334, "text": "Note: Several Linux distributions tend to have Python and Pillow preinstalled into them" }, { "code": null, "e": 25503, "s": 25422, "text": "Syntax: ImageDraw.floodfill(image, seed_pos, replace_val, border-None, thresh=0)" }, { "code": null, "e": 25964, "s": 25503, "text": "Parameters:image – Open Image Object (obtained via Image.open, Image.fromarray etc).seed_pos – Seed position (coordinates of the pixel from where the seed value would be obtained).replace_val – Fill color (the color value which would be used for replacement).border – Optional border value (modifies path selection according to border color)thresh – Optional Threshold Value (used to provide tolerance in floodfill, to incorporate similar valued pixel regions)" }, { "code": null, "e": 26054, "s": 25964, "text": "Return: NoneType (modifies the image in place, rather then returning then modified image)" }, { "code": null, "e": 26063, "s": 26054, "text": "Example:" }, { "code": null, "e": 26075, "s": 26063, "text": "Image Used:" }, { "code": "# Importing the pillow library's # desired modulesfrom PIL import Image, ImageDraw # Opening the image (R prefixed to# string in order to deal with '\\'# in paths)img = Image.open(R\"sample.png\") # Converting the image to RGB modeimg1 = img.convert(\"RGB\") # Coordinates of the pixel whose value# would be used as seedseed = (263, 70) # Pixel Value which would be used for# replacement rep_value = (255, 255, 0) # Calling the floodfill() function and # passing it image, seed, value and # thresh as argumentsImageDraw.floodfill(img, seed, rep_value, thresh=50) # Displaying the imageimg.show()", "e": 26677, "s": 26075, "text": null }, { "code": null, "e": 26685, "s": 26677, "text": "Output:" }, { "code": null, "e": 26698, "s": 26685, "text": "Explanation:" }, { "code": null, "e": 26917, "s": 26698, "text": "After importing the necessary modules required for the task, we firstly create an image object ('PIL.Image.Image'). This image objects acts as an separate in-core copy of the Image file, which could be used separately." }, { "code": null, "e": 27207, "s": 26917, "text": "Then assign a coordinate value (inside dimensions of the image) for the seed variable. The Coordinates are picked manually, i.e. the user should put in the value of coordinate which is picked intentionally (the value of the pixel coordinate could be verified by using img.getpixel(coord))." }, { "code": null, "e": 27314, "s": 27207, "text": "The pixel value obtained from these coordinates would be the one which is to be replaced inside the image." }, { "code": null, "e": 27747, "s": 27314, "text": "Then assign rep_value variable with a RGB color value (yellow in this case). The value is being assigned as a RGB Tuple, which is specific for our particular case as our input image is of RGB color space (img.mode == 'RGB').Note: The rep_value variable will contain value according to the Image mode of the current image, i.e. if img.mode == \"L\" then rep value will not be of tuple with 3 components, but rather would be of integer." }, { "code": null, "e": 27956, "s": 27747, "text": "Note: The rep_value variable will contain value according to the Image mode of the current image, i.e. if img.mode == \"L\" then rep value will not be of tuple with 3 components, but rather would be of integer." }, { "code": null, "e": 28210, "s": 27956, "text": "Then call the ImageDraw.floodfill() function by passing img, seed, rep_value and thresh as arguments. Since the ImageDraw.floodfill() function modifies the passed image object at place, we don’t need to store the return value (Nonetype) of the function." }, { "code": null, "e": 28285, "s": 28210, "text": "In the end we display the modified image, using img.show() (Image.show())." }, { "code": null, "e": 28296, "s": 28285, "text": "Python-pil" }, { "code": null, "e": 28303, "s": 28296, "text": "Python" }, { "code": null, "e": 28401, "s": 28303, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28410, "s": 28401, "text": "Comments" }, { "code": null, "e": 28423, "s": 28410, "text": "Old Comments" }, { "code": null, "e": 28441, "s": 28423, "text": "Python Dictionary" }, { "code": null, "e": 28476, "s": 28441, "text": "Read a file line by line in Python" }, { "code": null, "e": 28498, "s": 28476, "text": "Enumerate() in Python" }, { "code": null, "e": 28530, "s": 28498, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28560, "s": 28530, "text": "Iterate over a list in Python" }, { "code": null, "e": 28602, "s": 28560, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28645, "s": 28602, "text": "Python program to convert a list to string" }, { "code": null, "e": 28671, "s": 28645, "text": "Python String | replace()" }, { "code": null, "e": 28715, "s": 28671, "text": "Reading and Writing to text files in Python" } ]
Tryit Editor v3.7
HTML form attributes Tryit: HTML form target attribute
[ { "code": null, "e": 31, "s": 10, "text": "HTML form attributes" } ]
403bypasser - Bypass 403 Restricted Directory - GeeksforGeeks
23 Sep, 2021 Access control is a fundamental component of data security that manages who’s allowed to access and use company data and resources. This access control technique is also applied to web-based applications. Development of certain web pages is done with high security. Although we can bypass this access control through automated tools. 403bypasser tool automates the techniques used to circumvent access control restrictions on target pages. 403bypasser tool performs brute-forcing of possible directories in the target domain which can be bypassed. 403bypasser tool is developed in the python language and is available on GitHub. 403bypasser tool is an open-source tool and free to use. 403bypasser tool supports multiple URLs scan at the same time. We can store the results on the text file for further use. Note: Make Sure You have Python Installed on your System, as this is a python-based tool. Click to check the Installation process: Python Installation Steps on Linux Step 1: Use the following command to install the tool in your Kali Linux operating system. git clone https://github.com/yunemse48/403bypasser.git Step 2: Now use the following command to move into the directory of the tool. You have to move in the directory in order to run the tool. cd 403bypasser Step 3: You are in the directory of the 403Bypasser. Now you have to install a dependency of the 403Bypasser using the following command. sudo pip3 install -r requirements.txt Step 4: All the dependencies have been installed in your Kali Linux operating system. Now use the following command to run the tool and check the help section. python3 403bypasser.py -h Example 1: Single URL to scan python3 403bypasser.py -u https://geeksforgeeks.org -d /secret Example 2: Single directory to scan python3 403bypasser.py -u https://geeksforgeeks.org -d /admin Example 3: Path to list of URLs python3 403bypasser.py -U list.txt -d /admin The results of https://geeksforgeeks.org are shown in the below screenshot. The results of https://facebook.com are shown in the below screenshot. The results of https://google.com are shown in the below screenshot. Kali-Linux Linux-Tools Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Thread functions in C/C++ mv command in Linux with examples nohup Command in Linux with Examples scp command in Linux with Examples Docker - COPY Instruction chown command in Linux with Examples nslookup command in Linux with Examples SED command in Linux | Set 2 Named Pipe or FIFO with example C program uniq Command in LINUX with examples
[ { "code": null, "e": 24040, "s": 24012, "text": "\n23 Sep, 2021" }, { "code": null, "e": 24375, "s": 24040, "text": "Access control is a fundamental component of data security that manages who’s allowed to access and use company data and resources. This access control technique is also applied to web-based applications. Development of certain web pages is done with high security. Although we can bypass this access control through automated tools. " }, { "code": null, "e": 24852, "s": 24375, "text": "403bypasser tool automates the techniques used to circumvent access control restrictions on target pages. 403bypasser tool performs brute-forcing of possible directories in the target domain which can be bypassed. 403bypasser tool is developed in the python language and is available on GitHub. 403bypasser tool is an open-source tool and free to use. 403bypasser tool supports multiple URLs scan at the same time. We can store the results on the text file for further use." }, { "code": null, "e": 25018, "s": 24852, "text": "Note: Make Sure You have Python Installed on your System, as this is a python-based tool. Click to check the Installation process: Python Installation Steps on Linux" }, { "code": null, "e": 25109, "s": 25018, "text": "Step 1: Use the following command to install the tool in your Kali Linux operating system." }, { "code": null, "e": 25164, "s": 25109, "text": "git clone https://github.com/yunemse48/403bypasser.git" }, { "code": null, "e": 25302, "s": 25164, "text": "Step 2: Now use the following command to move into the directory of the tool. You have to move in the directory in order to run the tool." }, { "code": null, "e": 25317, "s": 25302, "text": "cd 403bypasser" }, { "code": null, "e": 25455, "s": 25317, "text": "Step 3: You are in the directory of the 403Bypasser. Now you have to install a dependency of the 403Bypasser using the following command." }, { "code": null, "e": 25493, "s": 25455, "text": "sudo pip3 install -r requirements.txt" }, { "code": null, "e": 25653, "s": 25493, "text": "Step 4: All the dependencies have been installed in your Kali Linux operating system. Now use the following command to run the tool and check the help section." }, { "code": null, "e": 25679, "s": 25653, "text": "python3 403bypasser.py -h" }, { "code": null, "e": 25709, "s": 25679, "text": "Example 1: Single URL to scan" }, { "code": null, "e": 25772, "s": 25709, "text": "python3 403bypasser.py -u https://geeksforgeeks.org -d /secret" }, { "code": null, "e": 25808, "s": 25772, "text": "Example 2: Single directory to scan" }, { "code": null, "e": 25870, "s": 25808, "text": "python3 403bypasser.py -u https://geeksforgeeks.org -d /admin" }, { "code": null, "e": 25904, "s": 25870, "text": "Example 3: Path to list of URLs " }, { "code": null, "e": 25949, "s": 25904, "text": "python3 403bypasser.py -U list.txt -d /admin" }, { "code": null, "e": 26025, "s": 25949, "text": "The results of https://geeksforgeeks.org are shown in the below screenshot." }, { "code": null, "e": 26096, "s": 26025, "text": "The results of https://facebook.com are shown in the below screenshot." }, { "code": null, "e": 26165, "s": 26096, "text": "The results of https://google.com are shown in the below screenshot." }, { "code": null, "e": 26176, "s": 26165, "text": "Kali-Linux" }, { "code": null, "e": 26188, "s": 26176, "text": "Linux-Tools" }, { "code": null, "e": 26199, "s": 26188, "text": "Linux-Unix" }, { "code": null, "e": 26297, "s": 26199, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26306, "s": 26297, "text": "Comments" }, { "code": null, "e": 26319, "s": 26306, "text": "Old Comments" }, { "code": null, "e": 26345, "s": 26319, "text": "Thread functions in C/C++" }, { "code": null, "e": 26379, "s": 26345, "text": "mv command in Linux with examples" }, { "code": null, "e": 26416, "s": 26379, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 26451, "s": 26416, "text": "scp command in Linux with Examples" }, { "code": null, "e": 26477, "s": 26451, "text": "Docker - COPY Instruction" }, { "code": null, "e": 26514, "s": 26477, "text": "chown command in Linux with Examples" }, { "code": null, "e": 26554, "s": 26514, "text": "nslookup command in Linux with Examples" }, { "code": null, "e": 26583, "s": 26554, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 26625, "s": 26583, "text": "Named Pipe or FIFO with example C program" } ]
Wiggle Animation Effect with CSS
The wiggle effect move or cause to move up and down or from side to side with small rapid movements. You can try to run the following code to implement the winggle animation effect − Live Demo <html> <head> <style> .animated { background-image: url(/css/images/logo.png); background-repeat: no-repeat; background-position: left top; padding-top:95px; margin-bottom:60px; -webkit-animation-duration: 10s; animation-duration: 10s; -webkit-animation-fill-mode: both; animation-fill-mode: both; } @-webkit-keyframes wiggle { 0% { -webkit-transform: skewX(9deg); } 10% { -webkit-transform: skewX(-8deg); } 20% { -webkit-transform: skewX(7deg); } 30% { -webkit-transform: skewX(-6deg); } 40% { -webkit-transform: skewX(5deg); } 50% { -webkit-transform: skewX(-4deg); } 60% { -webkit-transform: skewX(3deg); } 70% { -webkit-transform: skewX(-2deg); } 80% { -webkit-transform: skewX(1deg); } 90% { -webkit-transform: skewX(0deg); } 100% { -webkit-transform: skewX(0deg); } } @keyframes wiggle { 0% { transform: skewX(9deg); } 10% { transform: skewX(-8deg); } 20% { transform: skewX(7deg); } 30% { transform: skewX(-6deg); } 40% { transform: skewX(5deg); } 50% { transform: skewX(-4deg); } 60% { transform: skewX(3deg); } 70% { transform: skewX(-2deg); } 80% { transform: skewX(1deg); } 90% { transform: skewX(0deg); } 100% { transform: skewX(0deg); } } .wiggle { -webkit-animation-name: wiggle; animation-name: wiggle; -webkit-animation-timing-function: ease-in; animation-timing-function: ease-in; } .animated.wiggle { -webkit-animation-duration: 0.75s; animation-duration: 0.75s; } </style> </head> <body> <div id="animated-example" class="animated wiggle"></div> <button onclick="myFunction()">Reload page</button> <script> function myFunction() { location.reload(); } </script> </body> </html>
[ { "code": null, "e": 1163, "s": 1062, "text": "The wiggle effect move or cause to move up and down or from side to side with small rapid movements." }, { "code": null, "e": 1245, "s": 1163, "text": "You can try to run the following code to implement the winggle animation effect −" }, { "code": null, "e": 1255, "s": 1245, "text": "Live Demo" }, { "code": null, "e": 3473, "s": 1255, "text": "<html>\n <head>\n <style>\n\n .animated {\n background-image: url(/css/images/logo.png);\n background-repeat: no-repeat;\n background-position: left top;\n padding-top:95px;\n margin-bottom:60px;\n -webkit-animation-duration: 10s;\n animation-duration: 10s;\n -webkit-animation-fill-mode: both;\n animation-fill-mode: both;\n }\n\n @-webkit-keyframes wiggle {\n 0% { -webkit-transform: skewX(9deg); }\n 10% { -webkit-transform: skewX(-8deg); }\n 20% { -webkit-transform: skewX(7deg); }\n 30% { -webkit-transform: skewX(-6deg); }\n 40% { -webkit-transform: skewX(5deg); }\n 50% { -webkit-transform: skewX(-4deg); }\n 60% { -webkit-transform: skewX(3deg); }\n 70% { -webkit-transform: skewX(-2deg); }\n 80% { -webkit-transform: skewX(1deg); }\n 90% { -webkit-transform: skewX(0deg); }\n 100% { -webkit-transform: skewX(0deg); }\n }\n\n @keyframes wiggle {\n 0% { transform: skewX(9deg); }\n 10% { transform: skewX(-8deg); }\n 20% { transform: skewX(7deg); }\n 30% { transform: skewX(-6deg); }\n 40% { transform: skewX(5deg); }\n 50% { transform: skewX(-4deg); }\n 60% { transform: skewX(3deg); }\n 70% { transform: skewX(-2deg); }\n 80% { transform: skewX(1deg); }\n 90% { transform: skewX(0deg); }\n 100% { transform: skewX(0deg); }\n }\n\n .wiggle {\n -webkit-animation-name: wiggle;\n animation-name: wiggle;\n -webkit-animation-timing-function: ease-in;\n animation-timing-function: ease-in;\n }\n\n .animated.wiggle {\n -webkit-animation-duration: 0.75s;\n animation-duration: 0.75s;\n }\n </style>\n\n </head>\n <body>\n\n <div id=\"animated-example\" class=\"animated wiggle\"></div>\n <button onclick=\"myFunction()\">Reload page</button>\n\n <script>\n function myFunction() {\n location.reload();\n }\n </script>\n </body>\n</html>" } ]
CSS | Overflow - GeeksforGeeks
30 Jun, 2021 The CSS overflow controls the big content. It tells whether to clip content or to add scroll bars. The overflow contains the following property: visible hidden scroll auto Visible: The content is not clipped and visible outside the element box. Example: html <!DOCTYPE><html> <head> <style> p { width:100px; height:80px; border:1px solid; overflow:visible; } </style> </head> <body> <h2> GEEKSFORGEEKS </h2> <p> The CSS overflow controls big content. It tells whether to clip content or to add scroll bars. </p> </body></html> Output: Hidden: The overflow is clipped and the rest of the content is invisible.Example: html <!DOCTYPE><html> <head> <style> p { width:100px; height:80px; border:1px solid; overflow:hidden; } </style> </head> <body> <h2> GEEKSFORGEEKS </h2> <p> The CSS overflow controls big content. It tells whether to clip content or to add scroll bars. </p> </body></html> Output: Scroll: The overflow is clipped but a scrollbar is added to see the rest of the content. The scrollbar can be horizontal or vertical. Example: html <!DOCTYPE><html> <head> <style> p { width:120px; height:100px; border:1px solid; overflow:scroll; } </style> </head> <body> <h2> GEEKSFORGEEKS </h2> <p> The CSS overflow controls big content. It tells whether to clip content or to add scroll bars. </p> </body></html> Output: Auto: It automatically adds a scrollbar whenever it is required.Example: html <!DOCTYPE><html> <head> <style> p { width:120px; height:100px; border:1px solid; overflow:auto; } </style> </head> <body> <h2> GEEKSFORGEEKS </h2> <p> The CSS overflow controls big content. It tells whether to clip content or to add scroll bars. </p> </body></html> Output: Overflow-x and Overflow-y: This property specifies how to change the overflow of elements. x deals with horizontal edges and y deals with vertical edges. Example: html <!DOCTYPE><html> <head> <style> p { width:120px; height:100px; border:1px solid; overflow-x:scroll; overflow-y:hidden; } </style> </head> <body> <h2> GEEKSFORGEEKS </h2> <p> The CSS overflow controls big content. It tells whether to clip content or to add scroll bars. </p> </body></html> Output: Supported Browser: 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. ysachin2314 CSS-Basics CSS HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to create footer to stay at the bottom of a Web page? How to update Node.js and NPM to next version ? CSS to put icon inside an input element in a form How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to set the default value for an HTML <select> element ? How to update Node.js and NPM to next version ? How to set input type date in dd-mm-yyyy format using HTML ?
[ { "code": null, "e": 28071, "s": 28043, "text": "\n30 Jun, 2021" }, { "code": null, "e": 28218, "s": 28071, "text": "The CSS overflow controls the big content. It tells whether to clip content or to add scroll bars. The overflow contains the following property: " }, { "code": null, "e": 28226, "s": 28218, "text": "visible" }, { "code": null, "e": 28233, "s": 28226, "text": "hidden" }, { "code": null, "e": 28240, "s": 28233, "text": "scroll" }, { "code": null, "e": 28245, "s": 28240, "text": "auto" }, { "code": null, "e": 28329, "s": 28245, "text": "Visible: The content is not clipped and visible outside the element box. Example: " }, { "code": null, "e": 28334, "s": 28329, "text": "html" }, { "code": "<!DOCTYPE><html> <head> <style> p { width:100px; height:80px; border:1px solid; overflow:visible; } </style> </head> <body> <h2> GEEKSFORGEEKS </h2> <p> The CSS overflow controls big content. It tells whether to clip content or to add scroll bars. </p> </body></html>", "e": 28714, "s": 28334, "text": null }, { "code": null, "e": 28724, "s": 28714, "text": "Output: " }, { "code": null, "e": 28810, "s": 28726, "text": "Hidden: The overflow is clipped and the rest of the content is invisible.Example: " }, { "code": null, "e": 28815, "s": 28810, "text": "html" }, { "code": "<!DOCTYPE><html> <head> <style> p { width:100px; height:80px; border:1px solid; overflow:hidden; } </style> </head> <body> <h2> GEEKSFORGEEKS </h2> <p> The CSS overflow controls big content. It tells whether to clip content or to add scroll bars. </p> </body></html>", "e": 29194, "s": 28815, "text": null }, { "code": null, "e": 29204, "s": 29194, "text": "Output: " }, { "code": null, "e": 29351, "s": 29206, "text": "Scroll: The overflow is clipped but a scrollbar is added to see the rest of the content. The scrollbar can be horizontal or vertical. Example: " }, { "code": null, "e": 29356, "s": 29351, "text": "html" }, { "code": "<!DOCTYPE><html> <head> <style> p { width:120px; height:100px; border:1px solid; overflow:scroll; } </style> </head> <body> <h2> GEEKSFORGEEKS </h2> <p> The CSS overflow controls big content. It tells whether to clip content or to add scroll bars. </p> </body></html>", "e": 29736, "s": 29356, "text": null }, { "code": null, "e": 29746, "s": 29736, "text": "Output: " }, { "code": null, "e": 29823, "s": 29748, "text": "Auto: It automatically adds a scrollbar whenever it is required.Example: " }, { "code": null, "e": 29828, "s": 29823, "text": "html" }, { "code": "<!DOCTYPE><html> <head> <style> p { width:120px; height:100px; border:1px solid; overflow:auto; } </style> </head> <body> <h2> GEEKSFORGEEKS </h2> <p> The CSS overflow controls big content. It tells whether to clip content or to add scroll bars. </p> </body></html>", "e": 30206, "s": 29828, "text": null }, { "code": null, "e": 30216, "s": 30206, "text": "Output: " }, { "code": null, "e": 30383, "s": 30218, "text": "Overflow-x and Overflow-y: This property specifies how to change the overflow of elements. x deals with horizontal edges and y deals with vertical edges. Example: " }, { "code": null, "e": 30388, "s": 30383, "text": "html" }, { "code": "<!DOCTYPE><html> <head> <style> p { width:120px; height:100px; border:1px solid; overflow-x:scroll; overflow-y:hidden; } </style> </head> <body> <h2> GEEKSFORGEEKS </h2> <p> The CSS overflow controls big content. It tells whether to clip content or to add scroll bars. </p> </body></html>", "e": 30797, "s": 30388, "text": null }, { "code": null, "e": 30807, "s": 30797, "text": "Output: " }, { "code": null, "e": 30828, "s": 30809, "text": "Supported Browser:" }, { "code": null, "e": 30842, "s": 30828, "text": "Google Chrome" }, { "code": null, "e": 30860, "s": 30842, "text": "Internet Explorer" }, { "code": null, "e": 30868, "s": 30860, "text": "Firefox" }, { "code": null, "e": 30874, "s": 30868, "text": "Opera" }, { "code": null, "e": 30881, "s": 30874, "text": "Safari" }, { "code": null, "e": 31018, "s": 30881, "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": 31030, "s": 31018, "text": "ysachin2314" }, { "code": null, "e": 31041, "s": 31030, "text": "CSS-Basics" }, { "code": null, "e": 31045, "s": 31041, "text": "CSS" }, { "code": null, "e": 31050, "s": 31045, "text": "HTML" }, { "code": null, "e": 31067, "s": 31050, "text": "Web Technologies" }, { "code": null, "e": 31072, "s": 31067, "text": "HTML" }, { "code": null, "e": 31170, "s": 31072, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31232, "s": 31170, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 31282, "s": 31232, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 31340, "s": 31282, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 31388, "s": 31340, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 31438, "s": 31388, "text": "CSS to put icon inside an input element in a form" }, { "code": null, "e": 31488, "s": 31438, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 31550, "s": 31488, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 31610, "s": 31550, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 31658, "s": 31610, "text": "How to update Node.js and NPM to next version ?" } ]
Program to find minimum number of operations required to make one string substring of other in Python
Suppose we have two strings s and t, we have to find the minimum amount of operations required for s to make t a substring of s. Now, in each operation, we can choose any position in s and change the character at that position to any other character. So, if the input is like s = "abbpqr", t = "bbxy", then the output will be 2, as we can take the substring "bbpq" and change 'p' to 'x' and 'q' to 'y'. To solve this, we will follow these steps − k := size of t, n := size of s ans := 10^10 for i in range 0 to n - k, doss := substring of s[from index i to i+k-1]ans := minimum of ans and number of unmatched character of s and t ss := substring of s[from index i to i+k-1] ans := minimum of ans and number of unmatched character of s and t return ans Let us see the following implementation to get better understanding − Live Demo class Solution: def solve(self, s, t): k, n = len(t), len(s) ans = 10**10 for i in range(n - k + 1): ss = s[i:i+k] ans = min(ans, sum(ss[j]!=t[j] for j in range(k))) return ans ob = Solution() print(ob.solve("abbpqr", "bbxy")) "abbpqr", "bbxy" 2
[ { "code": null, "e": 1313, "s": 1062, "text": "Suppose we have two strings s and t, we have to find the minimum amount of operations required for s to make t a substring of s. Now, in each operation, we can choose any position in s and change the character at that position to any other character." }, { "code": null, "e": 1465, "s": 1313, "text": "So, if the input is like s = \"abbpqr\", t = \"bbxy\", then the output will be 2, as we can take the substring \"bbpq\" and change 'p' to 'x' and 'q' to 'y'." }, { "code": null, "e": 1509, "s": 1465, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1540, "s": 1509, "text": "k := size of t, n := size of s" }, { "code": null, "e": 1553, "s": 1540, "text": "ans := 10^10" }, { "code": null, "e": 1692, "s": 1553, "text": "for i in range 0 to n - k, doss := substring of s[from index i to i+k-1]ans := minimum of ans and number of unmatched character of s and t" }, { "code": null, "e": 1736, "s": 1692, "text": "ss := substring of s[from index i to i+k-1]" }, { "code": null, "e": 1803, "s": 1736, "text": "ans := minimum of ans and number of unmatched character of s and t" }, { "code": null, "e": 1814, "s": 1803, "text": "return ans" }, { "code": null, "e": 1884, "s": 1814, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 1895, "s": 1884, "text": " Live Demo" }, { "code": null, "e": 2167, "s": 1895, "text": "class Solution:\n def solve(self, s, t):\n k, n = len(t), len(s)\n ans = 10**10\n for i in range(n - k + 1):\n ss = s[i:i+k]\n ans = min(ans, sum(ss[j]!=t[j] for j in range(k)))\n return ans\nob = Solution()\nprint(ob.solve(\"abbpqr\", \"bbxy\"))" }, { "code": null, "e": 2184, "s": 2167, "text": "\"abbpqr\", \"bbxy\"" }, { "code": null, "e": 2186, "s": 2184, "text": "2" } ]
Word Break | Practice | GeeksforGeeks
Given a string A and a dictionary of n words B, find out if A can be segmented into a space-separated sequence of dictionary words. Note: From the dictionary B each word can be taken any number of times and in any order. Example 1: Input: n = 12 B = { "i", "like", "sam", "sung", "samsung", "mobile", "ice","cream", "icecream", "man", "go", "mango" } A = "ilike" Output: 1 Explanation: The string can be segmented as "i like". Example 2: Input: n = 12 B = { "i", "like", "sam", "sung", "samsung", "mobile", "ice","cream", "icecream", "man", "go", "mango" } A = "ilikesamsung" Output: 1 Explanation: The string can be segmented as "i like samsung" or "i like sam sung". Your Task: Complete wordBreak() function which takes a string and list of strings as a parameter and returns 1 if it is possible to break words, else return 0. You don't need to read any input or print any output, it is done by driver code. Expected time complexity: O(s2) Expected auxiliary space: O(s) , where s = length of string A Constraints: 1 ≤ N ≤ 12 1 ≤ s ≤ 1100 , where s = length of string A The length of each word is less than 15. +2 guptatushar110411 day ago unordered_set<string>st; int dp[1101]; int solve(string &s,int index) { if(index==s.size())return 1; string temp; if(dp[index]!=-1) return dp[index]; for(int j=index;j<s.size();j++) { temp +=s[j]; if(st.find(temp)!=st.end()) if(solve(s,j+1)) return dp[index]=1; } return dp[index]=0; } int wordBreak(string s, vector<string> &wordDict) { //code here memset(dp,-1,sizeof(dp)); for(auto x:wordDict) { st.insert(x); } return solve(s,0); } 0 jainmuskan5652 weeks ago unordered_map<string,int> mp; int solve(string a, vector<string> &b){ int sz= a.length(); if(sz==0){ // size os 0 then we found out word return 1; } if(mp[a]!= 0){ return mp[a]; } for(int i=1;i<=sz;i++){ string subs= a.substr(0,i); // compare the substrings with the b int f=0; // initialize a counter for(int j=0;j<b.size();j++){ if(subs.compare(b[j])==0){ f=1; break; // found a substring from a in b{} then break } } if(f==1 && solve(a.substr(i,sz-i),b)==1){ return mp[a]=1; } } return mp[a]=-1; } int wordBreak(string A, vector<string> &B) { int z= solve(A,B); if(z==1){ return 1; } return 0; } 0 sandeep55213 weeks ago C++ Tabulation DP Solution int wordBreak(string &s, vector<string> &wordDict) { //code here unordered_set<string> us; for(auto i: wordDict) us.insert(i); int n=s.size(),flag; vector<int> dp(n+1,1); for(int i=n-1;i>=0;i--){ string t;flag=1; for(int j=i;j<n;j++){ t.push_back(s[j]); if(us.find(t)==us.end()) continue; if(dp[j+1]) flag--; if(!flag) break; } if(flag) dp[i]=0; } return dp[0]; } 0 sougataroy8933 weeks ago c++ sol int fun(string &a,vector<string> &b){ if(s[a]) return 1; for(int i=0;i<=a.size();i++){ string s1=a.substr(0,i); string s2=a.substr(i); if(s[s1] && (s[s2] || fun(s2,b))){ return 1; } } return 0; } int wordBreak(string A, vector<string> &B) { for(auto i: B){ s[i]++; } return fun(A,B); } +1 kshitij14103 weeks ago bool isExist(string temp,vector<string> &b) { for(int i=0;i<b.size();i++) { if(b[i]==temp) return true; } return false; } int flag=0; bool solve(string str, vector<string>&s1,int k, int j) { for(int i=k;i<j;i++) { string temp=str.substr(k,i-k+1); //if it is exist if(isExist(temp,s1)) { if(i+1==j) { flag=1; return true; } else{ solve(str,s1,i+1,j); } } } if(flag==1) return true; return false; } int wordBreak(string A, vector<string> &B) { int n=A.size(); return solve(A,B,0,n); }}; +1 mukulbansal4214 weeks ago class Sol { public static int wordBreak(String s, ArrayList<String> b ) { //code here int[] dp=new int[s.length()]; for(int i=0;i<dp.length;i++){ for(int j=0;j<=i;j++){ String word=s.substring(j,i+1); if(b.contains(word)) { dp[i]+=1; } } } return dp[s.length()-1]>0?1:0; } } 0 jmanm1 month ago Recursive Java Solution: public static int wordBreak(String A, ArrayList<String> B ) { if (B.contains(A)) return 1; if (rec(A, B, 1)) return 1; else return 0; } public static boolean rec(String A, ArrayList<String> B, int index) { if (index == A.length()) return false; String prefix = A.substring(0, index); String suffix = A.substring(index, A.length()); if (B.contains(prefix) && B.contains(suffix)) return true; else if (B.contains(prefix) && !B.contains(suffix)) return rec(suffix, B, 1) || rec(A, B, index+1); else return rec(A, B, index+1); } 0 iamalizaidi1101 month ago class Sol { public static int wordBreak(String A, ArrayList<String> B ) { if(solve(A,0,A.length(),B)) return 1; else return 0; } public static boolean solve(String A,int i,int j,ArrayList<String> B) { if(i>=j) return false; if(B.indexOf(A.substring(i,j))!=-1) return true; for(int k=i;k<j-1;k++) { if(B.contains(A.substring(i,k+1)) && solve(A,k+1,j,B)) return true; } return false; } } 0 siddharthverma7971 month ago class Sol{ public static int wordBreak(String A, ArrayList<String> B ) { int dp[]=new int[A.length()]; for(int i=0;i<A.length();i++){ for(int j=0;j<=i;j++){ if(B.contains(A.substring(j,i+1))){ dp[i]+=j>0?dp[j-1]:1; } } } return dp[A.length()-1]; }} -1 mithileshkumarsingh1 month ago int i, j, k, n = B.size(); set<string> mp; for (i = 0; i < n; i++) { mp.insert(B[i]); } int len = (int)A.size(); vector<bool> dp(len + 1, false); dp[0] = true; for (int i = 1; i <= len; i++) { for (int j = i - 1; j >= 0; j--) { if (dp[j] && mp.find(A.substr(j, i - j)) != mp.end()) { dp[i] = true; break; } } } return dp[len]; 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": 370, "s": 238, "text": "Given a string A and a dictionary of n words B, find out if A can be segmented into a space-separated sequence of dictionary words." }, { "code": null, "e": 470, "s": 370, "text": "Note: From the dictionary B each word can be taken any number of times and in any order.\nExample 1:" }, { "code": null, "e": 666, "s": 470, "text": "Input:\nn = 12\nB = { \"i\", \"like\", \"sam\",\n\"sung\", \"samsung\", \"mobile\",\n\"ice\",\"cream\", \"icecream\",\n\"man\", \"go\", \"mango\" }\nA = \"ilike\"\nOutput:\n1\nExplanation:\nThe string can be segmented as \"i like\".\n" }, { "code": null, "e": 678, "s": 666, "text": "\nExample 2:" }, { "code": null, "e": 912, "s": 678, "text": "Input:\nn = 12\nB = { \"i\", \"like\", \"sam\",\n\"sung\", \"samsung\", \"mobile\",\n\"ice\",\"cream\", \"icecream\", \n\"man\", \"go\", \"mango\" }\nA = \"ilikesamsung\"\nOutput:\n1\nExplanation:\nThe string can be segmented as \n\"i like samsung\" or \"i like sam sung\".\n" }, { "code": null, "e": 1155, "s": 914, "text": "Your Task:\nComplete wordBreak() function which takes a string and list of strings as a parameter and returns 1 if it is possible to break words, else return 0. You don't need to read any input or print any output, it is done by driver code." }, { "code": null, "e": 1188, "s": 1155, "text": "\nExpected time complexity: O(s2)" }, { "code": null, "e": 1250, "s": 1188, "text": "Expected auxiliary space: O(s) , where s = length of string A" }, { "code": null, "e": 1362, "s": 1252, "text": "Constraints:\n1 ≤ N ≤ 12\n1 ≤ s ≤ 1100 , where s = length of string A\n The length of each word is less than 15." }, { "code": null, "e": 1365, "s": 1362, "text": "+2" }, { "code": null, "e": 1391, "s": 1365, "text": "guptatushar110411 day ago" }, { "code": null, "e": 1416, "s": 1391, "text": "unordered_set<string>st;" }, { "code": null, "e": 1990, "s": 1418, "text": " int dp[1101]; int solve(string &s,int index) { if(index==s.size())return 1; string temp; if(dp[index]!=-1) return dp[index]; for(int j=index;j<s.size();j++) { temp +=s[j]; if(st.find(temp)!=st.end()) if(solve(s,j+1)) return dp[index]=1; } return dp[index]=0; } int wordBreak(string s, vector<string> &wordDict) { //code here memset(dp,-1,sizeof(dp)); for(auto x:wordDict) { st.insert(x); } return solve(s,0); }" }, { "code": null, "e": 1992, "s": 1990, "text": "0" }, { "code": null, "e": 2017, "s": 1992, "text": "jainmuskan5652 weeks ago" }, { "code": null, "e": 2920, "s": 2017, "text": "unordered_map<string,int> mp; int solve(string a, vector<string> &b){ int sz= a.length(); if(sz==0){ // size os 0 then we found out word return 1; } if(mp[a]!= 0){ return mp[a]; } for(int i=1;i<=sz;i++){ string subs= a.substr(0,i); // compare the substrings with the b int f=0; // initialize a counter for(int j=0;j<b.size();j++){ if(subs.compare(b[j])==0){ f=1; break; // found a substring from a in b{} then break } } if(f==1 && solve(a.substr(i,sz-i),b)==1){ return mp[a]=1; } } return mp[a]=-1; } int wordBreak(string A, vector<string> &B) { int z= solve(A,B); if(z==1){ return 1; } return 0; }" }, { "code": null, "e": 2922, "s": 2920, "text": "0" }, { "code": null, "e": 2945, "s": 2922, "text": "sandeep55213 weeks ago" }, { "code": null, "e": 2972, "s": 2945, "text": "C++ Tabulation DP Solution" }, { "code": null, "e": 3499, "s": 2972, "text": "int wordBreak(string &s, vector<string> &wordDict) {\n //code here\n unordered_set<string> us;\n for(auto i: wordDict) us.insert(i);\n int n=s.size(),flag;\n vector<int> dp(n+1,1);\n for(int i=n-1;i>=0;i--){\n string t;flag=1;\n for(int j=i;j<n;j++){\n t.push_back(s[j]);\n if(us.find(t)==us.end()) continue;\n if(dp[j+1]) flag--;\n if(!flag) break;\n }\n if(flag) dp[i]=0;\n }\n return dp[0];\n }" }, { "code": null, "e": 3501, "s": 3499, "text": "0" }, { "code": null, "e": 3526, "s": 3501, "text": "sougataroy8933 weeks ago" }, { "code": null, "e": 3534, "s": 3526, "text": "c++ sol" }, { "code": null, "e": 3939, "s": 3534, "text": "int fun(string &a,vector<string> &b){ if(s[a]) return 1; for(int i=0;i<=a.size();i++){ string s1=a.substr(0,i); string s2=a.substr(i); if(s[s1] && (s[s2] || fun(s2,b))){ return 1; } } return 0; } int wordBreak(string A, vector<string> &B) { for(auto i: B){ s[i]++; } return fun(A,B); }" }, { "code": null, "e": 3942, "s": 3939, "text": "+1" }, { "code": null, "e": 3965, "s": 3942, "text": "kshitij14103 weeks ago" }, { "code": null, "e": 4793, "s": 3965, "text": "bool isExist(string temp,vector<string> &b) { for(int i=0;i<b.size();i++) { if(b[i]==temp) return true; } return false; } int flag=0; bool solve(string str, vector<string>&s1,int k, int j) { for(int i=k;i<j;i++) { string temp=str.substr(k,i-k+1); //if it is exist if(isExist(temp,s1)) { if(i+1==j) { flag=1; return true; } else{ solve(str,s1,i+1,j); } } } if(flag==1) return true; return false; } int wordBreak(string A, vector<string> &B) { int n=A.size(); return solve(A,B,0,n); }};" }, { "code": null, "e": 4796, "s": 4793, "text": "+1" }, { "code": null, "e": 4822, "s": 4796, "text": "mukulbansal4214 weeks ago" }, { "code": null, "e": 5258, "s": 4822, "text": "\nclass Sol\n{\n public static int wordBreak(String s, ArrayList<String> b )\n {\n //code here\n int[] dp=new int[s.length()];\n for(int i=0;i<dp.length;i++){\n for(int j=0;j<=i;j++){\n String word=s.substring(j,i+1);\n if(b.contains(word))\n {\n dp[i]+=1;\n }\n }\n }\n return dp[s.length()-1]>0?1:0;\n }\n}" }, { "code": null, "e": 5260, "s": 5258, "text": "0" }, { "code": null, "e": 5277, "s": 5260, "text": "jmanm1 month ago" }, { "code": null, "e": 5302, "s": 5277, "text": "Recursive Java Solution:" }, { "code": null, "e": 5978, "s": 5304, "text": "public static int wordBreak(String A, ArrayList<String> B ) { if (B.contains(A)) return 1; if (rec(A, B, 1)) return 1; else return 0; } public static boolean rec(String A, ArrayList<String> B, int index) { if (index == A.length()) return false; String prefix = A.substring(0, index); String suffix = A.substring(index, A.length()); if (B.contains(prefix) && B.contains(suffix)) return true; else if (B.contains(prefix) && !B.contains(suffix)) return rec(suffix, B, 1) || rec(A, B, index+1); else return rec(A, B, index+1); }" }, { "code": null, "e": 5980, "s": 5978, "text": "0" }, { "code": null, "e": 6006, "s": 5980, "text": "iamalizaidi1101 month ago" }, { "code": null, "e": 6556, "s": 6006, "text": "class Sol\n{\n \n public static int wordBreak(String A, ArrayList<String> B )\n {\n if(solve(A,0,A.length(),B))\n return 1;\n else return 0;\n \n }\n public static boolean solve(String A,int i,int j,ArrayList<String> B)\n {\n if(i>=j)\n return false;\n if(B.indexOf(A.substring(i,j))!=-1)\n return true;\n \n for(int k=i;k<j-1;k++)\n {\n if(B.contains(A.substring(i,k+1)) && solve(A,k+1,j,B))\n return true;\n }\n return false;\n }\n \n}" }, { "code": null, "e": 6558, "s": 6556, "text": "0" }, { "code": null, "e": 6587, "s": 6558, "text": "siddharthverma7971 month ago" }, { "code": null, "e": 6932, "s": 6587, "text": "class Sol{ public static int wordBreak(String A, ArrayList<String> B ) { int dp[]=new int[A.length()]; for(int i=0;i<A.length();i++){ for(int j=0;j<=i;j++){ if(B.contains(A.substring(j,i+1))){ dp[i]+=j>0?dp[j-1]:1; } } } return dp[A.length()-1]; }}" }, { "code": null, "e": 6935, "s": 6932, "text": "-1" }, { "code": null, "e": 6966, "s": 6935, "text": "mithileshkumarsingh1 month ago" }, { "code": null, "e": 7475, "s": 6966, "text": " int i, j, k, n = B.size();\n set<string> mp;\n for (i = 0; i < n; i++) {\n mp.insert(B[i]);\n }\n int len = (int)A.size();\n vector<bool> dp(len + 1, false);\n dp[0] = true;\n for (int i = 1; i <= len; i++) {\n for (int j = i - 1; j >= 0; j--) {\n if (dp[j] && mp.find(A.substr(j, i - j)) != mp.end()) {\n dp[i] = true;\n break;\n }\n }\n }\n return dp[len];" }, { "code": null, "e": 7621, "s": 7475, "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": 7657, "s": 7621, "text": " Login to access your submissions. " }, { "code": null, "e": 7667, "s": 7657, "text": "\nProblem\n" }, { "code": null, "e": 7677, "s": 7667, "text": "\nContest\n" }, { "code": null, "e": 7740, "s": 7677, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 7888, "s": 7740, "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": 8096, "s": 7888, "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": 8202, "s": 8096, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
2D Vector In C++ With User Defined Size - GeeksforGeeks
20 Oct, 2021 A 2D vector is a vector of the vector. Like 2D arrays, we can declare and assign values to a 2D vector! Assuming you are familiar with a normal vector in C++, with the help of an example we demonstrate how a 2D vector differs from a normal vector below: C++ /* Vectors belong to a C++ library called STL so we need to import it first! */#include <vector>using namespace std;int main(){ /* In the case of a normal vector we initialize it as: 1. vector<datatype> variable_name Now in the case of a 2D vector all we do is create a vector of datatype vector. We simply replace "datatype" with "vector<int>": 1. vector<vector<int>> variable_name That's literally it! We just created a 2D vector! On line 23 below we declare an actual 2D vector named "vect". */ vector<vector<int>> vect; return 0;} In a 2D vector, every element is a vector. C++ /* C++ code to demonstrate a 2D vector with elements(vectors) inside it. */#include <iostream>#include <vector>using namespace std; int main(){ /* Below we initialize a 2D vector named "vect" on line 12 and then we declare the values on line 14, 15 and 16 respectively. */ vector<vector<int>> vect { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; /* Now we print the values that we just declared on lines 14, 15 and 16 using a simple nested for loop. */ for (int i = 0; i < vect.size(); i++) { for (int j = 0; j < vect[i].size(); j++) { cout << vect[i][j] << " "; } cout << endl; } return 0;} 1 2 3 4 5 6 7 8 9 Another approach to access the vector elements: C++ /* C++ code to demonstrate a 2D vector with elements(vectors) inside it. */#include <iostream>#include <vector>using namespace std; int main(){ /* Below we initialize a 2D vector named "vect" on line 12 and then we declare the values on line 14, 15 and 16 respectively. */ vector<vector<int>> vect { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; /* Now we print the values that we just declared on lines 14, 15 and 16 using a simple nested for loop with the help of iterator. */ /* vector<vector<int>> vect We can divide this declaration to two parts, which will help us to understand the below concepts. 1. vect is a 2D vector consisting multiple elements of type vector<int>. 2. vector<int> is a 1D vector consisting of multiple int data. So we can use iterator provided by STL instead of i,j variable used in for loop. It can reduce the error which can happen wrt to i, j operations(i++, j++) In the below code we are using iterator to access the vector elements. 1. We are getting vect1D vectors of type vector<int> from the 2D vector vect. 2. We are getting int elements to x from the vector<int> vect 1D vector. */ for (vector<int> vect1D : vect) { for (int x : vect1D) { cout << x << " "; } cout << endl; } return 0;} 1 2 3 4 5 6 7 8 9 Like Java’s jagged arrays, each element of a 2D vector can contain a different number of values. C++ /*C++ program to demonstrate a 2D vector whereeach of its elements is of different size.*/#include <iostream>#include <vector>using namespace std;int main(){ /* We initialize a 2D vector named "vect" on line 16 with different number of values in each element. */ vector<vector<int>> vect { /* Element one with 2 values in it. */ {1, 2}, /* Element two with 3 values in it. */ {4, 5, 6}, /* Element three with 4 values in it. */ {7, 8, 9, 10} }; /* Now we print the vector that we just defined using a simple nested for loop. */ for (int i = 0; i < vect.size(); i++) { for (int j = 0; j < vect[i].size(); j++) { cout << vect[i][j] << " "; } cout << endl; } return 0;} 1 2 4 5 6 7 8 9 10 Exercise Problem: Define the 2D vector with different sizes of columns. Examples: Input : Number of rows : 5 Number of columns in rows : 2 3 4 5 1 Output : 1 2 1 2 3 1 2 3 4 1 2 3 4 5 1 Input : Number of rows : 3 Number of columns in rows : 3 2 1 Output : 1 2 3 1 2 1 2D vectors are often treated as a matrix with “rows” and “columns” inside it. Under the hood they are actually elements of the 2D vector. We first declare an integer variable named “row” and then an array named “column” which is going to hold the value of the size of each row. After that we proceed to initialize the memory of every row by the size of column. C++ /*C++ program to create a 2D vector whereevery row has a certain number of valuesas defined by the user.(On line 13)*/ #include <iostream>#include <vector>using namespace std;int main(){ /* Here we tell how many rows the 2D vector is going to have. */ int row = 5; /* We define the number of values each row is supposed to have. */ int column[] = {5, 3, 4, 2, 1}; /* We now create a vector of vector with size equal to row. */ vector<vector<int>> vec(row); /* On line 21 we created a 2D vector and assigned it a capacity of "row"(in this case 5) units. */ /* Now we will proceed to create the structure of our 2D vector by assigning the value of rows and columns through a nested for loop. */ for(int i = 0; i < row; i++) { /* Declaring the size of the column. */ int col = column[i]; /* On the 43rd line we declare the i-th row to the size of the column. We create a normal vector of capacity "col" which in every iteration of the for loop will define the values inside of each row. */ vec[i] = vector<int>(col); for(int j = 0; j < col; j++) { vec[i][j] = j + 1; } } /* We now finally use a simple nested for loop to print the 2D vector that we just created above. */ for(int i = 0; i < row; i++) { for (int j = 0; j < vec[i].size(); j++) { cout << vec[i][j] << " "; } cout << endl; } return 0;} 1 2 3 4 5 1 2 3 1 2 3 4 1 2 1 Another Approach Suppose we want to initialize a 2D vector of “n” rows and “m” columns, with a value 0. C++ // CPP program#include <iostream>#include <vector>using namespace std;int main(){ int n = 3; int m = 4; /* We create a 2D vector containing "n" elements each having the value "vector<int> (m, 0)". "vector<int> (m, 0)" means a vector having "m" elements each of value "0". Here these elements are vectors. */ vector<vector<int>> vec( n , vector<int> (m, 0)); for(int i = 0; i < n; i++) { for(int j = 0; j < m; j++) { cout << vec[i][j] << " "; } cout<< endl; } return 0;} 0 0 0 0 0 0 0 0 0 0 0 0 Yet Another Approach: Suppose we want to create a 2D vector of “n” rows and “m” columns and input values. C++ // CPP program#include <iostream>#include <vector>using namespace std;int main(){ int n = 4; int m = 5; /* Create a vector containing "n" vectors each of size "m". */ vector<vector<int>> vec( n , vector<int> (m)); for(int i = 0; i < n; i++) { for(int j = 0; j < m; j++) { vec[i][j] = j + i + 1; } } for(int i = 0; i < n; i++) { for(int j = 0; j < m; j++) { cout << vec[i][j] << " "; } cout << endl; } return 0;} 1 2 3 4 5 2 3 4 5 6 3 4 5 6 7 4 5 6 7 8 We hope you that you leave this article with a better understanding of 2D vectors and are now confident enough to apply them on your own. This article is contributed by Amit Verma. 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. Blinkii greengod dunno64 shashikantg sachisahu adnanirshad158 arorakashish0911 ruhelaa48 prachisoda1234 cpp-vector STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Constructors in C++ Socket Programming in C/C++ Operator Overloading in C++ Copy Constructor in C++ Virtual Function in C++ Templates in C++ with Examples rand() and srand() in C/C++ vector erase() and clear() in C++ unordered_map in C++ STL Left Shift and Right Shift Operators in C/C++
[ { "code": null, "e": 23995, "s": 23967, "text": "\n20 Oct, 2021" }, { "code": null, "e": 24250, "s": 23995, "text": "A 2D vector is a vector of the vector. Like 2D arrays, we can declare and assign values to a 2D vector! Assuming you are familiar with a normal vector in C++, with the help of an example we demonstrate how a 2D vector differs from a normal vector below: " }, { "code": null, "e": 24254, "s": 24250, "text": "C++" }, { "code": "/* Vectors belong to a C++ library called STL so we need to import it first! */#include <vector>using namespace std;int main(){ /* In the case of a normal vector we initialize it as: 1. vector<datatype> variable_name Now in the case of a 2D vector all we do is create a vector of datatype vector. We simply replace \"datatype\" with \"vector<int>\": 1. vector<vector<int>> variable_name That's literally it! We just created a 2D vector! On line 23 below we declare an actual 2D vector named \"vect\". */ vector<vector<int>> vect; return 0;}", "e": 24863, "s": 24254, "text": null }, { "code": null, "e": 24906, "s": 24863, "text": "In a 2D vector, every element is a vector." }, { "code": null, "e": 24910, "s": 24906, "text": "C++" }, { "code": "/* C++ code to demonstrate a 2D vector with elements(vectors) inside it. */#include <iostream>#include <vector>using namespace std; int main(){ /* Below we initialize a 2D vector named \"vect\" on line 12 and then we declare the values on line 14, 15 and 16 respectively. */ vector<vector<int>> vect { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; /* Now we print the values that we just declared on lines 14, 15 and 16 using a simple nested for loop. */ for (int i = 0; i < vect.size(); i++) { for (int j = 0; j < vect[i].size(); j++) { cout << vect[i][j] << \" \"; } cout << endl; } return 0;}", "e": 25629, "s": 24910, "text": null }, { "code": null, "e": 25650, "s": 25629, "text": "1 2 3 \n4 5 6 \n7 8 9 " }, { "code": null, "e": 25698, "s": 25650, "text": "Another approach to access the vector elements:" }, { "code": null, "e": 25702, "s": 25698, "text": "C++" }, { "code": "/* C++ code to demonstrate a 2D vector with elements(vectors) inside it. */#include <iostream>#include <vector>using namespace std; int main(){ /* Below we initialize a 2D vector named \"vect\" on line 12 and then we declare the values on line 14, 15 and 16 respectively. */ vector<vector<int>> vect { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; /* Now we print the values that we just declared on lines 14, 15 and 16 using a simple nested for loop with the help of iterator. */ /* vector<vector<int>> vect We can divide this declaration to two parts, which will help us to understand the below concepts. 1. vect is a 2D vector consisting multiple elements of type vector<int>. 2. vector<int> is a 1D vector consisting of multiple int data. So we can use iterator provided by STL instead of i,j variable used in for loop. It can reduce the error which can happen wrt to i, j operations(i++, j++) In the below code we are using iterator to access the vector elements. 1. We are getting vect1D vectors of type vector<int> from the 2D vector vect. 2. We are getting int elements to x from the vector<int> vect 1D vector. */ for (vector<int> vect1D : vect) { for (int x : vect1D) { cout << x << \" \"; } cout << endl; } return 0;}", "e": 27122, "s": 25702, "text": null }, { "code": null, "e": 27143, "s": 27122, "text": "1 2 3 \n4 5 6 \n7 8 9 " }, { "code": null, "e": 27240, "s": 27143, "text": "Like Java’s jagged arrays, each element of a 2D vector can contain a different number of values." }, { "code": null, "e": 27244, "s": 27240, "text": "C++" }, { "code": "/*C++ program to demonstrate a 2D vector whereeach of its elements is of different size.*/#include <iostream>#include <vector>using namespace std;int main(){ /* We initialize a 2D vector named \"vect\" on line 16 with different number of values in each element. */ vector<vector<int>> vect { /* Element one with 2 values in it. */ {1, 2}, /* Element two with 3 values in it. */ {4, 5, 6}, /* Element three with 4 values in it. */ {7, 8, 9, 10} }; /* Now we print the vector that we just defined using a simple nested for loop. */ for (int i = 0; i < vect.size(); i++) { for (int j = 0; j < vect[i].size(); j++) { cout << vect[i][j] << \" \"; } cout << endl; } return 0;} ", "e": 28078, "s": 27244, "text": null }, { "code": null, "e": 28100, "s": 28078, "text": "1 2 \n4 5 6 \n7 8 9 10 " }, { "code": null, "e": 28183, "s": 28100, "text": "Exercise Problem: Define the 2D vector with different sizes of columns. Examples: " }, { "code": null, "e": 28461, "s": 28183, "text": "Input : Number of rows : 5 \n Number of columns in rows : \n 2 3 4 5 1\nOutput : 1 2\n 1 2 3\n 1 2 3 4\n 1 2 3 4 5 \n 1\n\nInput : Number of rows : 3\n Number of columns in rows : \n 3 2 1\n\nOutput : 1 2 3\n 1 2\n 1" }, { "code": null, "e": 28740, "s": 28461, "text": "2D vectors are often treated as a matrix with “rows” and “columns” inside it. Under the hood they are actually elements of the 2D vector. We first declare an integer variable named “row” and then an array named “column” which is going to hold the value of the size of each row. " }, { "code": null, "e": 28823, "s": 28740, "text": "After that we proceed to initialize the memory of every row by the size of column." }, { "code": null, "e": 28827, "s": 28823, "text": "C++" }, { "code": "/*C++ program to create a 2D vector whereevery row has a certain number of valuesas defined by the user.(On line 13)*/ #include <iostream>#include <vector>using namespace std;int main(){ /* Here we tell how many rows the 2D vector is going to have. */ int row = 5; /* We define the number of values each row is supposed to have. */ int column[] = {5, 3, 4, 2, 1}; /* We now create a vector of vector with size equal to row. */ vector<vector<int>> vec(row); /* On line 21 we created a 2D vector and assigned it a capacity of \"row\"(in this case 5) units. */ /* Now we will proceed to create the structure of our 2D vector by assigning the value of rows and columns through a nested for loop. */ for(int i = 0; i < row; i++) { /* Declaring the size of the column. */ int col = column[i]; /* On the 43rd line we declare the i-th row to the size of the column. We create a normal vector of capacity \"col\" which in every iteration of the for loop will define the values inside of each row. */ vec[i] = vector<int>(col); for(int j = 0; j < col; j++) { vec[i][j] = j + 1; } } /* We now finally use a simple nested for loop to print the 2D vector that we just created above. */ for(int i = 0; i < row; i++) { for (int j = 0; j < vec[i].size(); j++) { cout << vec[i][j] << \" \"; } cout << endl; } return 0;}", "e": 30395, "s": 28827, "text": null }, { "code": null, "e": 30430, "s": 30395, "text": "1 2 3 4 5 \n1 2 3 \n1 2 3 4 \n1 2 \n1 " }, { "code": null, "e": 30534, "s": 30430, "text": "Another Approach Suppose we want to initialize a 2D vector of “n” rows and “m” columns, with a value 0." }, { "code": null, "e": 30538, "s": 30534, "text": "C++" }, { "code": "// CPP program#include <iostream>#include <vector>using namespace std;int main(){ int n = 3; int m = 4; /* We create a 2D vector containing \"n\" elements each having the value \"vector<int> (m, 0)\". \"vector<int> (m, 0)\" means a vector having \"m\" elements each of value \"0\". Here these elements are vectors. */ vector<vector<int>> vec( n , vector<int> (m, 0)); for(int i = 0; i < n; i++) { for(int j = 0; j < m; j++) { cout << vec[i][j] << \" \"; } cout<< endl; } return 0;}", "e": 31096, "s": 30538, "text": null }, { "code": null, "e": 31123, "s": 31096, "text": "0 0 0 0 \n0 0 0 0 \n0 0 0 0 " }, { "code": null, "e": 31230, "s": 31123, "text": "Yet Another Approach: Suppose we want to create a 2D vector of “n” rows and “m” columns and input values. " }, { "code": null, "e": 31234, "s": 31230, "text": "C++" }, { "code": "// CPP program#include <iostream>#include <vector>using namespace std;int main(){ int n = 4; int m = 5; /* Create a vector containing \"n\" vectors each of size \"m\". */ vector<vector<int>> vec( n , vector<int> (m)); for(int i = 0; i < n; i++) { for(int j = 0; j < m; j++) { vec[i][j] = j + i + 1; } } for(int i = 0; i < n; i++) { for(int j = 0; j < m; j++) { cout << vec[i][j] << \" \"; } cout << endl; } return 0;}", "e": 31766, "s": 31234, "text": null }, { "code": null, "e": 31810, "s": 31766, "text": "1 2 3 4 5 \n2 3 4 5 6 \n3 4 5 6 7 \n4 5 6 7 8 " }, { "code": null, "e": 31948, "s": 31810, "text": "We hope you that you leave this article with a better understanding of 2D vectors and are now confident enough to apply them on your own." }, { "code": null, "e": 32366, "s": 31948, "text": "This article is contributed by Amit Verma. 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": 32374, "s": 32366, "text": "Blinkii" }, { "code": null, "e": 32383, "s": 32374, "text": "greengod" }, { "code": null, "e": 32391, "s": 32383, "text": "dunno64" }, { "code": null, "e": 32403, "s": 32391, "text": "shashikantg" }, { "code": null, "e": 32413, "s": 32403, "text": "sachisahu" }, { "code": null, "e": 32428, "s": 32413, "text": "adnanirshad158" }, { "code": null, "e": 32445, "s": 32428, "text": "arorakashish0911" }, { "code": null, "e": 32455, "s": 32445, "text": "ruhelaa48" }, { "code": null, "e": 32470, "s": 32455, "text": "prachisoda1234" }, { "code": null, "e": 32481, "s": 32470, "text": "cpp-vector" }, { "code": null, "e": 32485, "s": 32481, "text": "STL" }, { "code": null, "e": 32489, "s": 32485, "text": "C++" }, { "code": null, "e": 32493, "s": 32489, "text": "STL" }, { "code": null, "e": 32497, "s": 32493, "text": "CPP" }, { "code": null, "e": 32595, "s": 32497, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32604, "s": 32595, "text": "Comments" }, { "code": null, "e": 32617, "s": 32604, "text": "Old Comments" }, { "code": null, "e": 32637, "s": 32617, "text": "Constructors in C++" }, { "code": null, "e": 32665, "s": 32637, "text": "Socket Programming in C/C++" }, { "code": null, "e": 32693, "s": 32665, "text": "Operator Overloading in C++" }, { "code": null, "e": 32717, "s": 32693, "text": "Copy Constructor in C++" }, { "code": null, "e": 32741, "s": 32717, "text": "Virtual Function in C++" }, { "code": null, "e": 32772, "s": 32741, "text": "Templates in C++ with Examples" }, { "code": null, "e": 32800, "s": 32772, "text": "rand() and srand() in C/C++" }, { "code": null, "e": 32834, "s": 32800, "text": "vector erase() and clear() in C++" }, { "code": null, "e": 32859, "s": 32834, "text": "unordered_map in C++ STL" } ]
Aho-Corasick Algorithm
This algorithm is helpful to find all occurrences of all given set of keywords. It is a kind of Dictionary-matching algorithm. It uses a tree structure using all keywords. After making the tree, it tries to convert the tree as an automaton to make the searching in linear time. There are three different phases of Aho-Corasick Algorithm. These are Go-to, Failure, and Output. In the go-to stage, it makes the tree using all the keywords. In the next phase or in the Failure Phase, it tries to find the backward transition to get a proper suffix of some keywords. In the output stage, for every state ‘s’ of the automaton, it finds all words which are ending at the state ‘s’. The time complexity of this algorithm is: O(N + L + Z), where N is the length of the text, L is the length of keywords and the Z is a number of matches. Input: A set of patterns: {their, there, answer, any, bye} The main string: “isthereanyanswerokgoodbye” Output: Word there location: 2 Word any location: 7 Word answer location: 10 Word bye location: 22 buildTree(patternList, size) Input − The list of all patterns, and the size of the list Output − Generate the transition map to find the patterns Begin set all elements of output array to 0 set all elements of fail array to -1 set all elements of goto matrix to -1 state := 1 //at first there is only one state. for all patterns ‘i’ in the patternList, do word := patternList[i] present := 0 for all character ‘ch’ of word, do if goto[present, ch] = -1 then goto[present, ch] := state state := state + 1 present:= goto[present, ch] done output[present] := output[present] OR (shift left 1 for i times) done for all type of characters ch, do if goto[0, ch] ≠ 0 then fail[goto[0,ch]] := 0 insert goto[0, ch] into a Queue q. done while q is not empty, do newState := first element of q delete from q. for all possible character ch, do if goto[newState, ch] ≠ -1 then failure := fail[newState] while goto[failure, ch] = -1, do failure := goto[failure, ch] done fail[goto[newState, ch]] = failure output[goto[newState, ch]] :=output[goto[newState,ch]] OR output[failure] insert goto[newState, ch] into q. done done return state End getNextState(presentState, nextChar) Input − present state and the next character to determine next state Output: the next state Begin answer := presentState ch := nextChar while goto[answer, ch] = -41, do answer := fail[answer] done return goto[answer, ch] End patternSearch(patternList, size, text) Input − List of patterns, size of the list and the main text Output − The indexes of the text where patterns are found Begin call buildTree(patternList, size) presentState := 0 for all indexes of the text, do if output[presentState] = 0 ignore next part and go for next iteration for all patterns in the patternList, do if the pattern found using output array, then print the location where pattern is present done done End #include <iostream> #include <queue> #define MAXS 500 //sum of the length of all patterns #define MAXC 26 //as 26 letters in alphabet using namespace std; int output[MAXS]; int fail[MAXS]; int gotoMat[MAXS][MAXC]; int buildTree(string array[], int size) { for(int i = 0; i<MAXS; i++) output[i] = 0; //all element of output is 0 for(int i = 0; i<MAXS; i++) fail[i] = -1; //all element of failure array is -1 for(int i = 0; i<MAXS; i++) for(int j = 0; j<MAXC; j++) gotoMat[i][j] = -1; //all element of goto matrix is -1 int state = 1; //there is only one state for (int i = 0; i < size; i++) { //make trie structure for all pattern in array //const string &word = array[i]; string word = array[i]; int presentState = 0; for (int j = 0; j < word.size(); ++j) { //all pattern is added int ch = word[j] - 'a'; if (gotoMat[presentState][ch] == -1) //ic ch is not present make new node gotoMat[presentState][ch] = state++; //increase state presentState = gotoMat[presentState][ch]; } output[presentState] |= (1 << i); //current word added in the output } for (int ch = 0; ch < MAXC; ++ch) //if ch is not directly connected to root if (gotoMat[0][ch] == -1) gotoMat[0][ch] = 0; queue<int> q; for (int ch = 0; ch < MAXC; ++ch) { //node goes to previous state when fails if (gotoMat[0][ch] != 0) { fail[gotoMat[0][ch]] = 0; q.push(gotoMat[0][ch]); } } while (q.size()) { int state = q.front(); //remove front node q.pop(); for (int ch = 0; ch <= MAXC; ++ch) { if (gotoMat[state][ch] != -1) { //if goto state is present int failure = fail[state]; while (gotoMat[failure][ch] == -1) //find deepest node with proper suffix failure = fail[failure]; failure = gotoMat[failure][ch]; fail[gotoMat[state][ch]] = failure; output[gotoMat[state][ch]] |= output[failure]; // Merge output values q.push(gotoMat[state][ch]); //add next level node to the queue } } } return state; } int getNextState(int presentState, char nextChar) { int answer = presentState; int ch = nextChar - 'a'; //subtract ascii of 'a' while (gotoMat[answer][ch] == -1) //if go to is not found, use fail function answer = fail[answer]; return gotoMat[answer][ch]; } void patternSearch(string arr[], int size, string text) { buildTree(arr, size); //make the trie structure int presentState = 0; //make current state as 0 for (int i = 0; i < text.size(); i++) { //find all occurances of pattern presentState = getNextState(presentState, text[i]); if (output[presentState] == 0) //if no match continue; for (int j = 0; j < size; ++j) { //matching found and print words if (output[presentState] & (1 << j)) { cout << "Word " << arr[j] << " location: " << i - arr[j].size() + 1 << endl; } } } } int main() { string arr[] = {"their", "there", "answer", "any", "bye"}; string text = "isthereanyanswerokgoodbye"; int k = sizeof(arr)/sizeof(arr[0]); patternSearch(arr, k, text); return 0; } Word there location: 2 Word any location: 7 Word answer location: 10 Word bye location: 22
[ { "code": null, "e": 1401, "s": 1062, "text": "This algorithm is helpful to find all occurrences of all given set of keywords. It is a kind of Dictionary-matching algorithm. It uses a tree structure using all keywords. After making the tree, it tries to convert the tree as an automaton to make the searching in linear time. There are three different phases of Aho-Corasick Algorithm. " }, { "code": null, "e": 1739, "s": 1401, "text": "These are Go-to, Failure, and Output. In the go-to stage, it makes the tree using all the keywords. In the next phase or in the Failure Phase, it tries to find the backward transition to get a proper suffix of some keywords. In the output stage, for every state ‘s’ of the automaton, it finds all words which are ending at the state ‘s’." }, { "code": null, "e": 1892, "s": 1739, "text": "The time complexity of this algorithm is: O(N + L + Z), where N is the length of the text, L is the length of keywords and the Z is a number of matches." }, { "code": null, "e": 2095, "s": 1892, "text": "Input:\nA set of patterns: {their, there, answer, any, bye}\nThe main string: “isthereanyanswerokgoodbye”\nOutput:\nWord there location: 2\nWord any location: 7\nWord answer location: 10\nWord bye location: 22" }, { "code": null, "e": 2124, "s": 2095, "text": "buildTree(patternList, size)" }, { "code": null, "e": 2183, "s": 2124, "text": "Input − The list of all patterns, and the size of the list" }, { "code": null, "e": 2241, "s": 2183, "text": "Output − Generate the transition map to find the patterns" }, { "code": null, "e": 3483, "s": 2241, "text": "Begin\n set all elements of output array to 0\n set all elements of fail array to -1\n set all elements of goto matrix to -1\n state := 1 //at first there is only one state.\n\n for all patterns ‘i’ in the patternList, do\n word := patternList[i]\n present := 0\n for all character ‘ch’ of word, do\n if goto[present, ch] = -1 then\n goto[present, ch] := state\n state := state + 1\n present:= goto[present, ch]\n done\n output[present] := output[present] OR (shift left 1 for i times)\n done\n\n for all type of characters ch, do\n if goto[0, ch] ≠ 0 then\n fail[goto[0,ch]] := 0\n insert goto[0, ch] into a Queue q.\n done\n\n while q is not empty, do\n newState := first element of q\n delete from q.\n for all possible character ch, do\n if goto[newState, ch] ≠ -1 then\n failure := fail[newState]\n while goto[failure, ch] = -1, do\n failure := goto[failure, ch]\n done\n\n fail[goto[newState, ch]] = failure\n output[goto[newState, ch]] :=output[goto[newState,ch]] OR output[failure]\n insert goto[newState, ch] into q.\n done\n done\n return state\nEnd" }, { "code": null, "e": 3520, "s": 3483, "text": "getNextState(presentState, nextChar)" }, { "code": null, "e": 3589, "s": 3520, "text": "Input − present state and the next character to determine next state" }, { "code": null, "e": 3612, "s": 3589, "text": "Output: the next state" }, { "code": null, "e": 3767, "s": 3612, "text": "Begin\n answer := presentState\n ch := nextChar\n\n while goto[answer, ch] = -41, do\n answer := fail[answer]\n done\n return goto[answer, ch]\nEnd" }, { "code": null, "e": 3806, "s": 3767, "text": "patternSearch(patternList, size, text)" }, { "code": null, "e": 3867, "s": 3806, "text": "Input − List of patterns, size of the list and the main text" }, { "code": null, "e": 3925, "s": 3867, "text": "Output − The indexes of the text where patterns are found" }, { "code": null, "e": 4291, "s": 3925, "text": "Begin\n call buildTree(patternList, size)\n presentState := 0\n\n for all indexes of the text, do\n if output[presentState] = 0\n ignore next part and go for next iteration\n for all patterns in the patternList, do\n if the pattern found using output array, then\n print the location where pattern is present\n done\n done\nEnd" }, { "code": null, "e": 7627, "s": 4291, "text": "#include <iostream>\n#include <queue>\n#define MAXS 500 //sum of the length of all patterns\n#define MAXC 26 //as 26 letters in alphabet\nusing namespace std;\n\nint output[MAXS];\nint fail[MAXS];\nint gotoMat[MAXS][MAXC];\n\nint buildTree(string array[], int size) {\n for(int i = 0; i<MAXS; i++)\n output[i] = 0; //all element of output is 0\n\n for(int i = 0; i<MAXS; i++)\n fail[i] = -1; //all element of failure array is -1\n\n for(int i = 0; i<MAXS; i++)\n for(int j = 0; j<MAXC; j++)\n gotoMat[i][j] = -1; //all element of goto matrix is -1\n\n int state = 1; //there is only one state\n\n for (int i = 0; i < size; i++) { //make trie structure for all pattern in array\n //const string &word = array[i];\n string word = array[i];\n int presentState = 0;\n\n for (int j = 0; j < word.size(); ++j) { //all pattern is added\n int ch = word[j] - 'a';\n if (gotoMat[presentState][ch] == -1) //ic ch is not present make new node\n gotoMat[presentState][ch] = state++; //increase state\n presentState = gotoMat[presentState][ch];\n }\n output[presentState] |= (1 << i); //current word added in the output\n }\n\n for (int ch = 0; ch < MAXC; ++ch) //if ch is not directly connected to root\n if (gotoMat[0][ch] == -1)\n gotoMat[0][ch] = 0;\n\n queue<int> q;\n\n for (int ch = 0; ch < MAXC; ++ch) { //node goes to previous state when fails\n if (gotoMat[0][ch] != 0) {\n fail[gotoMat[0][ch]] = 0;\n q.push(gotoMat[0][ch]);\n }\n }\n\n while (q.size()) {\n int state = q.front(); //remove front node\n q.pop();\n\n for (int ch = 0; ch <= MAXC; ++ch) {\n if (gotoMat[state][ch] != -1) { //if goto state is present\n int failure = fail[state];\n while (gotoMat[failure][ch] == -1) //find deepest node with proper suffix\n failure = fail[failure];\n failure = gotoMat[failure][ch];\n fail[gotoMat[state][ch]] = failure;\n output[gotoMat[state][ch]] |= output[failure]; // Merge output values\n q.push(gotoMat[state][ch]); //add next level node to the queue\n }\n }\n }\n return state;\n}\n\nint getNextState(int presentState, char nextChar) {\n int answer = presentState;\n int ch = nextChar - 'a'; //subtract ascii of 'a'\n\n while (gotoMat[answer][ch] == -1) //if go to is not found, use fail function\n answer = fail[answer];\n return gotoMat[answer][ch];\n}\n\nvoid patternSearch(string arr[], int size, string text) {\n buildTree(arr, size); //make the trie structure\n int presentState = 0; //make current state as 0\n\n for (int i = 0; i < text.size(); i++) { //find all occurances of pattern\n presentState = getNextState(presentState, text[i]);\n if (output[presentState] == 0) //if no match continue;\n for (int j = 0; j < size; ++j) { //matching found and print words\n if (output[presentState] & (1 << j)) {\n cout << \"Word \" << arr[j] << \" location: \" << i - arr[j].size() + 1 << endl;\n }\n }\n }\n}\n\nint main() {\n string arr[] = {\"their\", \"there\", \"answer\", \"any\", \"bye\"};\n string text = \"isthereanyanswerokgoodbye\";\n int k = sizeof(arr)/sizeof(arr[0]);\n patternSearch(arr, k, text);\n return 0;\n}" }, { "code": null, "e": 7718, "s": 7627, "text": "Word there location: 2\nWord any location: 7\nWord answer location: 10\nWord bye location: 22" } ]
Java - log() Method
The method returns the natural logarithm of the argument. double log(double d) Here is the detail of parameters − d − Any primitive data type. d − Any primitive data type. This method returns the natural logarithm of the argument. public class Test { public static void main(String args[]) { double x = 11.635; double y = 2.76; System.out.printf("The value of e is %.4f%n", Math.E); System.out.printf("log(%.3f) is %.3f%n", x, Math.log(x)); } } This will produce the following result − The value of e is 2.7183 log(11.635) is 2.454 16 Lectures 2 hours Malhar Lathkar 19 Lectures 5 hours Malhar Lathkar 25 Lectures 2.5 hours Anadi Sharma 126 Lectures 7 hours Tushar Kale 119 Lectures 17.5 hours Monica Mittal 76 Lectures 7 hours Arnab Chakraborty Print Add Notes Bookmark this page
[ { "code": null, "e": 2435, "s": 2377, "text": "The method returns the natural logarithm of the argument." }, { "code": null, "e": 2457, "s": 2435, "text": "double log(double d)\n" }, { "code": null, "e": 2492, "s": 2457, "text": "Here is the detail of parameters −" }, { "code": null, "e": 2521, "s": 2492, "text": "d − Any primitive data type." }, { "code": null, "e": 2550, "s": 2521, "text": "d − Any primitive data type." }, { "code": null, "e": 2609, "s": 2550, "text": "This method returns the natural logarithm of the argument." }, { "code": null, "e": 2856, "s": 2609, "text": "public class Test { \n\n public static void main(String args[]) {\n double x = 11.635;\n double y = 2.76;\n\n System.out.printf(\"The value of e is %.4f%n\", Math.E);\n System.out.printf(\"log(%.3f) is %.3f%n\", x, Math.log(x));\n }\n}" }, { "code": null, "e": 2897, "s": 2856, "text": "This will produce the following result −" }, { "code": null, "e": 2944, "s": 2897, "text": "The value of e is 2.7183\nlog(11.635) is 2.454\n" }, { "code": null, "e": 2977, "s": 2944, "text": "\n 16 Lectures \n 2 hours \n" }, { "code": null, "e": 2993, "s": 2977, "text": " Malhar Lathkar" }, { "code": null, "e": 3026, "s": 2993, "text": "\n 19 Lectures \n 5 hours \n" }, { "code": null, "e": 3042, "s": 3026, "text": " Malhar Lathkar" }, { "code": null, "e": 3077, "s": 3042, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3091, "s": 3077, "text": " Anadi Sharma" }, { "code": null, "e": 3125, "s": 3091, "text": "\n 126 Lectures \n 7 hours \n" }, { "code": null, "e": 3139, "s": 3125, "text": " Tushar Kale" }, { "code": null, "e": 3176, "s": 3139, "text": "\n 119 Lectures \n 17.5 hours \n" }, { "code": null, "e": 3191, "s": 3176, "text": " Monica Mittal" }, { "code": null, "e": 3224, "s": 3191, "text": "\n 76 Lectures \n 7 hours \n" }, { "code": null, "e": 3243, "s": 3224, "text": " Arnab Chakraborty" }, { "code": null, "e": 3250, "s": 3243, "text": " Print" }, { "code": null, "e": 3261, "s": 3250, "text": " Add Notes" } ]
What is the maximum length of string in Python?
Maximum length of a string is platform dependent and depends upon address space and/or RAM. The maxsize constant defined in sys module returns 263-1 on 64 bit system. >>> import sys >>> sys.maxsize 9223372036854775807 The largest positive integer supported by the platform's Py_ssize_t type, is the maximum size lists, strings, dicts, and many other containers can have.
[ { "code": null, "e": 1229, "s": 1062, "text": "Maximum length of a string is platform dependent and depends upon address space and/or RAM. The maxsize constant defined in sys module returns 263-1 on 64 bit system." }, { "code": null, "e": 1283, "s": 1229, "text": ">>> import sys\n>>> sys.maxsize\n 9223372036854775807" }, { "code": null, "e": 1436, "s": 1283, "text": "The largest positive integer supported by the platform's Py_ssize_t type, is the maximum size lists, strings, dicts, and many other containers can have." } ]
Difference between String class and StringBuffer class in Java
Strings, which are widely used in Java programming, are a sequence of characters. In Java programming language, strings are treated as objects. The Java platform provides the String class to create and manipulate strings. Whereas, StringBuffer class is a thread-safe, mutable sequence of characters. A string buffer is like a String, but can be modified. It contains some particular sequence of characters, but the length and content of the sequence can be changed through certain method calls. They are safe for use by multiple threads. Every string buffer has a capacity. Live Demo public class Sample { public static void main(String args[]) { String str = new String("Hi welcome to tutorialspoint"); System.out.println(str); StringBuffer sBuffer = new StringBuffer("test"); sBuffer.append(" String Buffer"); System.out.println(sBuffer); } } Hi welcome to tutorialspoint test String Buffer
[ { "code": null, "e": 1284, "s": 1062, "text": "Strings, which are widely used in Java programming, are a sequence of characters. In Java programming language, strings are treated as objects. The Java platform provides the String class to create and manipulate strings." }, { "code": null, "e": 1362, "s": 1284, "text": "Whereas, StringBuffer class is a thread-safe, mutable sequence of characters." }, { "code": null, "e": 1417, "s": 1362, "text": "A string buffer is like a String, but can be modified." }, { "code": null, "e": 1557, "s": 1417, "text": "It contains some particular sequence of characters, but the length and content of the sequence can be changed through certain method calls." }, { "code": null, "e": 1600, "s": 1557, "text": "They are safe for use by multiple threads." }, { "code": null, "e": 1636, "s": 1600, "text": "Every string buffer has a capacity." }, { "code": null, "e": 1646, "s": 1636, "text": "Live Demo" }, { "code": null, "e": 1943, "s": 1646, "text": "public class Sample {\n public static void main(String args[]) {\n String str = new String(\"Hi welcome to tutorialspoint\");\n System.out.println(str);\n StringBuffer sBuffer = new StringBuffer(\"test\");\n sBuffer.append(\" String Buffer\");\n System.out.println(sBuffer);\n }\n}" }, { "code": null, "e": 1991, "s": 1943, "text": "Hi welcome to tutorialspoint\ntest String Buffer" } ]
Getting started on Deep Learning for Audio Data | by Tirmidzi Faizal Aflahi | Towards Data Science
While traditional Machine Learning algorithm still triumphs on structural data with the insurgence of Gradient Boosting method, nothing beats Deep Learning on processing unstructured data. Let’s get back to the title. Audio Data, are you sure? Well, intentional or not, I think most of us already tried some solutions in Audio-based Deep Learning system. I can surely assume that most of us have tried this thing. Have you ever think of how that feature built? Yes, unstructured data is by far the most suitable data for Deep Learning. While you can also use it on structured data, traditional Machine Learning can beat the performance easily on a moderate amount of data. Things like Self-driving Cars, face recognition, or the notorious FaceApp that went viral several months ago, are the by-product of Deep Learning system on images data. Image data = pixels of colors = unstructured data Basically, unstructured data means a bunch of data points, without a mean to statistically analyze them. Well, you can’t use any form of standard deviation on pixels, so images are unstructured. So be texts and audios. Audio data is a bunch of wave signals sequenced one after another. You can’t possibly analyze how the effect of the mean to the model. So, you know about the concept of unstructured data. Now, you want to know how that “Ok, Google!” thing being built. In layman’s term, the flow should be like this: Your phone listens to surrounding words → someone says the keyword, “Ok, Google!” → the assistant app activates. What! My phone listened to me every time? Isn’t that a violation of privacy? Well, I don’t want to talk about that problem with this article. Let’s move on to step 2 and 3. If your phone listens to the keyword, it opens the app. So, in this particular tutorial, I want to share on how you can build an algorithm that able to distinguish the keyword from other voices. Let’s take a look at Kaggle, There is a competition on how to distinguished Turkey (the animal) sound from other voices. Why turkey? I don’t know. At least, it fits our needs. It doesn’t have to be a human voice as the keyword, does it? Lol. Download the data, and you can see the training data (train.json) You will see a JSON list with 1195 items, which means, you have 1995 items as training data. Each item will have 5 attributes, The video ID, which is the id of video from YouTubeStart Time of the clipEnd Time of the clip (So, not all video is used, only 10 seconds of the video)is_turkey, determine is that a turkey or notThe audio embedding, this is the 10 seconds embedding from the audio. They use the scripts in https://github.com/tensorflow/models/tree/master/research/audioset to change audio waves into numbers. We can just use the processed result. The video ID, which is the id of video from YouTube Start Time of the clip End Time of the clip (So, not all video is used, only 10 seconds of the video) is_turkey, determine is that a turkey or not The audio embedding, this is the 10 seconds embedding from the audio. They use the scripts in https://github.com/tensorflow/models/tree/master/research/audioset to change audio waves into numbers. We can just use the processed result. For example, you can watch this awesome turkey video, Awesome Turkey Watch from the 30th seconds to 40th. You know that there are turkeys, even though the background music disturbs the peace. Wait, I am getting overwhelmed. It seems so complicated. I want to start from the very beginning. I don’t know about Deep Learning, not even turkeys. You can find lots of resources on the internet from books, lectures, to courses. Just go google it. Or you can just go from what I have curated before. So, now you are already familiar with the jargons and other kinds of stuff, you are ready to go. Of course, Python. You need to install it first from the Python official website. You need to install version 3.6+ to keep up to date with the libraries. And install other things from the terminal, pip install numpypip install pandaspip install seabornpip install matplotlibpip install tensorflowpip install keraspip install jupyter Let’s type jupyter notebook from the terminal and we are ready to go! import numpy as npimport pandas as pd import osimport seaborn as snsimport matplotlib.pyplot as pltimport seaborn as snsplt.style.use('fivethirtyeight')from tqdm import tqdmprint(os.listdir("../input")) Prepare the libraries, and you can see the output ['train.json', 'sample_submission.csv', 'test.json'] Import Keras packages you need from keras import Sequentialfrom keras import optimizersfrom keras.preprocessing.sequence import pad_sequencesfrom keras.models import Sequential,Modelfrom keras.layers import LSTM, Dense, Bidirectional, Input,Dropout,BatchNormalization,CuDNNLSTM, GRU, CuDNNGRU, Embedding, GlobalMaxPooling1D, GlobalAveragePooling1D, Flattenfrom keras import backend as Kfrom keras.engine.topology import Layerfrom keras import initializers, regularizers, constraintsfrom sklearn.model_selection import KFold, cross_val_score, train_test_split And of course, prepare your data train = pd.read_json('../input/train.json')display(train.shape) It will show (1195, 5) Yep, you got 1195 data to work on. Let’s take a look inside the data train.head() Let’s prepare the data for training. You need to split some of them for validation, so that you can sure the model will work well on unseen data. train_train, train_val = train_test_split(train, random_state = 42)xtrain = [k for k in train_train['audio_embedding']]ytrain = train_train['is_turkey'].valuesxval = [k for k in train_val['audio_embedding']]yval = train_val['is_turkey'].values train_test_split method by default splitting the data by 3:1 means 75% of the data goes into the training set, while the rest 25% to the validation set. To create a standard on the data, let’s pad all audio embedding with zero until all of them have the same length of 10 seconds. # Pad the audio features so that all are "10 seconds" longx_train = pad_sequences(xtrain, maxlen=10)x_val = pad_sequences(xval, maxlen=10)y_train = np.asarray(ytrain)y_val = np.asarray(yval) model = Sequential()model.add(BatchNormalization(momentum=0.98,input_shape=(10, 128)))model.add(Bidirectional(CuDNNGRU(128, return_sequences = True)))model.add(Flatten())model.add(Dense(1,activation='sigmoid'))model.compile(loss='binary_crossentropy', optimizer = optimizers.Nadam(lr=0.001), metrics=['accuracy'])print(model.summary()) The detail would be like this: _________________________________________________________________Layer (type) Output Shape Param # =================================================================batch_normalization_7 (Batch (None, 10, 128) 512 _________________________________________________________________bidirectional_7 (Bidirection (None, 10, 256) 198144 _________________________________________________________________flatten_2 (Flatten) (None, 2560) 0 _________________________________________________________________dense_7 (Dense) (None, 1) 2561 =================================================================Total params: 201,217Trainable params: 200,961Non-trainable params: 256_________________________________________________________________ Take a look at this code model.add(Bidirectional(CuDNNGRU(128, return_sequences = True))) What the hell is that? Let’s see the beautiful sunrise before continuing. And refresh your brain of course. Lol This is something you have to know. Audio data is a sequence of sound waves. Attached one into another. With that property, audio data is basically a sequence of numbers. And of course with numbers, you can use LSTM of GRU. Both of these algorithms are really good at processing sequence of numbers. Basically, they can save what they have “read” and use that information when processing the next number. That “short term memory” gives them an edge over other algorithms. And in this tutorial, I used GRU Let’s get back to the code model = Sequential()model.add(BatchNormalization(momentum=0.98,input_shape=(10, 128)))model.add(Bidirectional(CuDNNGRU(128, return_sequences = True)))model.add(Flatten())model.add(Dense(1,activation='sigmoid')) I create a simple model on Keras, Add BatchNorm layer to standardize the input numbers (The audio inputs have not standardized yet)Add the Bidirectional GRU to process the inputFlatten the resultCreate a sigmoid Dense Layer for “True-False” or binary problems. Add BatchNorm layer to standardize the input numbers (The audio inputs have not standardized yet) Add the Bidirectional GRU to process the input Flatten the result Create a sigmoid Dense Layer for “True-False” or binary problems. #fit on a portion of the training data, and validate on the restfrom keras.callbacks import EarlyStopping, ModelCheckpoint, ReduceLROnPlateaureduce_lr = ReduceLROnPlateau(monitor='val_acc', factor=0.1, patience=2, verbose=1, min_lr=1e-8)early_stop = EarlyStopping(monitor='val_loss', verbose=1, patience=20, restore_best_weights=True)history = model.fit(x_train, y_train,batch_size=512, epochs=16,validation_data=[x_val, y_val],verbose = 2,callbacks=[reduce_lr,early_stop]) It will show you this result Epoch 16/16 - 0s - loss: 0.1037 - acc: 0.9710 - val_loss: 0.1694 - val_acc: 0.9231 It has 92.31% Accuracy on validation test! Awesome! Let’s plot the training history def eva_plot(History): plt.figure(figsize=(20,10)) sns.lineplot(range(1, 16+1), History.history['acc'], label='Train Accuracy') sns.lineplot(range(1, 16+1), History.history['val_acc'], label='Test Accuracy') plt.legend(['train', 'validaiton'], loc='upper left') plt.ylabel('accuracy') plt.xlabel('epoch') plt.show() plt.figure(figsize=(20,10)) sns.lineplot(range(1, 16+1), History.history['loss'], label='Train loss') sns.lineplot(range(1, 16+1), History.history['val_loss'], label='Test loss') plt.legend(['train', 'validaiton'], loc='upper left') plt.ylabel('loss') plt.xlabel('epoch') plt.show()eva_plot(history) This simple model can actually do something great. We don’t even do any optimization on it. Well, if you want to optimize, you are welcome to do it. Although, I want to do another form of optimization. I don’t know about the result, so why not. No, I mean, attention mechanism. Take a look at the image below What did you see? Of course, the bird Not the greenish background in the image. That’s how human perceive. And we want to simulate that mechanism to the machine. The figure above shows you about attention mechanism. It is a mechanism which forces the network to look at something while processing something new. Each row means the processing step by step. The red word is the currently processed word. While the blueish one, more blueish means the more the machine attend the word. This will make the machine keeping with the context. Thanks to our friend at kaggle, we can use this awesome class, class Attention(Layer): def __init__(self, step_dim, W_regularizer=None, b_regularizer=None, W_constraint=None, b_constraint=None, bias=True, **kwargs): self.supports_masking = True self.init = initializers.get('glorot_uniform')self.W_regularizer = regularizers.get(W_regularizer) self.b_regularizer = regularizers.get(b_regularizer)self.W_constraint = constraints.get(W_constraint) self.b_constraint = constraints.get(b_constraint)self.bias = bias self.step_dim = step_dim self.features_dim = 0 super(Attention, self).__init__(**kwargs) def build(self, input_shape): assert len(input_shape) == 3 self.W = self.add_weight((input_shape[-1],), initializer=self.init, name='{}_W'.format(self.name), regularizer=self.W_regularizer, constraint=self.W_constraint) self.features_dim = input_shape[-1] if self.bias: self.b = self.add_weight((input_shape[1],), initializer='zero', name='{}_b'.format(self.name), regularizer=self.b_regularizer, constraint=self.b_constraint) else: self.b = None self.built = True def compute_mask(self, input, input_mask=None): return None def call(self, x, mask=None): features_dim = self.features_dim step_dim = self.step_dim eij = K.reshape(K.dot(K.reshape(x, (-1, features_dim)), K.reshape(self.W, (features_dim, 1))), (-1, step_dim)) if self.bias: eij += self.b eij = K.tanh(eij) a = K.exp(eij) if mask is not None: a *= K.cast(mask, K.floatx()) a /= K.cast(K.sum(a, axis=1, keepdims=True) + K.epsilon(), K.floatx()) a = K.expand_dims(a) weighted_input = x * a return K.sum(weighted_input, axis=1) def compute_output_shape(self, input_shape): return input_shape[0], self.features_dim Don’t force yourself to understand the thing. Let’s just change our model model = Sequential()model.add(BatchNormalization(momentum=0.98,input_shape=(10, 128)))model.add(Bidirectional(CuDNNGRU(128, return_sequences = True)))model.add(Attention(10))model.add(Dense(1,activation='sigmoid'))model.compile(loss='binary_crossentropy', optimizer = optimizers.Nadam(lr=0.001), metrics=['accuracy'])print(model.summary()) Change the flatten layer into attention. And you will see _________________________________________________________________Layer (type) Output Shape Param # =================================================================batch_normalization_6 (Batch (None, 10, 128) 512 _________________________________________________________________bidirectional_6 (Bidirection (None, 10, 256) 198144 _________________________________________________________________attention_2 (Attention) (None, 256) 266 _________________________________________________________________dense_6 (Dense) (None, 1) 257 =================================================================Total params: 199,179Trainable params: 198,923Non-trainable params: 256_________________________________________________________________ It reduces around 2,000 trainable params. Well, that’s a good thing. Let’s try the training early_stop = EarlyStopping(monitor='val_loss', verbose=1, patience=20, restore_best_weights=True)model.fit(x_train, y_train,batch_size=512, epochs=16,validation_data=[x_val, y_val],verbose = 2,callbacks=[reduce_lr,early_stop]) Now you get: Epoch 16/16 - 0s - loss: 0.1037 - acc: 0.9710 - val_loss: 0.1680 - val_acc: 0.9331 Yeah! A 1% increase into 93.31% Not much, but definitely an increase! It is amazingly easy to get started to create a Deep Learning system for audio data. You just need to know-how. And get good to create the real “Ok, Google!”. Go ahead and try. Of course, you can try the tutorial and change the parameters or the network however you want.
[ { "code": null, "e": 361, "s": 172, "text": "While traditional Machine Learning algorithm still triumphs on structural data with the insurgence of Gradient Boosting method, nothing beats Deep Learning on processing unstructured data." }, { "code": null, "e": 390, "s": 361, "text": "Let’s get back to the title." }, { "code": null, "e": 416, "s": 390, "text": "Audio Data, are you sure?" }, { "code": null, "e": 527, "s": 416, "text": "Well, intentional or not, I think most of us already tried some solutions in Audio-based Deep Learning system." }, { "code": null, "e": 586, "s": 527, "text": "I can surely assume that most of us have tried this thing." }, { "code": null, "e": 633, "s": 586, "text": "Have you ever think of how that feature built?" }, { "code": null, "e": 845, "s": 633, "text": "Yes, unstructured data is by far the most suitable data for Deep Learning. While you can also use it on structured data, traditional Machine Learning can beat the performance easily on a moderate amount of data." }, { "code": null, "e": 1014, "s": 845, "text": "Things like Self-driving Cars, face recognition, or the notorious FaceApp that went viral several months ago, are the by-product of Deep Learning system on images data." }, { "code": null, "e": 1064, "s": 1014, "text": "Image data = pixels of colors = unstructured data" }, { "code": null, "e": 1259, "s": 1064, "text": "Basically, unstructured data means a bunch of data points, without a mean to statistically analyze them. Well, you can’t use any form of standard deviation on pixels, so images are unstructured." }, { "code": null, "e": 1283, "s": 1259, "text": "So be texts and audios." }, { "code": null, "e": 1418, "s": 1283, "text": "Audio data is a bunch of wave signals sequenced one after another. You can’t possibly analyze how the effect of the mean to the model." }, { "code": null, "e": 1535, "s": 1418, "text": "So, you know about the concept of unstructured data. Now, you want to know how that “Ok, Google!” thing being built." }, { "code": null, "e": 1583, "s": 1535, "text": "In layman’s term, the flow should be like this:" }, { "code": null, "e": 1696, "s": 1583, "text": "Your phone listens to surrounding words → someone says the keyword, “Ok, Google!” → the assistant app activates." }, { "code": null, "e": 1702, "s": 1696, "text": "What!" }, { "code": null, "e": 1773, "s": 1702, "text": "My phone listened to me every time? Isn’t that a violation of privacy?" }, { "code": null, "e": 1869, "s": 1773, "text": "Well, I don’t want to talk about that problem with this article. Let’s move on to step 2 and 3." }, { "code": null, "e": 1925, "s": 1869, "text": "If your phone listens to the keyword, it opens the app." }, { "code": null, "e": 2064, "s": 1925, "text": "So, in this particular tutorial, I want to share on how you can build an algorithm that able to distinguish the keyword from other voices." }, { "code": null, "e": 2093, "s": 2064, "text": "Let’s take a look at Kaggle," }, { "code": null, "e": 2306, "s": 2093, "text": "There is a competition on how to distinguished Turkey (the animal) sound from other voices. Why turkey? I don’t know. At least, it fits our needs. It doesn’t have to be a human voice as the keyword, does it? Lol." }, { "code": null, "e": 2372, "s": 2306, "text": "Download the data, and you can see the training data (train.json)" }, { "code": null, "e": 2465, "s": 2372, "text": "You will see a JSON list with 1195 items, which means, you have 1995 items as training data." }, { "code": null, "e": 2499, "s": 2465, "text": "Each item will have 5 attributes," }, { "code": null, "e": 2929, "s": 2499, "text": "The video ID, which is the id of video from YouTubeStart Time of the clipEnd Time of the clip (So, not all video is used, only 10 seconds of the video)is_turkey, determine is that a turkey or notThe audio embedding, this is the 10 seconds embedding from the audio. They use the scripts in https://github.com/tensorflow/models/tree/master/research/audioset to change audio waves into numbers. We can just use the processed result." }, { "code": null, "e": 2981, "s": 2929, "text": "The video ID, which is the id of video from YouTube" }, { "code": null, "e": 3004, "s": 2981, "text": "Start Time of the clip" }, { "code": null, "e": 3083, "s": 3004, "text": "End Time of the clip (So, not all video is used, only 10 seconds of the video)" }, { "code": null, "e": 3128, "s": 3083, "text": "is_turkey, determine is that a turkey or not" }, { "code": null, "e": 3363, "s": 3128, "text": "The audio embedding, this is the 10 seconds embedding from the audio. They use the scripts in https://github.com/tensorflow/models/tree/master/research/audioset to change audio waves into numbers. We can just use the processed result." }, { "code": null, "e": 3417, "s": 3363, "text": "For example, you can watch this awesome turkey video," }, { "code": null, "e": 3432, "s": 3417, "text": "Awesome Turkey" }, { "code": null, "e": 3555, "s": 3432, "text": "Watch from the 30th seconds to 40th. You know that there are turkeys, even though the background music disturbs the peace." }, { "code": null, "e": 3587, "s": 3555, "text": "Wait, I am getting overwhelmed." }, { "code": null, "e": 3705, "s": 3587, "text": "It seems so complicated. I want to start from the very beginning. I don’t know about Deep Learning, not even turkeys." }, { "code": null, "e": 3805, "s": 3705, "text": "You can find lots of resources on the internet from books, lectures, to courses. Just go google it." }, { "code": null, "e": 3857, "s": 3805, "text": "Or you can just go from what I have curated before." }, { "code": null, "e": 3954, "s": 3857, "text": "So, now you are already familiar with the jargons and other kinds of stuff, you are ready to go." }, { "code": null, "e": 4108, "s": 3954, "text": "Of course, Python. You need to install it first from the Python official website. You need to install version 3.6+ to keep up to date with the libraries." }, { "code": null, "e": 4152, "s": 4108, "text": "And install other things from the terminal," }, { "code": null, "e": 4287, "s": 4152, "text": "pip install numpypip install pandaspip install seabornpip install matplotlibpip install tensorflowpip install keraspip install jupyter" }, { "code": null, "e": 4357, "s": 4287, "text": "Let’s type jupyter notebook from the terminal and we are ready to go!" }, { "code": null, "e": 4560, "s": 4357, "text": "import numpy as npimport pandas as pd import osimport seaborn as snsimport matplotlib.pyplot as pltimport seaborn as snsplt.style.use('fivethirtyeight')from tqdm import tqdmprint(os.listdir(\"../input\"))" }, { "code": null, "e": 4610, "s": 4560, "text": "Prepare the libraries, and you can see the output" }, { "code": null, "e": 4663, "s": 4610, "text": "['train.json', 'sample_submission.csv', 'test.json']" }, { "code": null, "e": 4694, "s": 4663, "text": "Import Keras packages you need" }, { "code": null, "e": 5222, "s": 4694, "text": "from keras import Sequentialfrom keras import optimizersfrom keras.preprocessing.sequence import pad_sequencesfrom keras.models import Sequential,Modelfrom keras.layers import LSTM, Dense, Bidirectional, Input,Dropout,BatchNormalization,CuDNNLSTM, GRU, CuDNNGRU, Embedding, GlobalMaxPooling1D, GlobalAveragePooling1D, Flattenfrom keras import backend as Kfrom keras.engine.topology import Layerfrom keras import initializers, regularizers, constraintsfrom sklearn.model_selection import KFold, cross_val_score, train_test_split" }, { "code": null, "e": 5255, "s": 5222, "text": "And of course, prepare your data" }, { "code": null, "e": 5319, "s": 5255, "text": "train = pd.read_json('../input/train.json')display(train.shape)" }, { "code": null, "e": 5332, "s": 5319, "text": "It will show" }, { "code": null, "e": 5342, "s": 5332, "text": "(1195, 5)" }, { "code": null, "e": 5377, "s": 5342, "text": "Yep, you got 1195 data to work on." }, { "code": null, "e": 5411, "s": 5377, "text": "Let’s take a look inside the data" }, { "code": null, "e": 5424, "s": 5411, "text": "train.head()" }, { "code": null, "e": 5570, "s": 5424, "text": "Let’s prepare the data for training. You need to split some of them for validation, so that you can sure the model will work well on unseen data." }, { "code": null, "e": 5814, "s": 5570, "text": "train_train, train_val = train_test_split(train, random_state = 42)xtrain = [k for k in train_train['audio_embedding']]ytrain = train_train['is_turkey'].valuesxval = [k for k in train_val['audio_embedding']]yval = train_val['is_turkey'].values" }, { "code": null, "e": 5967, "s": 5814, "text": "train_test_split method by default splitting the data by 3:1 means 75% of the data goes into the training set, while the rest 25% to the validation set." }, { "code": null, "e": 6095, "s": 5967, "text": "To create a standard on the data, let’s pad all audio embedding with zero until all of them have the same length of 10 seconds." }, { "code": null, "e": 6286, "s": 6095, "text": "# Pad the audio features so that all are \"10 seconds\" longx_train = pad_sequences(xtrain, maxlen=10)x_val = pad_sequences(xval, maxlen=10)y_train = np.asarray(ytrain)y_val = np.asarray(yval)" }, { "code": null, "e": 6622, "s": 6286, "text": "model = Sequential()model.add(BatchNormalization(momentum=0.98,input_shape=(10, 128)))model.add(Bidirectional(CuDNNGRU(128, return_sequences = True)))model.add(Flatten())model.add(Dense(1,activation='sigmoid'))model.compile(loss='binary_crossentropy', optimizer = optimizers.Nadam(lr=0.001), metrics=['accuracy'])print(model.summary())" }, { "code": null, "e": 6653, "s": 6622, "text": "The detail would be like this:" }, { "code": null, "e": 7505, "s": 6653, "text": "_________________________________________________________________Layer (type) Output Shape Param # =================================================================batch_normalization_7 (Batch (None, 10, 128) 512 _________________________________________________________________bidirectional_7 (Bidirection (None, 10, 256) 198144 _________________________________________________________________flatten_2 (Flatten) (None, 2560) 0 _________________________________________________________________dense_7 (Dense) (None, 1) 2561 =================================================================Total params: 201,217Trainable params: 200,961Non-trainable params: 256_________________________________________________________________" }, { "code": null, "e": 7530, "s": 7505, "text": "Take a look at this code" }, { "code": null, "e": 7595, "s": 7530, "text": "model.add(Bidirectional(CuDNNGRU(128, return_sequences = True)))" }, { "code": null, "e": 7618, "s": 7595, "text": "What the hell is that?" }, { "code": null, "e": 7707, "s": 7618, "text": "Let’s see the beautiful sunrise before continuing. And refresh your brain of course. Lol" }, { "code": null, "e": 7811, "s": 7707, "text": "This is something you have to know. Audio data is a sequence of sound waves. Attached one into another." }, { "code": null, "e": 7878, "s": 7811, "text": "With that property, audio data is basically a sequence of numbers." }, { "code": null, "e": 7931, "s": 7878, "text": "And of course with numbers, you can use LSTM of GRU." }, { "code": null, "e": 8179, "s": 7931, "text": "Both of these algorithms are really good at processing sequence of numbers. Basically, they can save what they have “read” and use that information when processing the next number. That “short term memory” gives them an edge over other algorithms." }, { "code": null, "e": 8212, "s": 8179, "text": "And in this tutorial, I used GRU" }, { "code": null, "e": 8239, "s": 8212, "text": "Let’s get back to the code" }, { "code": null, "e": 8450, "s": 8239, "text": "model = Sequential()model.add(BatchNormalization(momentum=0.98,input_shape=(10, 128)))model.add(Bidirectional(CuDNNGRU(128, return_sequences = True)))model.add(Flatten())model.add(Dense(1,activation='sigmoid'))" }, { "code": null, "e": 8484, "s": 8450, "text": "I create a simple model on Keras," }, { "code": null, "e": 8711, "s": 8484, "text": "Add BatchNorm layer to standardize the input numbers (The audio inputs have not standardized yet)Add the Bidirectional GRU to process the inputFlatten the resultCreate a sigmoid Dense Layer for “True-False” or binary problems." }, { "code": null, "e": 8809, "s": 8711, "text": "Add BatchNorm layer to standardize the input numbers (The audio inputs have not standardized yet)" }, { "code": null, "e": 8856, "s": 8809, "text": "Add the Bidirectional GRU to process the input" }, { "code": null, "e": 8875, "s": 8856, "text": "Flatten the result" }, { "code": null, "e": 8941, "s": 8875, "text": "Create a sigmoid Dense Layer for “True-False” or binary problems." }, { "code": null, "e": 9416, "s": 8941, "text": "#fit on a portion of the training data, and validate on the restfrom keras.callbacks import EarlyStopping, ModelCheckpoint, ReduceLROnPlateaureduce_lr = ReduceLROnPlateau(monitor='val_acc', factor=0.1, patience=2, verbose=1, min_lr=1e-8)early_stop = EarlyStopping(monitor='val_loss', verbose=1, patience=20, restore_best_weights=True)history = model.fit(x_train, y_train,batch_size=512, epochs=16,validation_data=[x_val, y_val],verbose = 2,callbacks=[reduce_lr,early_stop])" }, { "code": null, "e": 9445, "s": 9416, "text": "It will show you this result" }, { "code": null, "e": 9528, "s": 9445, "text": "Epoch 16/16 - 0s - loss: 0.1037 - acc: 0.9710 - val_loss: 0.1694 - val_acc: 0.9231" }, { "code": null, "e": 9580, "s": 9528, "text": "It has 92.31% Accuracy on validation test! Awesome!" }, { "code": null, "e": 9612, "s": 9580, "text": "Let’s plot the training history" }, { "code": null, "e": 10270, "s": 9612, "text": "def eva_plot(History): plt.figure(figsize=(20,10)) sns.lineplot(range(1, 16+1), History.history['acc'], label='Train Accuracy') sns.lineplot(range(1, 16+1), History.history['val_acc'], label='Test Accuracy') plt.legend(['train', 'validaiton'], loc='upper left') plt.ylabel('accuracy') plt.xlabel('epoch') plt.show() plt.figure(figsize=(20,10)) sns.lineplot(range(1, 16+1), History.history['loss'], label='Train loss') sns.lineplot(range(1, 16+1), History.history['val_loss'], label='Test loss') plt.legend(['train', 'validaiton'], loc='upper left') plt.ylabel('loss') plt.xlabel('epoch') plt.show()eva_plot(history)" }, { "code": null, "e": 10362, "s": 10270, "text": "This simple model can actually do something great. We don’t even do any optimization on it." }, { "code": null, "e": 10419, "s": 10362, "text": "Well, if you want to optimize, you are welcome to do it." }, { "code": null, "e": 10515, "s": 10419, "text": "Although, I want to do another form of optimization. I don’t know about the result, so why not." }, { "code": null, "e": 10579, "s": 10515, "text": "No, I mean, attention mechanism. Take a look at the image below" }, { "code": null, "e": 10597, "s": 10579, "text": "What did you see?" }, { "code": null, "e": 10617, "s": 10597, "text": "Of course, the bird" }, { "code": null, "e": 10659, "s": 10617, "text": "Not the greenish background in the image." }, { "code": null, "e": 10741, "s": 10659, "text": "That’s how human perceive. And we want to simulate that mechanism to the machine." }, { "code": null, "e": 10891, "s": 10741, "text": "The figure above shows you about attention mechanism. It is a mechanism which forces the network to look at something while processing something new." }, { "code": null, "e": 11061, "s": 10891, "text": "Each row means the processing step by step. The red word is the currently processed word. While the blueish one, more blueish means the more the machine attend the word." }, { "code": null, "e": 11114, "s": 11061, "text": "This will make the machine keeping with the context." }, { "code": null, "e": 11177, "s": 11114, "text": "Thanks to our friend at kaggle, we can use this awesome class," }, { "code": null, "e": 13374, "s": 11177, "text": "class Attention(Layer): def __init__(self, step_dim, W_regularizer=None, b_regularizer=None, W_constraint=None, b_constraint=None, bias=True, **kwargs): self.supports_masking = True self.init = initializers.get('glorot_uniform')self.W_regularizer = regularizers.get(W_regularizer) self.b_regularizer = regularizers.get(b_regularizer)self.W_constraint = constraints.get(W_constraint) self.b_constraint = constraints.get(b_constraint)self.bias = bias self.step_dim = step_dim self.features_dim = 0 super(Attention, self).__init__(**kwargs) def build(self, input_shape): assert len(input_shape) == 3 self.W = self.add_weight((input_shape[-1],), initializer=self.init, name='{}_W'.format(self.name), regularizer=self.W_regularizer, constraint=self.W_constraint) self.features_dim = input_shape[-1] if self.bias: self.b = self.add_weight((input_shape[1],), initializer='zero', name='{}_b'.format(self.name), regularizer=self.b_regularizer, constraint=self.b_constraint) else: self.b = None self.built = True def compute_mask(self, input, input_mask=None): return None def call(self, x, mask=None): features_dim = self.features_dim step_dim = self.step_dim eij = K.reshape(K.dot(K.reshape(x, (-1, features_dim)), K.reshape(self.W, (features_dim, 1))), (-1, step_dim)) if self.bias: eij += self.b eij = K.tanh(eij) a = K.exp(eij) if mask is not None: a *= K.cast(mask, K.floatx()) a /= K.cast(K.sum(a, axis=1, keepdims=True) + K.epsilon(), K.floatx()) a = K.expand_dims(a) weighted_input = x * a return K.sum(weighted_input, axis=1) def compute_output_shape(self, input_shape): return input_shape[0], self.features_dim" }, { "code": null, "e": 13448, "s": 13374, "text": "Don’t force yourself to understand the thing. Let’s just change our model" }, { "code": null, "e": 13788, "s": 13448, "text": "model = Sequential()model.add(BatchNormalization(momentum=0.98,input_shape=(10, 128)))model.add(Bidirectional(CuDNNGRU(128, return_sequences = True)))model.add(Attention(10))model.add(Dense(1,activation='sigmoid'))model.compile(loss='binary_crossentropy', optimizer = optimizers.Nadam(lr=0.001), metrics=['accuracy'])print(model.summary())" }, { "code": null, "e": 13846, "s": 13788, "text": "Change the flatten layer into attention. And you will see" }, { "code": null, "e": 14698, "s": 13846, "text": "_________________________________________________________________Layer (type) Output Shape Param # =================================================================batch_normalization_6 (Batch (None, 10, 128) 512 _________________________________________________________________bidirectional_6 (Bidirection (None, 10, 256) 198144 _________________________________________________________________attention_2 (Attention) (None, 256) 266 _________________________________________________________________dense_6 (Dense) (None, 1) 257 =================================================================Total params: 199,179Trainable params: 198,923Non-trainable params: 256_________________________________________________________________" }, { "code": null, "e": 14790, "s": 14698, "text": "It reduces around 2,000 trainable params. Well, that’s a good thing. Let’s try the training" }, { "code": null, "e": 15018, "s": 14790, "text": "early_stop = EarlyStopping(monitor='val_loss', verbose=1, patience=20, restore_best_weights=True)model.fit(x_train, y_train,batch_size=512, epochs=16,validation_data=[x_val, y_val],verbose = 2,callbacks=[reduce_lr,early_stop])" }, { "code": null, "e": 15031, "s": 15018, "text": "Now you get:" }, { "code": null, "e": 15114, "s": 15031, "text": "Epoch 16/16 - 0s - loss: 0.1037 - acc: 0.9710 - val_loss: 0.1680 - val_acc: 0.9331" }, { "code": null, "e": 15146, "s": 15114, "text": "Yeah! A 1% increase into 93.31%" }, { "code": null, "e": 15184, "s": 15146, "text": "Not much, but definitely an increase!" }, { "code": null, "e": 15269, "s": 15184, "text": "It is amazingly easy to get started to create a Deep Learning system for audio data." }, { "code": null, "e": 15343, "s": 15269, "text": "You just need to know-how. And get good to create the real “Ok, Google!”." } ]
5 Must-Know Pandas Operations on Strings | by Soner Yıldırım | Towards Data Science
We have to represent every bit of data in numerical values to be processed and analyzed by machine learning and deep learning models. However, strings do not usually come in a nice and clean format and require preprocessing to convert to numerical values. Pandas offers many versatile functions to modify and process string data efficiently. In this post, we will discover how Pandas can manipulate strings. I grouped string functions and methods under 5 categories: SplittingStrippingReplacingFilteringCombining Splitting Stripping Replacing Filtering Combining Let’s first create a sample dataframe to work on for examples. import numpy as npimport pandas as pdsample = {'col_a':['Houston,TX', 'Dallas,TX', 'Chicago,IL', 'Phoenix,AZ', 'San Diego,CA'],'col_b':['$64K-$72K', '$62K-$70K', '$69K-$76K', '$62K-$72K', '$71K-$78K' ],'col_c':['A','B','A','a','c'],'col_d':[' 1x', ' 1y', '2x ', '1x', '1y ']}df_sample = pd.DataFrame(sample)df_sample Sometimes strings carry more than one piece of information and we may need to use them separately. For instance, “col_a” contains both city and state. The split function of pandas is a highly flexible function to split strings. df_sample['col_a'].str.split(',')0 [Houston, TX] 1 [Dallas, TX] 2 [Chicago, IL] 3 [Phoenix, AZ] 4 [San Diego, CA] Name: col_a, dtype: object Now each element is converted to a list based on the character used for splitting. We can easily export individual elements from those lists. Let’s create a “state” column. df_sample['state'] = df_sample['col_a'].str.split(',').str[1]df_sample Warning: Subscript ([1]) must be applied with str keyword. Otherwise, we will get the list in the specified row. df_sample['col_a'].str.split(',')[1]['Dallas', 'TX'] The splitting can be done on any character or letter. The split function returns a dataframe if expand parameter is set as True. df_sample['col_a'].str.split('a', expand=True) By default, splitting is done from the left. To do splitting on the right, use rsplit. Consider the series below: Let’s apply split function and limit the number of splits with n parameter: categories.str.split('-', expand=True, n=2) Only 2 splits on the left are performed. If we do the same operation with rsplit: categories.str.rsplit('-', expand=True, n=2) Same operation is done but on the right. Stripping is like trimming tree branches. We can remove spaces or any other characters at the beginning or end of a string. For instance, the strings in “col_b” has $ character at the beginning which can be removed with lstrip: df_sample['col_b'].str.lstrip('$')0 64K-$72K 1 62K-$70K 2 69K-$76K 3 62K-$72K 4 71K-$78K Name: col_b, dtype: object Similary, rstrip is used to trim off characters from the end. Strings may have spaces at the beginning or end. Consider “col_d” in our dataframe. Those leading and trailing spaces can be removed with strip: df_sample['col_d'] = df_sample['col_d'].str.strip() Pandas replace function is used to replace values in rows or columns. Similarly, replace as a string operation is used to replace characters in a string. Let’s replace “x” letters in “col_d” with “z”. df_sample['col_d'] = df_sample['col_d'].str.replace('x', 'z') We can filter strings based on the first and last characters. The functions to use are startswith() and endswith(). Here is our original dataframe: Here is a filtered version that only includes rows in which “col_a” ends with the letter “x”. df_sample[df_sample['col_a'].str.endswith('X')] Or, rows in which “col_b” starts with “$6”: df_sample[df_sample['col_b'].str.startswith('$6')] We can also filter strings by extracting certain characters. For instace, we can get the first 2 character of strings in a column or series by str[:2]. “col_b” represents a value range but numerical values are hidden in a string. Let’s extract them with string subscripts: lower = df_sample['col_b'].str[1:3] upper = df_sample['col_b'].str[-3:-1] Cat function can be used to concatenate strings. We need pass an argument to put between concatenated strings using sep parameter. By default, cat ignores missing values but we can also specify how to handle them using na_rep parameter. Let’s create a new column by concatenating “col_c” and “col_d” with “-” separator. df_sample['new']=df_sample['col_c'].str.cat(df_sample['col_d'], sep='-')df_sample Before pandas 1.0, only “object” datatype was used to store strings which cause some drawbacks because non-string data can also be stored using “object” datatype. Pandas 1.0 introduces a new datatype specific to string data which is StringDtype. As of now, we can still use object or StringDtype to store strings but in the future, we may be required to only use StringDtype. One important thing to note here is that object datatype is still the default datatype for strings. To use StringDtype, we need to explicitly state it. We can pass “string” or pd.StringDtype() argument to dtype parameter to string datatype. Thank you for reading. Please let me know if you have any feedback.
[ { "code": null, "e": 514, "s": 172, "text": "We have to represent every bit of data in numerical values to be processed and analyzed by machine learning and deep learning models. However, strings do not usually come in a nice and clean format and require preprocessing to convert to numerical values. Pandas offers many versatile functions to modify and process string data efficiently." }, { "code": null, "e": 639, "s": 514, "text": "In this post, we will discover how Pandas can manipulate strings. I grouped string functions and methods under 5 categories:" }, { "code": null, "e": 685, "s": 639, "text": "SplittingStrippingReplacingFilteringCombining" }, { "code": null, "e": 695, "s": 685, "text": "Splitting" }, { "code": null, "e": 705, "s": 695, "text": "Stripping" }, { "code": null, "e": 715, "s": 705, "text": "Replacing" }, { "code": null, "e": 725, "s": 715, "text": "Filtering" }, { "code": null, "e": 735, "s": 725, "text": "Combining" }, { "code": null, "e": 798, "s": 735, "text": "Let’s first create a sample dataframe to work on for examples." }, { "code": null, "e": 1123, "s": 798, "text": "import numpy as npimport pandas as pdsample = {'col_a':['Houston,TX', 'Dallas,TX', 'Chicago,IL', 'Phoenix,AZ', 'San Diego,CA'],'col_b':['$64K-$72K', '$62K-$70K', '$69K-$76K', '$62K-$72K', '$71K-$78K' ],'col_c':['A','B','A','a','c'],'col_d':[' 1x', ' 1y', '2x ', '1x', '1y ']}df_sample = pd.DataFrame(sample)df_sample" }, { "code": null, "e": 1351, "s": 1123, "text": "Sometimes strings carry more than one piece of information and we may need to use them separately. For instance, “col_a” contains both city and state. The split function of pandas is a highly flexible function to split strings." }, { "code": null, "e": 1516, "s": 1351, "text": "df_sample['col_a'].str.split(',')0 [Houston, TX] 1 [Dallas, TX] 2 [Chicago, IL] 3 [Phoenix, AZ] 4 [San Diego, CA] Name: col_a, dtype: object" }, { "code": null, "e": 1689, "s": 1516, "text": "Now each element is converted to a list based on the character used for splitting. We can easily export individual elements from those lists. Let’s create a “state” column." }, { "code": null, "e": 1760, "s": 1689, "text": "df_sample['state'] = df_sample['col_a'].str.split(',').str[1]df_sample" }, { "code": null, "e": 1873, "s": 1760, "text": "Warning: Subscript ([1]) must be applied with str keyword. Otherwise, we will get the list in the specified row." }, { "code": null, "e": 1926, "s": 1873, "text": "df_sample['col_a'].str.split(',')[1]['Dallas', 'TX']" }, { "code": null, "e": 1980, "s": 1926, "text": "The splitting can be done on any character or letter." }, { "code": null, "e": 2055, "s": 1980, "text": "The split function returns a dataframe if expand parameter is set as True." }, { "code": null, "e": 2102, "s": 2055, "text": "df_sample['col_a'].str.split('a', expand=True)" }, { "code": null, "e": 2189, "s": 2102, "text": "By default, splitting is done from the left. To do splitting on the right, use rsplit." }, { "code": null, "e": 2216, "s": 2189, "text": "Consider the series below:" }, { "code": null, "e": 2292, "s": 2216, "text": "Let’s apply split function and limit the number of splits with n parameter:" }, { "code": null, "e": 2336, "s": 2292, "text": "categories.str.split('-', expand=True, n=2)" }, { "code": null, "e": 2418, "s": 2336, "text": "Only 2 splits on the left are performed. If we do the same operation with rsplit:" }, { "code": null, "e": 2463, "s": 2418, "text": "categories.str.rsplit('-', expand=True, n=2)" }, { "code": null, "e": 2504, "s": 2463, "text": "Same operation is done but on the right." }, { "code": null, "e": 2628, "s": 2504, "text": "Stripping is like trimming tree branches. We can remove spaces or any other characters at the beginning or end of a string." }, { "code": null, "e": 2732, "s": 2628, "text": "For instance, the strings in “col_b” has $ character at the beginning which can be removed with lstrip:" }, { "code": null, "e": 2863, "s": 2732, "text": "df_sample['col_b'].str.lstrip('$')0 64K-$72K 1 62K-$70K 2 69K-$76K 3 62K-$72K 4 71K-$78K Name: col_b, dtype: object" }, { "code": null, "e": 2925, "s": 2863, "text": "Similary, rstrip is used to trim off characters from the end." }, { "code": null, "e": 3009, "s": 2925, "text": "Strings may have spaces at the beginning or end. Consider “col_d” in our dataframe." }, { "code": null, "e": 3070, "s": 3009, "text": "Those leading and trailing spaces can be removed with strip:" }, { "code": null, "e": 3122, "s": 3070, "text": "df_sample['col_d'] = df_sample['col_d'].str.strip()" }, { "code": null, "e": 3276, "s": 3122, "text": "Pandas replace function is used to replace values in rows or columns. Similarly, replace as a string operation is used to replace characters in a string." }, { "code": null, "e": 3323, "s": 3276, "text": "Let’s replace “x” letters in “col_d” with “z”." }, { "code": null, "e": 3385, "s": 3323, "text": "df_sample['col_d'] = df_sample['col_d'].str.replace('x', 'z')" }, { "code": null, "e": 3501, "s": 3385, "text": "We can filter strings based on the first and last characters. The functions to use are startswith() and endswith()." }, { "code": null, "e": 3533, "s": 3501, "text": "Here is our original dataframe:" }, { "code": null, "e": 3627, "s": 3533, "text": "Here is a filtered version that only includes rows in which “col_a” ends with the letter “x”." }, { "code": null, "e": 3675, "s": 3627, "text": "df_sample[df_sample['col_a'].str.endswith('X')]" }, { "code": null, "e": 3719, "s": 3675, "text": "Or, rows in which “col_b” starts with “$6”:" }, { "code": null, "e": 3770, "s": 3719, "text": "df_sample[df_sample['col_b'].str.startswith('$6')]" }, { "code": null, "e": 3922, "s": 3770, "text": "We can also filter strings by extracting certain characters. For instace, we can get the first 2 character of strings in a column or series by str[:2]." }, { "code": null, "e": 4043, "s": 3922, "text": "“col_b” represents a value range but numerical values are hidden in a string. Let’s extract them with string subscripts:" }, { "code": null, "e": 4080, "s": 4043, "text": "lower = df_sample['col_b'].str[1:3]" }, { "code": null, "e": 4119, "s": 4080, "text": "upper = df_sample['col_b'].str[-3:-1]" }, { "code": null, "e": 4168, "s": 4119, "text": "Cat function can be used to concatenate strings." }, { "code": null, "e": 4356, "s": 4168, "text": "We need pass an argument to put between concatenated strings using sep parameter. By default, cat ignores missing values but we can also specify how to handle them using na_rep parameter." }, { "code": null, "e": 4439, "s": 4356, "text": "Let’s create a new column by concatenating “col_c” and “col_d” with “-” separator." }, { "code": null, "e": 4521, "s": 4439, "text": "df_sample['new']=df_sample['col_c'].str.cat(df_sample['col_d'], sep='-')df_sample" }, { "code": null, "e": 4897, "s": 4521, "text": "Before pandas 1.0, only “object” datatype was used to store strings which cause some drawbacks because non-string data can also be stored using “object” datatype. Pandas 1.0 introduces a new datatype specific to string data which is StringDtype. As of now, we can still use object or StringDtype to store strings but in the future, we may be required to only use StringDtype." }, { "code": null, "e": 5049, "s": 4897, "text": "One important thing to note here is that object datatype is still the default datatype for strings. To use StringDtype, we need to explicitly state it." }, { "code": null, "e": 5138, "s": 5049, "text": "We can pass “string” or pd.StringDtype() argument to dtype parameter to string datatype." } ]
Create an option group in HTML
The HTML <optgroup> tag is used for grouping related options within your select list. This makes it easier for users to comprehend their choices when looking at a large list. The following are the attributes − You can try to run the following code to create an option group in HTML − <!DOCTYPE html> <html> <head> <title>HTML optgroup Tag</title> </head> <body> <select> <optgroup label = "India"> <option value = "mumbai">Mumbai</option> <option value = "delhi">Delhi</option> </optgroup> <optgroup label = "USA"> <option value = "florida">Florida</option> <option value = "newyork">New York</option> </optgroup> </select> </body> </html>
[ { "code": null, "e": 1237, "s": 1062, "text": "The HTML <optgroup> tag is used for grouping related options within your select list. This makes it easier for users to comprehend their choices when looking at a large list." }, { "code": null, "e": 1272, "s": 1237, "text": "The following are the attributes −" }, { "code": null, "e": 1346, "s": 1272, "text": "You can try to run the following code to create an option group in HTML −" }, { "code": null, "e": 1816, "s": 1346, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>HTML optgroup Tag</title>\n </head>\n <body>\n <select>\n <optgroup label = \"India\">\n <option value = \"mumbai\">Mumbai</option>\n <option value = \"delhi\">Delhi</option>\n </optgroup>\n <optgroup label = \"USA\">\n <option value = \"florida\">Florida</option>\n <option value = \"newyork\">New York</option>\n </optgroup>\n </select>\n </body>\n</html>" } ]
C++ String Library - assign
It appends character c to the end of the string, increasing its length by one. Following is the declaration for std::string::assign. string& assign (const string& str); string& assign (const string& str); string& assign (const string& str); c − It is a character object. c − It is a character object. str − It is a string object. str − It is a string object. It returns *this. if an exception is thrown, there are no changes in the string. In below example for std::string::assign. #include <iostream> #include <string> int main () { std::string str; std::string base="Sairamkrishna is a one of the tech person in tutorialspoint."; str.assign(base); std::cout << str << '\n'; str.assign(base,10,9); std::cout << str << '\n'; str.assign("pangrams are cool",7); std::cout << str << '\n'; str.assign("c-string"); std::cout << str << '\n'; str.assign(10,'*'); std::cout << str << '\n'; str.assign<int>(10,0x2D); std::cout << str << '\n'; str.assign(base.begin()+16,base.end()-12); std::cout << str << '\n'; return 0; } The sample output should be like this − Sairamkrishna is a one of the tech person in tutorialspoint. hna is a pangram c-string ********** ---------- a one of the tech person in tut Print Add Notes Bookmark this page
[ { "code": null, "e": 2682, "s": 2603, "text": "It appends character c to the end of the string, increasing its length by one." }, { "code": null, "e": 2736, "s": 2682, "text": "Following is the declaration for std::string::assign." }, { "code": null, "e": 2772, "s": 2736, "text": "string& assign (const string& str);" }, { "code": null, "e": 2808, "s": 2772, "text": "string& assign (const string& str);" }, { "code": null, "e": 2844, "s": 2808, "text": "string& assign (const string& str);" }, { "code": null, "e": 2874, "s": 2844, "text": "c − It is a character object." }, { "code": null, "e": 2904, "s": 2874, "text": "c − It is a character object." }, { "code": null, "e": 2933, "s": 2904, "text": "str − It is a string object." }, { "code": null, "e": 2962, "s": 2933, "text": "str − It is a string object." }, { "code": null, "e": 2980, "s": 2962, "text": "It returns *this." }, { "code": null, "e": 3043, "s": 2980, "text": "if an exception is thrown, there are no changes in the string." }, { "code": null, "e": 3085, "s": 3043, "text": "In below example for std::string::assign." }, { "code": null, "e": 3678, "s": 3085, "text": "#include <iostream>\n#include <string>\n\nint main () {\n std::string str;\n std::string base=\"Sairamkrishna is a one of the tech person in tutorialspoint.\";\n\n str.assign(base);\n std::cout << str << '\\n';\n\n str.assign(base,10,9);\n std::cout << str << '\\n';\n\n str.assign(\"pangrams are cool\",7);\n std::cout << str << '\\n';\n\n str.assign(\"c-string\");\n std::cout << str << '\\n';\n\n str.assign(10,'*');\n std::cout << str << '\\n';\n\n str.assign<int>(10,0x2D);\n std::cout << str << '\\n';\n\n str.assign(base.begin()+16,base.end()-12);\n std::cout << str << '\\n';\n\n return 0;\n}" }, { "code": null, "e": 3718, "s": 3678, "text": "The sample output should be like this −" }, { "code": null, "e": 3862, "s": 3718, "text": "Sairamkrishna is a one of the tech person in tutorialspoint.\nhna is a \npangram\nc-string\n**********\n----------\n a one of the tech person in tut\n" }, { "code": null, "e": 3869, "s": 3862, "text": " Print" }, { "code": null, "e": 3880, "s": 3869, "text": " Add Notes" } ]
A Series on Flask APIs, Part 1: GETting and POSTing | by Alexis McKenzie | Towards Data Science
This article is part of a series on Flask APIs. This part addresses creating a basic REST API using a JSON doc and running that API locally. Each subsequent part will incorporate new technologies to help you better understand APIs and DevOps in the cloud. The Basics: What is Flask, What are APIs, What is a REST API? Flask is a Python microframework commonly used for creating APIs, or Application Programming Interfaces. APIs let you interact with applications. Even modules in Python are a type of API, for this reason: They let you interact with external code in your application. APIs act as a sort of contract between the server and you. As such, have clear documentation for the call formatting and the type of response that is expected. Flask is a microframework, in contrast to a full-stack framework, that facilitates receiving HTTP requests, processing those requests in a controller, and returning an HTTP response. You can use Flask as a component in a full stack project with Angular or React, but we probably won’t be going into that in this series. Microframeworks typically lack authentication, form validation and database abstraction layers on their own, but those can be built in using other components. “REST” applies architectural constraints to an API. REST stands for Representational State Transfer and means that when a call is made, a representation of the state is also transferred with that call. These include GET, POST, PUT and DELETE as our verbs, and their usage results in a representation of the server’s data being returned. There are five critical components for your API to be “RESTful”: A uniform interface that standardizes the request format via our verbs and has logical and patterned URI routes to interact with the APIClient-server separation that allows for the client and server to evolve separately and communicate only via the request URIA stateless request so that each request is self-contained and need not create a server session and the server need not maintain data about past requestsCacheable response data on the server side to improve scalability and client-side performanceAnd finally, a layered system architecture to allow for multiple layers in the application (for authentication typically) and for the client and server to be unaware of which layer they are communicating with A uniform interface that standardizes the request format via our verbs and has logical and patterned URI routes to interact with the API Client-server separation that allows for the client and server to evolve separately and communicate only via the request URI A stateless request so that each request is self-contained and need not create a server session and the server need not maintain data about past requests Cacheable response data on the server side to improve scalability and client-side performance And finally, a layered system architecture to allow for multiple layers in the application (for authentication typically) and for the client and server to be unaware of which layer they are communicating with An optional sixth constraint for code on demand allows the server to respond with code instead of a representation of the data in JSON or XML format. If we miss any of the key components, our API is simply REST-like. For more information on RESTful APIs, check out the Roy Fielding dissertation. Prerequisites: You must have python and Flask installed. Create a local folder for your flask API and open up said folder in VS Code. You may also want to put this in a git repo from the beginning. It will make the subsequent parts of this series easier.Create two folders and a py file as below. Name the folders static and templates. Flask is specifically looking for folders with these names, so a functional approach to folder structures will save you headaches in the future. Create a local folder for your flask API and open up said folder in VS Code. You may also want to put this in a git repo from the beginning. It will make the subsequent parts of this series easier. Create two folders and a py file as below. Name the folders static and templates. Flask is specifically looking for folders with these names, so a functional approach to folder structures will save you headaches in the future. 3. Open up the demo_api.py file and write the following code: It is critical you have the shebang on Line 1. The shebang is an interpreter directive that tells the program loader that this file should be interpreted as a Python file, and /usr/bin/env represents the logical path for where Python is installed. Excluding the shebang will likely not cause problems now, but it will when you try to run this in the cloud. The route decorator on Line 9 is a feature of Flask that lets us easily create endpoints for our API. In general, a decorator lets us extend the behavior of a function. The render_template function on Line 14 takes the text variable on Line 11 and renders it in the index.html file. 4*. Next, create a file called index.html in the templates folder with the below code: <!DOCTYPE html><html lang="en"><head><title>Flask Demo</title></head><body>{{html_page_text}}</body></html> The double curly braces house the variable referenced in the render_template function in the Python file. If you need more info on html, check out W3Schools. *You do not need to create an html file, and the code snippets will tell you how to complete this API with or without. 5. Open up a terminal/command prompt and cd into the directory with your demo_api.py file. Next, type: $ export FLASK_APP=demo_api$ flask run You should see the following output in you terminal/command prompt: 6. Go to https://127.0.0.1:5000 . This is the localhost on port 5000. Localhost, or 127.0.0.1, is a reference to your home computer. No websites can have an IP address that starts with 127 since those IPs are reserved for loopbacks, which let you interact with your computer’s simulation of a webserver. We are able to test applications in localhost because the computer simulates a webserver when a loopback is triggered. In this section, we’re going to expand the functionality of the API to show how to GET and POST data to a file. Let’s imagine a business scenario where we’re logging and retrieving yearly events. Let’s say we have three objectives: We want to go to /all and see all the events for all time, we want to go to /year/<year> and see events for that particular year, and we want to add events in case some important ones are missing. Any time you have a route with an unspecified method, Flask assumes the method is GET (that the client is requesting data from the server). You will need to create a file with data in it. First, create a folder called data and create a file within that called data.json . Paste the following into data.json: {"events":[{ "year":"2020","id":1,"event_category":"pandemic","event":"covid"},{ "year":"2020","id":2,"event_category":"environmental","event":"west coast wildfires"},{ "year":"2021","id":1,"event_category":"sports","event":"summer olympics"}]} Let’s start with adding an /all route . We need to create another route and function in our demo_api.py file that reads from the data.json file: The json_url variable on Line 18 is referencing the path where the data is located. We then use json.loads to open the file and render it inside the index.html page. Note that we can pass all sorts of different data into one template as long as we pay attention to the variables. Make sure this works as expected for you before progressing. Now, we are going to work on the /year/<year> route. Check out this video for some thoughts around endpoint naming. First, create a file in templates called events.html. We can no longer use the index.html file because we have multiple items in our events list in the data file. Paste the following code into events.html: <!DOCTYPE html><html lang="en"><head><title>Flask Demo</title></head><body>{% for item in html_page_text %}<p>{{ item}}</p>{% endfor %}</body></html> Next, we need to create a new route to get data by year. The full code should look like below: Notice on Line 24 I included methods =[‘GET’] even though we didn’t do that for any other routes in the past. If a route is only getting data, you do not need to specify the methods, but we will be expanding the methods shortly. Line 31 is making sure we access the data inside the events key in the data.json file. Line 32 gets the data passed into the route and converts it to a variable. We then iterate through all the data in that list to get the data for the year of interest using a list comprehension on Line 33. Now you can pass any year into the path and the data in data.json will be filtered to only show events for that year. The for-loop in the events.html is critical to display all events for years with multiple events listed. If you use index.html on Line 36 instead you will see that only one event for each year is returned. If you go to http://127.0.0.1:5000/year/2020 in your browser, you should see the following results: Now we are going to handle adding new events to the data.json file. Create another html file under the templates folder called form.html. In order to POST, we need some type of form to send data (or we could also use Postman and pass data in parameters, but more on that later). Paste the following into form.html: <!DOCTYPE html><html lang="en"><head><title>Flask Demo</title></head><body><form action="#" method="post" ><p>Yearly Events:</p><table><tbody><tr><td>Category:</td><td><input type="text" name="category" /></td></tr><tr><td>Event:</td><td><input type="text" name="event" /></td></tr></tbody></table><p><input type="submit" value="submit"/></p></form></body></html> First, we need to render this form in our application. Adding the /add route as below will let us do that. Everything in the /add route that starts on Line 25 should be familiar to you except the send_file function. This lets us send the contents in the form to a client. However, at this point, without anything to receive and process POSTs, you will get an internal server error. We now need to write some logic to get the POSTed data from the form. There are several ways to do this, but I will show you one approach. Feel free to include other approaches in the comments below. We need to specify that this accepts the POST method on Line 1. If not, none of the code will work. Lines 15 through 20 pull the data out of the form that’s posted. The code is referencing those elements by the names specified in the form.html attributes. Lines 21 through 25 put that data into a dictionary so all the data is retrieved from one form submittal is together. Lines 27 through 30 are a bit more complex based on how the data file is formatted, but I will walk you through my thought process based on how the data is structured. There is great documentation for Python built-in functions like open, but I chose r+ as the mode to make sure the file could be read and updated. First, we need to get the json changes to work as we envisioned. Initially, I thought, OK, I need to load the data currently in the file, append the new data to the end of the events list, and then overwrite the original file. If you attempt to add another value, you will notice this doesn’t exactly work...the new dictionary gets added to the end of the old dictionary: So we need to start at the beginning of the file instead of appending to the end. That’s where the seek function comes in. This points us to the beginning of the file instead of the end (where the data was previously getting appended) Now you have a basic API that can GET and POST data from a form to a document! Notes/Troubleshooting: If you run the above code, you may notice that the first line gets overwritten. If your original data.json had some indents, this may be problematic. Here is where a useful argument in json.dump comes in handy. Indent! You can use any level of indentation from 0 up, but you will need to play around with it depending on how the data.json file was indented. Some other approaches: You can use additional modes in the built-in open function to first read and then overwrite the file. If you have additional suggestions or comments, please post in the comments section. Thanks for reading!
[ { "code": null, "e": 428, "s": 172, "text": "This article is part of a series on Flask APIs. This part addresses creating a basic REST API using a JSON doc and running that API locally. Each subsequent part will incorporate new technologies to help you better understand APIs and DevOps in the cloud." }, { "code": null, "e": 490, "s": 428, "text": "The Basics: What is Flask, What are APIs, What is a REST API?" }, { "code": null, "e": 917, "s": 490, "text": "Flask is a Python microframework commonly used for creating APIs, or Application Programming Interfaces. APIs let you interact with applications. Even modules in Python are a type of API, for this reason: They let you interact with external code in your application. APIs act as a sort of contract between the server and you. As such, have clear documentation for the call formatting and the type of response that is expected." }, { "code": null, "e": 1396, "s": 917, "text": "Flask is a microframework, in contrast to a full-stack framework, that facilitates receiving HTTP requests, processing those requests in a controller, and returning an HTTP response. You can use Flask as a component in a full stack project with Angular or React, but we probably won’t be going into that in this series. Microframeworks typically lack authentication, form validation and database abstraction layers on their own, but those can be built in using other components." }, { "code": null, "e": 1798, "s": 1396, "text": "“REST” applies architectural constraints to an API. REST stands for Representational State Transfer and means that when a call is made, a representation of the state is also transferred with that call. These include GET, POST, PUT and DELETE as our verbs, and their usage results in a representation of the server’s data being returned. There are five critical components for your API to be “RESTful”:" }, { "code": null, "e": 2513, "s": 1798, "text": "A uniform interface that standardizes the request format via our verbs and has logical and patterned URI routes to interact with the APIClient-server separation that allows for the client and server to evolve separately and communicate only via the request URIA stateless request so that each request is self-contained and need not create a server session and the server need not maintain data about past requestsCacheable response data on the server side to improve scalability and client-side performanceAnd finally, a layered system architecture to allow for multiple layers in the application (for authentication typically) and for the client and server to be unaware of which layer they are communicating with" }, { "code": null, "e": 2650, "s": 2513, "text": "A uniform interface that standardizes the request format via our verbs and has logical and patterned URI routes to interact with the API" }, { "code": null, "e": 2775, "s": 2650, "text": "Client-server separation that allows for the client and server to evolve separately and communicate only via the request URI" }, { "code": null, "e": 2929, "s": 2775, "text": "A stateless request so that each request is self-contained and need not create a server session and the server need not maintain data about past requests" }, { "code": null, "e": 3023, "s": 2929, "text": "Cacheable response data on the server side to improve scalability and client-side performance" }, { "code": null, "e": 3232, "s": 3023, "text": "And finally, a layered system architecture to allow for multiple layers in the application (for authentication typically) and for the client and server to be unaware of which layer they are communicating with" }, { "code": null, "e": 3382, "s": 3232, "text": "An optional sixth constraint for code on demand allows the server to respond with code instead of a representation of the data in JSON or XML format." }, { "code": null, "e": 3528, "s": 3382, "text": "If we miss any of the key components, our API is simply REST-like. For more information on RESTful APIs, check out the Roy Fielding dissertation." }, { "code": null, "e": 3585, "s": 3528, "text": "Prerequisites: You must have python and Flask installed." }, { "code": null, "e": 4009, "s": 3585, "text": "Create a local folder for your flask API and open up said folder in VS Code. You may also want to put this in a git repo from the beginning. It will make the subsequent parts of this series easier.Create two folders and a py file as below. Name the folders static and templates. Flask is specifically looking for folders with these names, so a functional approach to folder structures will save you headaches in the future." }, { "code": null, "e": 4207, "s": 4009, "text": "Create a local folder for your flask API and open up said folder in VS Code. You may also want to put this in a git repo from the beginning. It will make the subsequent parts of this series easier." }, { "code": null, "e": 4434, "s": 4207, "text": "Create two folders and a py file as below. Name the folders static and templates. Flask is specifically looking for folders with these names, so a functional approach to folder structures will save you headaches in the future." }, { "code": null, "e": 4496, "s": 4434, "text": "3. Open up the demo_api.py file and write the following code:" }, { "code": null, "e": 4853, "s": 4496, "text": "It is critical you have the shebang on Line 1. The shebang is an interpreter directive that tells the program loader that this file should be interpreted as a Python file, and /usr/bin/env represents the logical path for where Python is installed. Excluding the shebang will likely not cause problems now, but it will when you try to run this in the cloud." }, { "code": null, "e": 5022, "s": 4853, "text": "The route decorator on Line 9 is a feature of Flask that lets us easily create endpoints for our API. In general, a decorator lets us extend the behavior of a function." }, { "code": null, "e": 5136, "s": 5022, "text": "The render_template function on Line 14 takes the text variable on Line 11 and renders it in the index.html file." }, { "code": null, "e": 5223, "s": 5136, "text": "4*. Next, create a file called index.html in the templates folder with the below code:" }, { "code": null, "e": 5331, "s": 5223, "text": "<!DOCTYPE html><html lang=\"en\"><head><title>Flask Demo</title></head><body>{{html_page_text}}</body></html>" }, { "code": null, "e": 5437, "s": 5331, "text": "The double curly braces house the variable referenced in the render_template function in the Python file." }, { "code": null, "e": 5489, "s": 5437, "text": "If you need more info on html, check out W3Schools." }, { "code": null, "e": 5608, "s": 5489, "text": "*You do not need to create an html file, and the code snippets will tell you how to complete this API with or without." }, { "code": null, "e": 5711, "s": 5608, "text": "5. Open up a terminal/command prompt and cd into the directory with your demo_api.py file. Next, type:" }, { "code": null, "e": 5750, "s": 5711, "text": "$ export FLASK_APP=demo_api$ flask run" }, { "code": null, "e": 5818, "s": 5750, "text": "You should see the following output in you terminal/command prompt:" }, { "code": null, "e": 5888, "s": 5818, "text": "6. Go to https://127.0.0.1:5000 . This is the localhost on port 5000." }, { "code": null, "e": 6241, "s": 5888, "text": "Localhost, or 127.0.0.1, is a reference to your home computer. No websites can have an IP address that starts with 127 since those IPs are reserved for loopbacks, which let you interact with your computer’s simulation of a webserver. We are able to test applications in localhost because the computer simulates a webserver when a loopback is triggered." }, { "code": null, "e": 6670, "s": 6241, "text": "In this section, we’re going to expand the functionality of the API to show how to GET and POST data to a file. Let’s imagine a business scenario where we’re logging and retrieving yearly events. Let’s say we have three objectives: We want to go to /all and see all the events for all time, we want to go to /year/<year> and see events for that particular year, and we want to add events in case some important ones are missing." }, { "code": null, "e": 6810, "s": 6670, "text": "Any time you have a route with an unspecified method, Flask assumes the method is GET (that the client is requesting data from the server)." }, { "code": null, "e": 6978, "s": 6810, "text": "You will need to create a file with data in it. First, create a folder called data and create a file within that called data.json . Paste the following into data.json:" }, { "code": null, "e": 7223, "s": 6978, "text": "{\"events\":[{ \"year\":\"2020\",\"id\":1,\"event_category\":\"pandemic\",\"event\":\"covid\"},{ \"year\":\"2020\",\"id\":2,\"event_category\":\"environmental\",\"event\":\"west coast wildfires\"},{ \"year\":\"2021\",\"id\":1,\"event_category\":\"sports\",\"event\":\"summer olympics\"}]}" }, { "code": null, "e": 7368, "s": 7223, "text": "Let’s start with adding an /all route . We need to create another route and function in our demo_api.py file that reads from the data.json file:" }, { "code": null, "e": 7648, "s": 7368, "text": "The json_url variable on Line 18 is referencing the path where the data is located. We then use json.loads to open the file and render it inside the index.html page. Note that we can pass all sorts of different data into one template as long as we pay attention to the variables." }, { "code": null, "e": 7709, "s": 7648, "text": "Make sure this works as expected for you before progressing." }, { "code": null, "e": 8031, "s": 7709, "text": "Now, we are going to work on the /year/<year> route. Check out this video for some thoughts around endpoint naming. First, create a file in templates called events.html. We can no longer use the index.html file because we have multiple items in our events list in the data file. Paste the following code into events.html:" }, { "code": null, "e": 8181, "s": 8031, "text": "<!DOCTYPE html><html lang=\"en\"><head><title>Flask Demo</title></head><body>{% for item in html_page_text %}<p>{{ item}}</p>{% endfor %}</body></html>" }, { "code": null, "e": 8276, "s": 8181, "text": "Next, we need to create a new route to get data by year. The full code should look like below:" }, { "code": null, "e": 8505, "s": 8276, "text": "Notice on Line 24 I included methods =[‘GET’] even though we didn’t do that for any other routes in the past. If a route is only getting data, you do not need to specify the methods, but we will be expanding the methods shortly." }, { "code": null, "e": 8797, "s": 8505, "text": "Line 31 is making sure we access the data inside the events key in the data.json file. Line 32 gets the data passed into the route and converts it to a variable. We then iterate through all the data in that list to get the data for the year of interest using a list comprehension on Line 33." }, { "code": null, "e": 9121, "s": 8797, "text": "Now you can pass any year into the path and the data in data.json will be filtered to only show events for that year. The for-loop in the events.html is critical to display all events for years with multiple events listed. If you use index.html on Line 36 instead you will see that only one event for each year is returned." }, { "code": null, "e": 9221, "s": 9121, "text": "If you go to http://127.0.0.1:5000/year/2020 in your browser, you should see the following results:" }, { "code": null, "e": 9536, "s": 9221, "text": "Now we are going to handle adding new events to the data.json file. Create another html file under the templates folder called form.html. In order to POST, we need some type of form to send data (or we could also use Postman and pass data in parameters, but more on that later). Paste the following into form.html:" }, { "code": null, "e": 9900, "s": 9536, "text": "<!DOCTYPE html><html lang=\"en\"><head><title>Flask Demo</title></head><body><form action=\"#\" method=\"post\" ><p>Yearly Events:</p><table><tbody><tr><td>Category:</td><td><input type=\"text\" name=\"category\" /></td></tr><tr><td>Event:</td><td><input type=\"text\" name=\"event\" /></td></tr></tbody></table><p><input type=\"submit\" value=\"submit\"/></p></form></body></html>" }, { "code": null, "e": 10007, "s": 9900, "text": "First, we need to render this form in our application. Adding the /add route as below will let us do that." }, { "code": null, "e": 10282, "s": 10007, "text": "Everything in the /add route that starts on Line 25 should be familiar to you except the send_file function. This lets us send the contents in the form to a client. However, at this point, without anything to receive and process POSTs, you will get an internal server error." }, { "code": null, "e": 10482, "s": 10282, "text": "We now need to write some logic to get the POSTed data from the form. There are several ways to do this, but I will show you one approach. Feel free to include other approaches in the comments below." }, { "code": null, "e": 10582, "s": 10482, "text": "We need to specify that this accepts the POST method on Line 1. If not, none of the code will work." }, { "code": null, "e": 10856, "s": 10582, "text": "Lines 15 through 20 pull the data out of the form that’s posted. The code is referencing those elements by the names specified in the form.html attributes. Lines 21 through 25 put that data into a dictionary so all the data is retrieved from one form submittal is together." }, { "code": null, "e": 11170, "s": 10856, "text": "Lines 27 through 30 are a bit more complex based on how the data file is formatted, but I will walk you through my thought process based on how the data is structured. There is great documentation for Python built-in functions like open, but I chose r+ as the mode to make sure the file could be read and updated." }, { "code": null, "e": 11542, "s": 11170, "text": "First, we need to get the json changes to work as we envisioned. Initially, I thought, OK, I need to load the data currently in the file, append the new data to the end of the events list, and then overwrite the original file. If you attempt to add another value, you will notice this doesn’t exactly work...the new dictionary gets added to the end of the old dictionary:" }, { "code": null, "e": 11777, "s": 11542, "text": "So we need to start at the beginning of the file instead of appending to the end. That’s where the seek function comes in. This points us to the beginning of the file instead of the end (where the data was previously getting appended)" }, { "code": null, "e": 11856, "s": 11777, "text": "Now you have a basic API that can GET and POST data from a form to a document!" }, { "code": null, "e": 12098, "s": 11856, "text": "Notes/Troubleshooting: If you run the above code, you may notice that the first line gets overwritten. If your original data.json had some indents, this may be problematic. Here is where a useful argument in json.dump comes in handy. Indent!" }, { "code": null, "e": 12237, "s": 12098, "text": "You can use any level of indentation from 0 up, but you will need to play around with it depending on how the data.json file was indented." }, { "code": null, "e": 12447, "s": 12237, "text": "Some other approaches: You can use additional modes in the built-in open function to first read and then overwrite the file. If you have additional suggestions or comments, please post in the comments section." } ]
Dynamic RatingBar in Kotlin - GeeksforGeeks
28 Mar, 2022 Android RatingBar is a user interface widget which is used to get the rating from the customers or users. It is an extension of SeekBar and ProgressBar that shows star ratings and it allow users to give the rating by clicking on the stars. In RatingBar, we can set the step size using android:stepSize and it will always return a rating value as floating point number such as 1.0, 2.0, 2.5 etc. By using, android:numStars attribute we can specify the number of stars in RatingBar. RatingBar is used to get ratings form users or customers about the product, movie or hotel experience etc. RatingBar can be created manually or programmatically but we are going to discuss programmatically or dynamically. First we create a new project by following the below steps: Click on File, then New => New Project.After that include the Kotlin support and click on next.Select the minimum SDK as per convenience and click next button.Then select the Empty activity => next => finish. Click on File, then New => New Project. After that include the Kotlin support and click on next. Select the minimum SDK as per convenience and click next button. Then select the Empty activity => next => finish. In this file, we use the LinearLayout and set its attributes like id, padding etc and it can be accessed in the Kotlin file using id. XML <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/container" android:layout_width="wrap_content" android:layout_height="wrap_content" tools:context=".MainActivity" android:orientation="vertical" android:paddingLeft="35dp" android:paddingTop="50dp"> </LinearLayout> Add application name in strings.xml fileHere, we can put all the strings which can be used in the application in any file. So, we update the app_name which can be seen on the top of the activity. XML <resources> <string name="app_name">DynamicRatingBarInKotlin</string></resources> First of all, we declare variable rBar to create RatingBar and set its attributes using it. val rBar = RatingBar(this) val layoutParams = LinearLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) rBar.layoutParams = layoutParams rBar.stepSize = 1.0.toFloat() rBar.numStars = 5 then, we declare another variable to create a button like this val button = Button(this) val layoutParams1 = LinearLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) button.text="Submit Rating" After this, RatingBar and button added into the LinearLayout using the statements linearLayout?.addView(rBar) linearLayout?.addView(button) Kotlin package com.geeksforgeeks.myfirstkotlinapp import androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.view.ViewGroupimport android.widget.Buttonimport android.widget.LinearLayoutimport android.widget.RatingBarimport android.widget.Toast class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Create RatingBar val rBar = RatingBar(this) val layoutParams = LinearLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) rBar.layoutParams = layoutParams rBar.stepSize = 1.0.toFloat() rBar.numStars = 5 //create button val button = Button(this) val layoutParams1 = LinearLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) button.text="Submit Rating" val linearLayout = findViewById<LinearLayout>(R.id.container) // Add RatingBar and button to LinearLayout linearLayout?.addView(rBar) linearLayout?.addView(button) button?.setOnClickListener { val msg = rBar.rating.toString() Toast.makeText(this@MainActivity, "Given Rating: "+msg, Toast.LENGTH_SHORT).show() } }} XML <?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"package="com.geeksforgeeks.myfirstkotlinapp"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity></application> </manifest> ayushpandey3july Android-Bars Kotlin Android Android Kotlin Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Broadcast Receiver in Android With Example How to Create and Add Data to SQLite Database in Android? Services in Android with Example Content Providers in Android with Example Android RecyclerView in Kotlin Broadcast Receiver in Android With Example Content Providers in Android with Example Services in Android with Example Android UI Layouts Android RecyclerView in Kotlin
[ { "code": null, "e": 23922, "s": 23894, "text": "\n28 Mar, 2022" }, { "code": null, "e": 24162, "s": 23922, "text": "Android RatingBar is a user interface widget which is used to get the rating from the customers or users. It is an extension of SeekBar and ProgressBar that shows star ratings and it allow users to give the rating by clicking on the stars." }, { "code": null, "e": 24510, "s": 24162, "text": "In RatingBar, we can set the step size using android:stepSize and it will always return a rating value as floating point number such as 1.0, 2.0, 2.5 etc. By using, android:numStars attribute we can specify the number of stars in RatingBar. RatingBar is used to get ratings form users or customers about the product, movie or hotel experience etc." }, { "code": null, "e": 24625, "s": 24510, "text": "RatingBar can be created manually or programmatically but we are going to discuss programmatically or dynamically." }, { "code": null, "e": 24685, "s": 24625, "text": "First we create a new project by following the below steps:" }, { "code": null, "e": 24894, "s": 24685, "text": "Click on File, then New => New Project.After that include the Kotlin support and click on next.Select the minimum SDK as per convenience and click next button.Then select the Empty activity => next => finish." }, { "code": null, "e": 24934, "s": 24894, "text": "Click on File, then New => New Project." }, { "code": null, "e": 24991, "s": 24934, "text": "After that include the Kotlin support and click on next." }, { "code": null, "e": 25056, "s": 24991, "text": "Select the minimum SDK as per convenience and click next button." }, { "code": null, "e": 25106, "s": 25056, "text": "Then select the Empty activity => next => finish." }, { "code": null, "e": 25240, "s": 25106, "text": "In this file, we use the LinearLayout and set its attributes like id, padding etc and it can be accessed in the Kotlin file using id." }, { "code": null, "e": 25244, "s": 25240, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:id=\"@+id/container\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" tools:context=\".MainActivity\" android:orientation=\"vertical\" android:paddingLeft=\"35dp\" android:paddingTop=\"50dp\"> </LinearLayout>", "e": 25662, "s": 25244, "text": null }, { "code": null, "e": 25858, "s": 25662, "text": "Add application name in strings.xml fileHere, we can put all the strings which can be used in the application in any file. So, we update the app_name which can be seen on the top of the activity." }, { "code": null, "e": 25862, "s": 25858, "text": "XML" }, { "code": "<resources> <string name=\"app_name\">DynamicRatingBarInKotlin</string></resources>", "e": 25947, "s": 25862, "text": null }, { "code": null, "e": 26039, "s": 25947, "text": "First of all, we declare variable rBar to create RatingBar and set its attributes using it." }, { "code": null, "e": 26326, "s": 26039, "text": " \nval rBar = RatingBar(this)\n val layoutParams = LinearLayout.LayoutParams(\n ViewGroup.LayoutParams.MATCH_PARENT,\n ViewGroup.LayoutParams.WRAP_CONTENT)\n rBar.layoutParams = layoutParams\n rBar.stepSize = 1.0.toFloat()\n rBar.numStars = 5\n" }, { "code": null, "e": 26389, "s": 26326, "text": "then, we declare another variable to create a button like this" }, { "code": null, "e": 26605, "s": 26389, "text": "val button = Button(this)\n val layoutParams1 = LinearLayout.LayoutParams(\n ViewGroup.LayoutParams.MATCH_PARENT,\n ViewGroup.LayoutParams.WRAP_CONTENT)\n button.text=\"Submit Rating\"\n" }, { "code": null, "e": 26687, "s": 26605, "text": "After this, RatingBar and button added into the LinearLayout using the statements" }, { "code": null, "e": 26746, "s": 26687, "text": "linearLayout?.addView(rBar)\nlinearLayout?.addView(button)\n" }, { "code": null, "e": 26753, "s": 26746, "text": "Kotlin" }, { "code": "package com.geeksforgeeks.myfirstkotlinapp import androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.view.ViewGroupimport android.widget.Buttonimport android.widget.LinearLayoutimport android.widget.RatingBarimport android.widget.Toast class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Create RatingBar val rBar = RatingBar(this) val layoutParams = LinearLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) rBar.layoutParams = layoutParams rBar.stepSize = 1.0.toFloat() rBar.numStars = 5 //create button val button = Button(this) val layoutParams1 = LinearLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) button.text=\"Submit Rating\" val linearLayout = findViewById<LinearLayout>(R.id.container) // Add RatingBar and button to LinearLayout linearLayout?.addView(rBar) linearLayout?.addView(button) button?.setOnClickListener { val msg = rBar.rating.toString() Toast.makeText(this@MainActivity, \"Given Rating: \"+msg, Toast.LENGTH_SHORT).show() } }}", "e": 28167, "s": 26753, "text": null }, { "code": null, "e": 28171, "s": 28167, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"package=\"com.geeksforgeeks.myfirstkotlinapp\"> <application android:allowBackup=\"true\" android:icon=\"@mipmap/ic_launcher\" android:label=\"@string/app_name\" android:roundIcon=\"@mipmap/ic_launcher_round\" android:supportsRtl=\"true\" android:theme=\"@style/AppTheme\"> <activity android:name=\".MainActivity\"> <intent-filter> <action android:name=\"android.intent.action.MAIN\" /> <category android:name=\"android.intent.category.LAUNCHER\" /> </intent-filter> </activity></application> </manifest>", "e": 28826, "s": 28171, "text": null }, { "code": null, "e": 28845, "s": 28828, "text": "ayushpandey3july" }, { "code": null, "e": 28858, "s": 28845, "text": "Android-Bars" }, { "code": null, "e": 28873, "s": 28858, "text": "Kotlin Android" }, { "code": null, "e": 28881, "s": 28873, "text": "Android" }, { "code": null, "e": 28888, "s": 28881, "text": "Kotlin" }, { "code": null, "e": 28896, "s": 28888, "text": "Android" }, { "code": null, "e": 28994, "s": 28896, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29003, "s": 28994, "text": "Comments" }, { "code": null, "e": 29016, "s": 29003, "text": "Old Comments" }, { "code": null, "e": 29059, "s": 29016, "text": "Broadcast Receiver in Android With Example" }, { "code": null, "e": 29117, "s": 29059, "text": "How to Create and Add Data to SQLite Database in Android?" }, { "code": null, "e": 29150, "s": 29117, "text": "Services in Android with Example" }, { "code": null, "e": 29192, "s": 29150, "text": "Content Providers in Android with Example" }, { "code": null, "e": 29223, "s": 29192, "text": "Android RecyclerView in Kotlin" }, { "code": null, "e": 29266, "s": 29223, "text": "Broadcast Receiver in Android With Example" }, { "code": null, "e": 29308, "s": 29266, "text": "Content Providers in Android with Example" }, { "code": null, "e": 29341, "s": 29308, "text": "Services in Android with Example" }, { "code": null, "e": 29360, "s": 29341, "text": "Android UI Layouts" } ]
click_and_hold - Action Chains in Selenium Python - GeeksforGeeks
11 May, 2020 Selenium’s Python Module is built to perform automated testing with Python. ActionChains are a way to automate low-level interactions such as mouse movements, mouse button actions, keypress, and context menu interactions. This is useful for doing more complex actions like hover over and drag and drop. Action chain methods are used by advanced scripts where we need to drag an element, click an element, double click, etc.This article revolves around click_and_hold method on Action Chains in Python Selenium. click_and_hold method is used to hold down the left mouse button on an element.Syntax – click_and_hold(on_element=None) Example – <input type ="text" name ="passwd" id ="passwd-id" /> To find an element one needs to use one of the locating strategies, For example, element = driver.find_element_by_id("passwd-id")element = driver.find_element_by_name("passwd") Now one can use click_and_hold method as an Action chain as below – click_and_hold(on_element=element) To demonstrate, click_and_hold method of Action Chains in Selenium Python. Let’ s visit https://www.geeksforgeeks.org/ and operate on an element. Program – # import webdriverfrom selenium import webdriver # import Action chains from selenium.webdriver.common.action_chains import ActionChains # create webdriver objectdriver = webdriver.Firefox() # get geeksforgeeks.orgdriver.get("https://www.geeksforgeeks.org/") # get element element = driver.find_element_by_link_text("Courses") # create action chain objectaction = ActionChains(driver) # click and hold the itemaction.click_and_hold(on_element = element) # perform the operationaction.perform() Output – Python-selenium selenium Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Check if element exists in list in Python Python | os.path.join() method Selecting rows in pandas DataFrame based on conditions Defaultdict in Python Python | Get unique values from a list Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 24292, "s": 24264, "text": "\n11 May, 2020" }, { "code": null, "e": 24891, "s": 24292, "text": "Selenium’s Python Module is built to perform automated testing with Python. ActionChains are a way to automate low-level interactions such as mouse movements, mouse button actions, keypress, and context menu interactions. This is useful for doing more complex actions like hover over and drag and drop. Action chain methods are used by advanced scripts where we need to drag an element, click an element, double click, etc.This article revolves around click_and_hold method on Action Chains in Python Selenium. click_and_hold method is used to hold down the left mouse button on an element.Syntax –" }, { "code": null, "e": 24923, "s": 24891, "text": "click_and_hold(on_element=None)" }, { "code": null, "e": 24933, "s": 24923, "text": "Example –" }, { "code": "<input type =\"text\" name =\"passwd\" id =\"passwd-id\" />", "e": 24987, "s": 24933, "text": null }, { "code": null, "e": 25068, "s": 24987, "text": "To find an element one needs to use one of the locating strategies, For example," }, { "code": "element = driver.find_element_by_id(\"passwd-id\")element = driver.find_element_by_name(\"passwd\")", "e": 25164, "s": 25068, "text": null }, { "code": null, "e": 25232, "s": 25164, "text": "Now one can use click_and_hold method as an Action chain as below –" }, { "code": null, "e": 25268, "s": 25232, "text": "click_and_hold(on_element=element)\n" }, { "code": null, "e": 25414, "s": 25268, "text": "To demonstrate, click_and_hold method of Action Chains in Selenium Python. Let’ s visit https://www.geeksforgeeks.org/ and operate on an element." }, { "code": null, "e": 25424, "s": 25414, "text": "Program –" }, { "code": "# import webdriverfrom selenium import webdriver # import Action chains from selenium.webdriver.common.action_chains import ActionChains # create webdriver objectdriver = webdriver.Firefox() # get geeksforgeeks.orgdriver.get(\"https://www.geeksforgeeks.org/\") # get element element = driver.find_element_by_link_text(\"Courses\") # create action chain objectaction = ActionChains(driver) # click and hold the itemaction.click_and_hold(on_element = element) # perform the operationaction.perform()", "e": 25926, "s": 25424, "text": null }, { "code": null, "e": 25935, "s": 25926, "text": "Output –" }, { "code": null, "e": 25951, "s": 25935, "text": "Python-selenium" }, { "code": null, "e": 25960, "s": 25951, "text": "selenium" }, { "code": null, "e": 25967, "s": 25960, "text": "Python" }, { "code": null, "e": 26065, "s": 25967, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26097, "s": 26065, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26139, "s": 26097, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26195, "s": 26139, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26237, "s": 26195, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26268, "s": 26237, "text": "Python | os.path.join() method" }, { "code": null, "e": 26323, "s": 26268, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 26345, "s": 26323, "text": "Defaultdict in Python" }, { "code": null, "e": 26384, "s": 26345, "text": "Python | Get unique values from a list" }, { "code": null, "e": 26413, "s": 26384, "text": "Create a directory in Python" } ]
10 Most Important SQL Commands Every Data Analyst Needs to Know | by Jason Chong | Towards Data Science
As a data analyst or data scientist, it doesn’t matter how good you are at creating fancy visualizations or how skilled you are at building complicated models — at its core, you need data in order to do those things. When working at a large company, these data are typically stored in a database such that everyone can easily access and query the data that they need to do their job. How do you query said data? Well, that’s where SQL comes in. SQL is short for Structured Query Language and as the name suggests, it is a standardized language that is used to query or retrieve data from a relational database. Furthermore, it can also be used to perform various operations on the data such as filtering rows and columns as well as simple data manipulation. One of the earliest observations that I made when I started working as a data analyst was that everybody around me knew how to use SQL, and I mean literally everybody. Whether if you are an intern who just recently joined the team or a senior analyst who has been around for a long time, this is a skill that everyone needs to know. This goes to show just how significant SQL is in the world of data science analytics. In light of this, I wanted to highlight the top 10 SQL commands in this blog post to help you get started on your journey with using SQL but more importantly, I will be demonstrating each command using practical examples in order to simulate the feeling of actually working with a database. To do this, we will be using SQL Fiddle, a handy application for testing and sharing SQL queries online. For the purpose of this tutorial, I have created two mock tables called transaction and customers, which represent the transactions of a supermarket chain and customer profile respectively. SELECT and FROM form the foundation of all SQL queries. The most basic SQL query will involve these two commands and as the query gets more complex, more commands will be added on top of them. SELECT informs which columns you want to select whereas FROM specifies which table you want to query the data from. Let’s now look at some examples in relation to the transaction table. To view all the columns in the transaction table: SELECT * FROM transaction; Suppose we only want specific columns in the transaction table: SELECT transaction_id, purchase_date, sales FROM transaction; DISTINCT is used to view the unique values in a column. For example, suppose we would like to see the unique dates with transactions: SELECT DISTINCT purchase_date FROM transaction; WHERE is used to filter rows that match a certain condition. Moreover, it is also often used with other operators such as AND, OR, BETWEEN, IN and LIKE to combine multiple conditions together. Here are some examples: SELECT * FROM transaction WHERE purchase_date = '2021-10-15'; SELECT * FROM transactionWHERE purchase_date = '2021-10-15'AND store_location = 'Melbourne CBD'; SELECT * FROM transactionWHERE purchase_date = '2021-10-15'OR store_location = 'Melbourne CBD'; SELECT * FROM transactionWHERE store_location IN ('Richmond', 'Brunswick', 'Kew'); The % wildcard is used in a LIKE operator to match string patterns. Before we look at how this wildcard works, let’s first examine the customer profile table. This table tells us the life stage and the premium status of a particular customer. SELECT * FROM customers; Suppose now we want to filter out the rows in the customers' table where the customer life stage starts with the word Young. SELECT * FROM customers WHERE customer_lifestage LIKE 'Young%'; Similarly, if we want to view the rows where the customer life stage ends with the word families. SELECT * FROM customers WHERE customer_lifestage LIKE '%families'; As you can see, SQL offers a quick and straightforward way to matching string patterns, which can be convenient in many situations when filtering out rows. ORDER BY can be used to sort the result of a query by a particular column either alphabetically or numerically. It can be ordered in two ways: DESC which is in descending order or ASC which is in ascending order. Note that people don’t normally use ASC in their queries simply because SQL sets this by default. To demonstrate this, suppose we would like to order the transactions in alphabetical order based on the name of the store location. SELECT store_location, sales FROM transaction ORDER BY store_location; Alternatively, we can also sort the transactions by sales amount in descending order. SELECT store_location, sales FROM transaction ORDER BY store_location; AS enables us to rename a column or table. Note that this will not directly alter the names in their original columns or tables. The given query will return the date column from the transaction table where purchase_date is renamed to date. SELECT purchase_date as date from transaction; If you have used any other programming languages before, this is very similar to an if-else statement. Effectively, in plain English, the command sounds a little something like this: if a condition is satisfied, do this, otherwise do that. Let’s look at an example to solidify this idea. Suppose we want to create a new column that tells us if the sales amount of a particular transaction exceeds $20. SELECT transaction_id, sales,CASE WHEN sales < 20 THEN 'Sales amount is less than $20'ELSE 'Sales amount is greater than $20' END AS sales_threshold FROM transaction; GROUP BY will group data by their identical values. It is frequently used along with aggregate functions to summarise the attribute of a particular group of data. Aggregate functions, on the other hand, perform calculations on a range of values and return a single value. Some examples of aggregate functions include: COUNT: returns the total number of rows SUM: returns the sum of all the values MAX: returns the maximum value MIN: returns the minimum value AVG: returns the average value Let’s now turn to some examples. Suppose we want to know the number of rows in the transaction dataset. SELECT COUNT(*) FROM transaction; What about the highest sales amount in the transaction dataset. SELECT MAX(sales) as max_sales FROM transaction; Lastly, what if we are interested to know the total sales of each day, rounded to the nearest dollar? SELECT purchase_date, ROUND(SUM(sales)) as total_sales FROM transaction GROUP BY purchase_date; Before we discuss the concept of joins, I think it is important that we first distinguish the difference between a primary key and a foreign key. In relational databases, a primary key is used to uniquely identify each row in a table. For instance, the primary key for the transaction table is the transaction_id column, whereas the primary key for the customer profile table is the customer_id column. A foreign key, on the other hand, provides a link between data in two tables. Specifically, a foreign key in one table will link to the primary key in another table. For example, the customer_id column is a foreign key in the transaction table but it is a primary key in the customer profile table. Given the relationship between a primary key and a foreign key, we can perform a LEFT JOINin this particular scenario. There are other types of joins in SQL, such as INNER JOIN, RIGHT JOIN and FULL JOIN, which I won’t get to here. If you are interested to learn more, check out this blog post for more details. For now, suppose we want to perform a LEFT JOIN on the transaction table based on the customer_id column. SELECT a.*, b.customer_lifestage, b.customer_premiumFROM transaction AS aLEFT JOIN customers AS bON a.customer_id = b.customer_id; It’s also good practice to always check the number of rows after we perform LEFT JOIN to make sure the new table has the same number of rows as the left table before the join, which in this case is the transaction table. Last but certainly not least, UNION is used to combine query results from multiple SELECT statements. Note that the tables that you wish to union must have the same number of columns and equally important, the columns must be of the same data type. I have to admit, both the tables I have put together for this exercise might not be the best at illustrating the power of UNION, however, for the purpose of completeness, I will demonstrate it here. Suppose we want to union the customer_id column with the quantity_purchased column, both from the transaction table. SELECT customer_id AS sample_union FROM transaction UNIONSELECT quantity_purchased FROM transaction; With that, we conclude the 10 most important SQL commands that you need to get started with using SQL. I hope, through this blog post, you have gained a better understanding of what SQL is, its significance in data science analytics but more importantly, realize that it is actually relatively easy to learn once you get hold of the fundamentals. For any aspiring data analyst or data scientist, this is definitely one of the skills you should consider adding to your toolkit because SQL is here to stay. Until my next article, feel free to check out my other content here:
[ { "code": null, "e": 389, "s": 172, "text": "As a data analyst or data scientist, it doesn’t matter how good you are at creating fancy visualizations or how skilled you are at building complicated models — at its core, you need data in order to do those things." }, { "code": null, "e": 556, "s": 389, "text": "When working at a large company, these data are typically stored in a database such that everyone can easily access and query the data that they need to do their job." }, { "code": null, "e": 617, "s": 556, "text": "How do you query said data? Well, that’s where SQL comes in." }, { "code": null, "e": 930, "s": 617, "text": "SQL is short for Structured Query Language and as the name suggests, it is a standardized language that is used to query or retrieve data from a relational database. Furthermore, it can also be used to perform various operations on the data such as filtering rows and columns as well as simple data manipulation." }, { "code": null, "e": 1349, "s": 930, "text": "One of the earliest observations that I made when I started working as a data analyst was that everybody around me knew how to use SQL, and I mean literally everybody. Whether if you are an intern who just recently joined the team or a senior analyst who has been around for a long time, this is a skill that everyone needs to know. This goes to show just how significant SQL is in the world of data science analytics." }, { "code": null, "e": 1640, "s": 1349, "text": "In light of this, I wanted to highlight the top 10 SQL commands in this blog post to help you get started on your journey with using SQL but more importantly, I will be demonstrating each command using practical examples in order to simulate the feeling of actually working with a database." }, { "code": null, "e": 1935, "s": 1640, "text": "To do this, we will be using SQL Fiddle, a handy application for testing and sharing SQL queries online. For the purpose of this tutorial, I have created two mock tables called transaction and customers, which represent the transactions of a supermarket chain and customer profile respectively." }, { "code": null, "e": 2128, "s": 1935, "text": "SELECT and FROM form the foundation of all SQL queries. The most basic SQL query will involve these two commands and as the query gets more complex, more commands will be added on top of them." }, { "code": null, "e": 2244, "s": 2128, "text": "SELECT informs which columns you want to select whereas FROM specifies which table you want to query the data from." }, { "code": null, "e": 2314, "s": 2244, "text": "Let’s now look at some examples in relation to the transaction table." }, { "code": null, "e": 2364, "s": 2314, "text": "To view all the columns in the transaction table:" }, { "code": null, "e": 2391, "s": 2364, "text": "SELECT * FROM transaction;" }, { "code": null, "e": 2455, "s": 2391, "text": "Suppose we only want specific columns in the transaction table:" }, { "code": null, "e": 2517, "s": 2455, "text": "SELECT transaction_id, purchase_date, sales FROM transaction;" }, { "code": null, "e": 2651, "s": 2517, "text": "DISTINCT is used to view the unique values in a column. For example, suppose we would like to see the unique dates with transactions:" }, { "code": null, "e": 2699, "s": 2651, "text": "SELECT DISTINCT purchase_date FROM transaction;" }, { "code": null, "e": 2892, "s": 2699, "text": "WHERE is used to filter rows that match a certain condition. Moreover, it is also often used with other operators such as AND, OR, BETWEEN, IN and LIKE to combine multiple conditions together." }, { "code": null, "e": 2916, "s": 2892, "text": "Here are some examples:" }, { "code": null, "e": 2978, "s": 2916, "text": "SELECT * FROM transaction WHERE purchase_date = '2021-10-15';" }, { "code": null, "e": 3075, "s": 2978, "text": "SELECT * FROM transactionWHERE purchase_date = '2021-10-15'AND store_location = 'Melbourne CBD';" }, { "code": null, "e": 3171, "s": 3075, "text": "SELECT * FROM transactionWHERE purchase_date = '2021-10-15'OR store_location = 'Melbourne CBD';" }, { "code": null, "e": 3254, "s": 3171, "text": "SELECT * FROM transactionWHERE store_location IN ('Richmond', 'Brunswick', 'Kew');" }, { "code": null, "e": 3322, "s": 3254, "text": "The % wildcard is used in a LIKE operator to match string patterns." }, { "code": null, "e": 3497, "s": 3322, "text": "Before we look at how this wildcard works, let’s first examine the customer profile table. This table tells us the life stage and the premium status of a particular customer." }, { "code": null, "e": 3522, "s": 3497, "text": "SELECT * FROM customers;" }, { "code": null, "e": 3647, "s": 3522, "text": "Suppose now we want to filter out the rows in the customers' table where the customer life stage starts with the word Young." }, { "code": null, "e": 3711, "s": 3647, "text": "SELECT * FROM customers WHERE customer_lifestage LIKE 'Young%';" }, { "code": null, "e": 3809, "s": 3711, "text": "Similarly, if we want to view the rows where the customer life stage ends with the word families." }, { "code": null, "e": 3876, "s": 3809, "text": "SELECT * FROM customers WHERE customer_lifestage LIKE '%families';" }, { "code": null, "e": 4032, "s": 3876, "text": "As you can see, SQL offers a quick and straightforward way to matching string patterns, which can be convenient in many situations when filtering out rows." }, { "code": null, "e": 4245, "s": 4032, "text": "ORDER BY can be used to sort the result of a query by a particular column either alphabetically or numerically. It can be ordered in two ways: DESC which is in descending order or ASC which is in ascending order." }, { "code": null, "e": 4343, "s": 4245, "text": "Note that people don’t normally use ASC in their queries simply because SQL sets this by default." }, { "code": null, "e": 4475, "s": 4343, "text": "To demonstrate this, suppose we would like to order the transactions in alphabetical order based on the name of the store location." }, { "code": null, "e": 4546, "s": 4475, "text": "SELECT store_location, sales FROM transaction ORDER BY store_location;" }, { "code": null, "e": 4632, "s": 4546, "text": "Alternatively, we can also sort the transactions by sales amount in descending order." }, { "code": null, "e": 4703, "s": 4632, "text": "SELECT store_location, sales FROM transaction ORDER BY store_location;" }, { "code": null, "e": 4832, "s": 4703, "text": "AS enables us to rename a column or table. Note that this will not directly alter the names in their original columns or tables." }, { "code": null, "e": 4943, "s": 4832, "text": "The given query will return the date column from the transaction table where purchase_date is renamed to date." }, { "code": null, "e": 4990, "s": 4943, "text": "SELECT purchase_date as date from transaction;" }, { "code": null, "e": 5093, "s": 4990, "text": "If you have used any other programming languages before, this is very similar to an if-else statement." }, { "code": null, "e": 5230, "s": 5093, "text": "Effectively, in plain English, the command sounds a little something like this: if a condition is satisfied, do this, otherwise do that." }, { "code": null, "e": 5278, "s": 5230, "text": "Let’s look at an example to solidify this idea." }, { "code": null, "e": 5392, "s": 5278, "text": "Suppose we want to create a new column that tells us if the sales amount of a particular transaction exceeds $20." }, { "code": null, "e": 5559, "s": 5392, "text": "SELECT transaction_id, sales,CASE WHEN sales < 20 THEN 'Sales amount is less than $20'ELSE 'Sales amount is greater than $20' END AS sales_threshold FROM transaction;" }, { "code": null, "e": 5722, "s": 5559, "text": "GROUP BY will group data by their identical values. It is frequently used along with aggregate functions to summarise the attribute of a particular group of data." }, { "code": null, "e": 5877, "s": 5722, "text": "Aggregate functions, on the other hand, perform calculations on a range of values and return a single value. Some examples of aggregate functions include:" }, { "code": null, "e": 5917, "s": 5877, "text": "COUNT: returns the total number of rows" }, { "code": null, "e": 5956, "s": 5917, "text": "SUM: returns the sum of all the values" }, { "code": null, "e": 5987, "s": 5956, "text": "MAX: returns the maximum value" }, { "code": null, "e": 6018, "s": 5987, "text": "MIN: returns the minimum value" }, { "code": null, "e": 6049, "s": 6018, "text": "AVG: returns the average value" }, { "code": null, "e": 6082, "s": 6049, "text": "Let’s now turn to some examples." }, { "code": null, "e": 6153, "s": 6082, "text": "Suppose we want to know the number of rows in the transaction dataset." }, { "code": null, "e": 6187, "s": 6153, "text": "SELECT COUNT(*) FROM transaction;" }, { "code": null, "e": 6251, "s": 6187, "text": "What about the highest sales amount in the transaction dataset." }, { "code": null, "e": 6300, "s": 6251, "text": "SELECT MAX(sales) as max_sales FROM transaction;" }, { "code": null, "e": 6402, "s": 6300, "text": "Lastly, what if we are interested to know the total sales of each day, rounded to the nearest dollar?" }, { "code": null, "e": 6498, "s": 6402, "text": "SELECT purchase_date, ROUND(SUM(sales)) as total_sales FROM transaction GROUP BY purchase_date;" }, { "code": null, "e": 6644, "s": 6498, "text": "Before we discuss the concept of joins, I think it is important that we first distinguish the difference between a primary key and a foreign key." }, { "code": null, "e": 6901, "s": 6644, "text": "In relational databases, a primary key is used to uniquely identify each row in a table. For instance, the primary key for the transaction table is the transaction_id column, whereas the primary key for the customer profile table is the customer_id column." }, { "code": null, "e": 7200, "s": 6901, "text": "A foreign key, on the other hand, provides a link between data in two tables. Specifically, a foreign key in one table will link to the primary key in another table. For example, the customer_id column is a foreign key in the transaction table but it is a primary key in the customer profile table." }, { "code": null, "e": 7319, "s": 7200, "text": "Given the relationship between a primary key and a foreign key, we can perform a LEFT JOINin this particular scenario." }, { "code": null, "e": 7511, "s": 7319, "text": "There are other types of joins in SQL, such as INNER JOIN, RIGHT JOIN and FULL JOIN, which I won’t get to here. If you are interested to learn more, check out this blog post for more details." }, { "code": null, "e": 7617, "s": 7511, "text": "For now, suppose we want to perform a LEFT JOIN on the transaction table based on the customer_id column." }, { "code": null, "e": 7748, "s": 7617, "text": "SELECT a.*, b.customer_lifestage, b.customer_premiumFROM transaction AS aLEFT JOIN customers AS bON a.customer_id = b.customer_id;" }, { "code": null, "e": 7969, "s": 7748, "text": "It’s also good practice to always check the number of rows after we perform LEFT JOIN to make sure the new table has the same number of rows as the left table before the join, which in this case is the transaction table." }, { "code": null, "e": 8218, "s": 7969, "text": "Last but certainly not least, UNION is used to combine query results from multiple SELECT statements. Note that the tables that you wish to union must have the same number of columns and equally important, the columns must be of the same data type." }, { "code": null, "e": 8417, "s": 8218, "text": "I have to admit, both the tables I have put together for this exercise might not be the best at illustrating the power of UNION, however, for the purpose of completeness, I will demonstrate it here." }, { "code": null, "e": 8534, "s": 8417, "text": "Suppose we want to union the customer_id column with the quantity_purchased column, both from the transaction table." }, { "code": null, "e": 8635, "s": 8534, "text": "SELECT customer_id AS sample_union FROM transaction UNIONSELECT quantity_purchased FROM transaction;" }, { "code": null, "e": 8738, "s": 8635, "text": "With that, we conclude the 10 most important SQL commands that you need to get started with using SQL." }, { "code": null, "e": 8982, "s": 8738, "text": "I hope, through this blog post, you have gained a better understanding of what SQL is, its significance in data science analytics but more importantly, realize that it is actually relatively easy to learn once you get hold of the fundamentals." }, { "code": null, "e": 9140, "s": 8982, "text": "For any aspiring data analyst or data scientist, this is definitely one of the skills you should consider adding to your toolkit because SQL is here to stay." } ]
Get current year in MySQL WHERE clause?
To get current year, use YEAR() along with CURDATE(). Let us first create a table − mysql> create table DemoTable1360 -> ( -> JoiningYear int -> ) -> ; Query OK, 0 rows affected (0.51 sec) Insert some records in the table using insert command − mysql> insert into DemoTable1360 values(1998); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable1360 values(2018); Query OK, 1 row affected (0.22 sec) mysql> insert into DemoTable1360 values(2016); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable1360 values(2019); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable1360 values(2017); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable1360 values(2015); Query OK, 1 row affected (0.14 sec) Display all records from the table using select statement − mysql> select * from DemoTable1360; This will produce the following output − +-------------+ | JoiningYear | +-------------+ | 1998 | | 2018 | | 2016 | | 2019 | | 2017 | | 2015 | +-------------+ 6 rows in set (0.00 sec) Following is the query to get current year in MySQL where clause − mysql> select * from DemoTable1360 where JoiningYear=year(curdate()); This will produce the following output − +-------------+ | JoiningYear | +-------------+ | 2019 | +-------------+ 1 row in set (0.00 sec)
[ { "code": null, "e": 1146, "s": 1062, "text": "To get current year, use YEAR() along with CURDATE(). Let us first create a table −" }, { "code": null, "e": 1267, "s": 1146, "text": "mysql> create table DemoTable1360\n -> (\n -> JoiningYear int\n -> )\n -> ;\nQuery OK, 0 rows affected (0.51 sec)" }, { "code": null, "e": 1323, "s": 1267, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 1821, "s": 1323, "text": "mysql> insert into DemoTable1360 values(1998);\nQuery OK, 1 row affected (0.13 sec)\nmysql> insert into DemoTable1360 values(2018);\nQuery OK, 1 row affected (0.22 sec)\nmysql> insert into DemoTable1360 values(2016);\nQuery OK, 1 row affected (0.12 sec)\nmysql> insert into DemoTable1360 values(2019);\nQuery OK, 1 row affected (0.13 sec)\nmysql> insert into DemoTable1360 values(2017);\nQuery OK, 1 row affected (0.14 sec)\nmysql> insert into DemoTable1360 values(2015);\nQuery OK, 1 row affected (0.14 sec)" }, { "code": null, "e": 1881, "s": 1821, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 1917, "s": 1881, "text": "mysql> select * from DemoTable1360;" }, { "code": null, "e": 1958, "s": 1917, "text": "This will produce the following output −" }, { "code": null, "e": 2143, "s": 1958, "text": "+-------------+\n| JoiningYear |\n+-------------+\n| 1998 |\n| 2018 |\n| 2016 |\n| 2019 |\n| 2017 |\n| 2015 |\n+-------------+\n6 rows in set (0.00 sec)" }, { "code": null, "e": 2210, "s": 2143, "text": "Following is the query to get current year in MySQL where clause −" }, { "code": null, "e": 2280, "s": 2210, "text": "mysql> select * from DemoTable1360 where JoiningYear=year(curdate());" }, { "code": null, "e": 2321, "s": 2280, "text": "This will produce the following output −" }, { "code": null, "e": 2425, "s": 2321, "text": "+-------------+\n| JoiningYear |\n+-------------+\n| 2019 |\n+-------------+\n1 row in set (0.00 sec)" } ]
wxPython - SplitterWindow Class
Object of this class is a layout manager, which holds two subwindows whose size can be changed dynamically by dragging the boundaries between them. The Splitter control gives a handle that can be dragged to resize the controls. wx.SplitterWindow class has a very basic constructor with all parameters having usual default values. wx.SplitterWindow(self, id, pos, size, style) The list of predefined values for style parameter is as follows − wxSP_3D Draws a 3D effect border and sash wxSP_THIN_SASH Draws a thin sash wxSP_3DSASH Draws a 3D effect sash (part of default style) wxSP_BORDER Draws a standard border wxSP_NOBORDER No border (default) wxSP_PERMIT_UNSPLIT Always allow to unsplit, even with the minimum pane size other than zero Event binders for SplitterWindow class − EVT_SPLITTER_SASH_POS_CHANGING() The sash position is in the process of being changed EVT_SPLITTER_SASH_POS_CHANGED() The sash position was changed EVT_SPLITTER_UNSPLIT() The splitter has been just unsplit EVT_SPLITTER_DCLICK() The sash was double clicked. The default behavior is to unsplit the window when this happens The following code demonstrates the functioning of SplitterWindow. The splitter object is added to the top level frame. splitter = wx.SplitterWindow(self, -1) A Panel is designed to hold a multi-line TextCtrl object. b = wx.BoxSizer(wx.HORIZONTAL) self.text = wx.TextCtrl(panel1,style = wx.TE_MULTILINE) b.Add(self.text, 1, wx.EXPAND) panel1.SetSizerAndFit(b) A ListBox object is placed in another panel. panel2 = wx.Panel(splitter, -1) languages = ['C', 'C++', 'Java', 'Python', 'Perl', 'JavaScript', 'PHP', 'VB.NET', 'C#'] lst = wx.ListBox(panel2, size = (100,300), choices = languages, style = wx.LB_SINGLE) hbox1 = wx.BoxSizer(wx.HORIZONTAL) hbox1.Add(lst,1) panel2.SetSizer(hbox1) The splitter object is vertically split and two panels are added to two subwindows. The width of subwindows can be resized with the help of sash. splitter.SplitVertically(panel2, panel1) The complete listing of code is as follows − import wx class Mywin(wx.Frame): def __init__(self, parent, title): super(Mywin, self).__init__(parent, title = title,size = (350,300)) splitter = wx.SplitterWindow(self, -1) panel1 = wx.Panel(splitter, -1) b = wx.BoxSizer(wx.HORIZONTAL) self.text = wx.TextCtrl(panel1,style = wx.TE_MULTILINE) b.Add(self.text, 1, wx.EXPAND) panel1.SetSizerAndFit(b) panel2 = wx.Panel(splitter, -1) languages = ['C', 'C++', 'Java', 'Python', 'Perl', 'JavaScript', 'PHP' ,'VB.NET' ,'C#'] lst = wx.ListBox(panel2, size = (100,300), choices = languages, style = wx.LB_SINGLE) hbox1 = wx.BoxSizer(wx.HORIZONTAL) hbox1.Add(lst,1) panel2.SetSizer(hbox1) splitter.SplitVertically(panel2, panel1) self.Centre() self.Bind(wx.EVT_LISTBOX, self.onListBox, lst) self.Show(True) def onListBox(self, event): self.text.AppendText( "Current selection: " + event.GetEventObject().GetStringSelection() +"\n") ex = wx.App() Mywin(None,'Splitter Demo') ex.MainLoop() The above code produces the following output − Print Add Notes Bookmark this page
[ { "code": null, "e": 2110, "s": 1882, "text": "Object of this class is a layout manager, which holds two subwindows whose size can be changed dynamically by dragging the boundaries between them. The Splitter control gives a handle that can be dragged to resize the controls." }, { "code": null, "e": 2212, "s": 2110, "text": "wx.SplitterWindow class has a very basic constructor with all parameters having usual default values." }, { "code": null, "e": 2259, "s": 2212, "text": "wx.SplitterWindow(self, id, pos, size, style)\n" }, { "code": null, "e": 2325, "s": 2259, "text": "The list of predefined values for style parameter is as follows −" }, { "code": null, "e": 2333, "s": 2325, "text": "wxSP_3D" }, { "code": null, "e": 2367, "s": 2333, "text": "Draws a 3D effect border and sash" }, { "code": null, "e": 2382, "s": 2367, "text": "wxSP_THIN_SASH" }, { "code": null, "e": 2400, "s": 2382, "text": "Draws a thin sash" }, { "code": null, "e": 2412, "s": 2400, "text": "wxSP_3DSASH" }, { "code": null, "e": 2459, "s": 2412, "text": "Draws a 3D effect sash (part of default style)" }, { "code": null, "e": 2471, "s": 2459, "text": "wxSP_BORDER" }, { "code": null, "e": 2495, "s": 2471, "text": "Draws a standard border" }, { "code": null, "e": 2509, "s": 2495, "text": "wxSP_NOBORDER" }, { "code": null, "e": 2529, "s": 2509, "text": "No border (default)" }, { "code": null, "e": 2549, "s": 2529, "text": "wxSP_PERMIT_UNSPLIT" }, { "code": null, "e": 2622, "s": 2549, "text": "Always allow to unsplit, even with the minimum pane size other than zero" }, { "code": null, "e": 2663, "s": 2622, "text": "Event binders for SplitterWindow class −" }, { "code": null, "e": 2696, "s": 2663, "text": "EVT_SPLITTER_SASH_POS_CHANGING()" }, { "code": null, "e": 2749, "s": 2696, "text": "The sash position is in the process of being changed" }, { "code": null, "e": 2781, "s": 2749, "text": "EVT_SPLITTER_SASH_POS_CHANGED()" }, { "code": null, "e": 2811, "s": 2781, "text": "The sash position was changed" }, { "code": null, "e": 2834, "s": 2811, "text": "EVT_SPLITTER_UNSPLIT()" }, { "code": null, "e": 2869, "s": 2834, "text": "The splitter has been just unsplit" }, { "code": null, "e": 2891, "s": 2869, "text": "EVT_SPLITTER_DCLICK()" }, { "code": null, "e": 2984, "s": 2891, "text": "The sash was double clicked. The default behavior is to unsplit the window when this happens" }, { "code": null, "e": 3104, "s": 2984, "text": "The following code demonstrates the functioning of SplitterWindow. The splitter object is added to the top level frame." }, { "code": null, "e": 3144, "s": 3104, "text": "splitter = wx.SplitterWindow(self, -1)\n" }, { "code": null, "e": 3202, "s": 3144, "text": "A Panel is designed to hold a multi-line TextCtrl object." }, { "code": null, "e": 3349, "s": 3202, "text": "b = wx.BoxSizer(wx.HORIZONTAL) \nself.text = wx.TextCtrl(panel1,style = wx.TE_MULTILINE)\n \nb.Add(self.text, 1, wx.EXPAND) \npanel1.SetSizerAndFit(b)" }, { "code": null, "e": 3394, "s": 3349, "text": "A ListBox object is placed in another panel." }, { "code": null, "e": 3680, "s": 3394, "text": "panel2 = wx.Panel(splitter, -1) \nlanguages = ['C', 'C++', 'Java', 'Python', 'Perl', 'JavaScript', 'PHP', 'VB.NET', 'C#'] \nlst = wx.ListBox(panel2, size = (100,300), choices = languages, style = wx.LB_SINGLE) \nhbox1 = wx.BoxSizer(wx.HORIZONTAL) \nhbox1.Add(lst,1) \npanel2.SetSizer(hbox1)" }, { "code": null, "e": 3826, "s": 3680, "text": "The splitter object is vertically split and two panels are added to two subwindows. The width of subwindows can be resized with the help of sash." }, { "code": null, "e": 3868, "s": 3826, "text": "splitter.SplitVertically(panel2, panel1)\n" }, { "code": null, "e": 3913, "s": 3868, "text": "The complete listing of code is as follows −" }, { "code": null, "e": 5036, "s": 3913, "text": "import wx \nclass Mywin(wx.Frame): \n \n def __init__(self, parent, title): \n super(Mywin, self).__init__(parent, title = title,size = (350,300))\n\t\t\n splitter = wx.SplitterWindow(self, -1) \n panel1 = wx.Panel(splitter, -1) \n b = wx.BoxSizer(wx.HORIZONTAL) \n\t\t\n self.text = wx.TextCtrl(panel1,style = wx.TE_MULTILINE) \n b.Add(self.text, 1, wx.EXPAND) \n\t\t\n panel1.SetSizerAndFit(b)\n panel2 = wx.Panel(splitter, -1) \n\t\t\n languages = ['C', 'C++', 'Java', 'Python', 'Perl',\n 'JavaScript', 'PHP' ,'VB.NET' ,'C#'] \n lst = wx.ListBox(panel2, size = (100,300), choices = languages, style = wx.LB_SINGLE) \n\t\t\n hbox1 = wx.BoxSizer(wx.HORIZONTAL) \n hbox1.Add(lst,1) \n\t\t\n panel2.SetSizer(hbox1) \n splitter.SplitVertically(panel2, panel1) \n self.Centre() \n self.Bind(wx.EVT_LISTBOX, self.onListBox, lst) \n self.Show(True) \n\t\t\n def onListBox(self, event): \n self.text.AppendText( \"Current selection: \" + \n event.GetEventObject().GetStringSelection() +\"\\n\")\n\t\t\t\nex = wx.App() \nMywin(None,'Splitter Demo') \nex.MainLoop()" }, { "code": null, "e": 5083, "s": 5036, "text": "The above code produces the following output −" }, { "code": null, "e": 5090, "s": 5083, "text": " Print" }, { "code": null, "e": 5101, "s": 5090, "text": " Add Notes" } ]
How to change the code "Yes" to 1 in an R data frame column?
To change the code “Yes” to 1, we can use ifelse function and set the Yes to 1 and others to 0. For example, if we have a data frame called df that contains a character column x which has Yes and No values then we can convert those values to 1 and 0 using the command ifelse(df$x=="Yes",1,0). Consider the below data frame − Live Demo Agree<-sample(c("Yes","No"),20,replace=TRUE) x<-rpois(20,5) df1<-data.frame(Agree,x) df1 Agree x 1 No 6 2 No 4 3 Yes 5 4 No 9 5 No 4 6 No 0 7 Yes 4 8 No 5 9 No 6 10 No 5 11 No 6 12 No 2 13 No 6 14 No 2 15 Yes 3 16 Yes 9 17 No 3 18 Yes 3 19 No 0 20 Yes 7 Converting Yes to 1 and No to 0 in df1 − df1$Agree<-ifelse(df1$Agree=="Yes",1,0) df1 Agree x 1 0 6 2 0 4 3 1 5 4 0 9 5 0 4 6 0 0 7 1 4 8 0 5 9 0 6 10 0 5 11 0 6 12 0 2 13 0 6 14 0 2 15 1 3 16 1 9 17 0 3 18 1 3 19 0 0 20 1 7 Live Demo Approved<-sample(c("Yes","No"),20,replace=TRUE) y<-rnorm(20,30,2.4) df2<-data.frame(Approved,y) df2 Approved y 1 Yes 33.17910 2 No 31.69268 3 Yes 30.96484 4 Yes 34.12339 5 Yes 30.84079 6 No 27.57933 7 Yes 29.13050 8 No 32.55457 9 Yes 34.39399 10 No 30.22306 11 Yes 29.65322 12 Yes 29.42060 13 Yes 30.75312 14 No 32.25545 15 Yes 27.54001 16 No 25.93290 17 No 27.45960 18 Yes 26.28884 19 No 32.08387 20 Yes 28.60269 Converting Yes to 1 and No to 0 in df2 − df2$Approved<-ifelse(df2$Approved=="Yes",1,0) df2 Approved y 1 1 33.17910 2 0 31.69268 3 1 30.96484 4 1 34.12339 5 1 30.84079 6 0 27.57933 7 1 29.13050 8 0 32.55457 9 1 34.39399 10 0 30.22306 11 1 29.65322 12 1 29.42060 13 1 30.75312 14 0 32.25545 15 1 27.54001 16 0 25.93290 17 0 27.45960 18 1 26.28884 19 0 32.08387 20 1 28.60269
[ { "code": null, "e": 1355, "s": 1062, "text": "To change the code “Yes” to 1, we can use ifelse function and set the Yes to 1 and others to 0. For example, if we have a data frame called df that contains a character column x which has Yes and No values then we can convert those values to 1 and 0 using the command ifelse(df$x==\"Yes\",1,0)." }, { "code": null, "e": 1387, "s": 1355, "text": "Consider the below data frame −" }, { "code": null, "e": 1398, "s": 1387, "text": " Live Demo" }, { "code": null, "e": 1487, "s": 1398, "text": "Agree<-sample(c(\"Yes\",\"No\"),20,replace=TRUE)\nx<-rpois(20,5)\ndf1<-data.frame(Agree,x)\ndf1" }, { "code": null, "e": 1697, "s": 1487, "text": " Agree x\n1 No 6\n2 No 4\n3 Yes 5\n4 No 9\n5 No 4\n6 No 0\n7 Yes 4\n8 No 5\n9 No 6\n10 No 5\n11 No 6\n12 No 2\n13 No 6\n14 No 2\n15 Yes 3\n16 Yes 9\n17 No 3\n18 Yes 3\n19 No 0\n20 Yes 7" }, { "code": null, "e": 1738, "s": 1697, "text": "Converting Yes to 1 and No to 0 in df1 −" }, { "code": null, "e": 1782, "s": 1738, "text": "df1$Agree<-ifelse(df1$Agree==\"Yes\",1,0)\ndf1" }, { "code": null, "e": 1992, "s": 1782, "text": " Agree x\n1 0 6\n2 0 4\n3 1 5\n4 0 9\n5 0 4\n6 0 0\n7 1 4\n8 0 5\n9 0 6\n10 0 5\n11 0 6\n12 0 2\n13 0 6\n14 0 2\n15 1 3\n16 1 9\n17 0 3\n18 1 3\n19 0 0\n20 1 7" }, { "code": null, "e": 2003, "s": 1992, "text": " Live Demo" }, { "code": null, "e": 2103, "s": 2003, "text": "Approved<-sample(c(\"Yes\",\"No\"),20,replace=TRUE)\ny<-rnorm(20,30,2.4)\ndf2<-data.frame(Approved,y)\ndf2" }, { "code": null, "e": 2519, "s": 2103, "text": " Approved y\n1 Yes 33.17910\n2 No 31.69268\n3 Yes 30.96484\n4 Yes 34.12339\n5 Yes 30.84079\n6 No 27.57933\n7 Yes 29.13050\n8 No 32.55457\n9 Yes 34.39399\n10 No 30.22306\n11 Yes 29.65322\n12 Yes 29.42060\n13 Yes 30.75312\n14 No 32.25545\n15 Yes 27.54001\n16 No 25.93290\n17 No 27.45960\n18 Yes 26.28884\n19 No 32.08387\n20 Yes 28.60269" }, { "code": null, "e": 2560, "s": 2519, "text": "Converting Yes to 1 and No to 0 in df2 −" }, { "code": null, "e": 2610, "s": 2560, "text": "df2$Approved<-ifelse(df2$Approved==\"Yes\",1,0)\ndf2" }, { "code": null, "e": 3007, "s": 2610, "text": " Approved y\n1 1 33.17910\n2 0 31.69268\n3 1 30.96484\n4 1 34.12339\n5 1 30.84079\n6 0 27.57933\n7 1 29.13050\n8 0 32.55457\n9 1 34.39399\n10 0 30.22306\n11 1 29.65322\n12 1 29.42060\n13 1 30.75312\n14 0 32.25545\n15 1 27.54001\n16 0 25.93290\n17 0 27.45960\n18 1 26.28884\n19 0 32.08387\n20 1 28.60269" } ]
How can Tensorflow be used to train and compile a CNN model?
A convolutional neural network can be trained and compiled using the ‘train’ method and the ‘fit’ method respectively. The ‘epoch’ value is provided in the ‘fit’ method. Read More: What is TensorFlow and how Keras work with TensorFlow to create Neural Networks? We will use the Keras Sequential API, which is helpful in building a sequential model that is used to work with a plain stack of layers, where every layer has exactly one input tensor and one output tensor. A neural network that contains at least one layer is known as a convolutional layer. Convolutional neural networks have been used to produce great results for a specific kind of problems, such as image recognition. We are using the Google Colaboratory to run the below code. Google Colab or Colaboratory helps run Python code over the browser and requires zero configuration and free access to GPUs (Graphical Processing Units). Colaboratory has been built on top of Jupyter Notebook. print("Compiling the model") model.compile(optimizer='adam',loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True), metrics=['accuracy']) print("Training the model to fit the data") history = model.fit(train_images, train_labels, epochs=10,validation_data=(test_images, test_labels)) Code credit: https://www.tensorflow.org/tutorials/images/cnn Compiling the model Training the model to fit the data Epoch 1/10 1563/1563 [==============================] - 70s 44ms/step - loss: 1.7408 - accuracy: 0.3557 - val_loss: 1.2260 - val_accuracy: 0.5509 Epoch 2/10 1563/1563 [==============================] - 67s 43ms/step - loss: 1.1928 - accuracy: 0.5751 - val_loss: 1.0800 - val_accuracy: 0.6159 Epoch 3/10 1563/1563 [==============================] - 68s 43ms/step - loss: 1.0330 - accuracy: 0.6396 - val_loss: 0.9791 - val_accuracy: 0.6562 Epoch 4/10 1563/1563 [==============================] - 66s 43ms/step - loss: 0.9197 - accuracy: 0.6782 - val_loss: 0.9488 - val_accuracy: 0.6677 Epoch 5/10 1563/1563 [==============================] - 65s 42ms/step - loss: 0.8388 - accuracy: 0.7043 - val_loss: 0.9090 - val_accuracy: 0.6851 Epoch 6/10 1563/1563 [==============================] - 66s 42ms/step - loss: 0.7755 - accuracy: 0.7279 - val_loss: 0.8694 - val_accuracy: 0.6944 Epoch 7/10 1563/1563 [==============================] - 66s 42ms/step - loss: 0.7107 - accuracy: 0.7494 - val_loss: 0.9152 - val_accuracy: 0.6929 Epoch 8/10 1563/1563 [==============================] - 65s 42ms/step - loss: 0.6674 - accuracy: 0.7649 - val_loss: 0.8613 - val_accuracy: 0.7045 Epoch 9/10 1563/1563 [==============================] - 66s 42ms/step - loss: 0.6288 - accuracy: 0.7771 - val_loss: 0.8788 - val_accuracy: 0.7026 Epoch 10/10 1563/1563 [==============================] - 66s 42ms/step - loss: 0.5913 - accuracy: 0.7953 - val_loss: 0.8884 - val_accuracy: 0.7053 The model is compiled. The next step is to train the model to fit the training data. The number of steps to train the data is 10.
[ { "code": null, "e": 1232, "s": 1062, "text": "A convolutional neural network can be trained and compiled using the ‘train’ method and the ‘fit’ method respectively. The ‘epoch’ value is provided in the ‘fit’ method." }, { "code": null, "e": 1324, "s": 1232, "text": "Read More:\nWhat is TensorFlow and how Keras work with TensorFlow to create Neural Networks?" }, { "code": null, "e": 1531, "s": 1324, "text": "We will use the Keras Sequential API, which is helpful in building a sequential model that is used to work with a plain stack of layers, where every layer has exactly one input tensor and one output tensor." }, { "code": null, "e": 1748, "s": 1531, "text": "A neural network that contains at least one layer is known as a convolutional layer. Convolutional neural networks have been used to produce great results for a specific kind of problems, such as image recognition. " }, { "code": null, "e": 2018, "s": 1748, "text": "We are using the Google Colaboratory to run the below code. Google Colab or Colaboratory helps run Python code over the browser and requires zero configuration and free access to GPUs (Graphical Processing Units). Colaboratory has been built on top of Jupyter Notebook." }, { "code": null, "e": 2319, "s": 2018, "text": "print(\"Compiling the model\")\nmodel.compile(optimizer='adam',loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),\n metrics=['accuracy'])\nprint(\"Training the model to fit the data\")\nhistory = model.fit(train_images, train_labels, epochs=10,validation_data=(test_images, test_labels))" }, { "code": null, "e": 2380, "s": 2319, "text": "Code credit: https://www.tensorflow.org/tutorials/images/cnn" }, { "code": null, "e": 3896, "s": 2380, "text": "Compiling the model\nTraining the model to fit the data\nEpoch 1/10\n1563/1563 [==============================] - 70s 44ms/step - loss: 1.7408 - accuracy: 0.3557 - val_loss: 1.2260 - val_accuracy: 0.5509\nEpoch 2/10\n1563/1563 [==============================] - 67s 43ms/step - loss: 1.1928 - accuracy: 0.5751 - val_loss: 1.0800 - val_accuracy: 0.6159\nEpoch 3/10\n1563/1563 [==============================] - 68s 43ms/step - loss: 1.0330 - accuracy: 0.6396 - val_loss: 0.9791 - val_accuracy: 0.6562\nEpoch 4/10\n1563/1563 [==============================] - 66s 43ms/step - loss: 0.9197 - accuracy: 0.6782 - val_loss: 0.9488 - val_accuracy: 0.6677\nEpoch 5/10\n1563/1563 [==============================] - 65s 42ms/step - loss: 0.8388 - accuracy: 0.7043 - val_loss: 0.9090 - val_accuracy: 0.6851\nEpoch 6/10\n1563/1563 [==============================] - 66s 42ms/step - loss: 0.7755 - accuracy: 0.7279 - val_loss: 0.8694 - val_accuracy: 0.6944\nEpoch 7/10\n1563/1563 [==============================] - 66s 42ms/step - loss: 0.7107 - accuracy: 0.7494 - val_loss: 0.9152 - val_accuracy: 0.6929\nEpoch 8/10\n1563/1563 [==============================] - 65s 42ms/step - loss: 0.6674 - accuracy: 0.7649 - val_loss: 0.8613 - val_accuracy: 0.7045\nEpoch 9/10\n1563/1563 [==============================] - 66s 42ms/step - loss: 0.6288 - accuracy: 0.7771 - val_loss: 0.8788 - val_accuracy: 0.7026\nEpoch 10/10\n1563/1563 [==============================] - 66s 42ms/step - loss: 0.5913 - accuracy: 0.7953 - val_loss: 0.8884 - val_accuracy: 0.7053" }, { "code": null, "e": 3919, "s": 3896, "text": "The model is compiled." }, { "code": null, "e": 3981, "s": 3919, "text": "The next step is to train the model to fit the training data." }, { "code": null, "e": 4026, "s": 3981, "text": "The number of steps to train the data is 10." } ]
Python program to print all odd numbers in a range - GeeksforGeeks
31 Mar, 2020 Given starting and end points, write a Python program to print all odd numbers in that given range. Example: Input: start = 4, end = 15 Output: 5, 7, 9, 11, 13, 15 Input: start = 3, end = 11 Output: 3, 5, 7, 9, 11 Example #1: Print all odd numbers from given list using for loop Define start and end limit of range. Iterate from start till the range in the list using for loop and check if num % 2 != 0. If the condition satisfies, then only print the number. # Python program to print odd Numbers in given range start, end = 4, 19 # iterating each number in listfor num in range(start, end + 1): # checking condition if num % 2 != 0: print(num, end = " ") Output: 5 7 9 11 13 15 17 19 Example #2: Taking range limit from user input # Python program to print Even Numbers in given range start = int(input("Enter the start of range: "))end = int(input("Enter the end of range: ")) # iterating each number in listfor num in range(start, end + 1): # checking condition if num % 2 != 0: print(num, end = " ") Output: Enter the start of range: 3 Enter the end of range: 11 3 5 7 9 11 Example #3: Taking range limit from user input # Python program to print Even Numbers in given range start = int(input("Enter the start of range: "))end = int(input("Enter the end of range: ")) #create a list that contains only Even numbers in given rangeeven_list = range(start, end + 1)[start%2::2] for num in even_list: print(num, end = " ") Output: Enter the start of range: 3 Enter the end of range: 11 3 5 7 9 11 KenMa Python list-programs python-list Python Python Programs School Programming python-list Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Enumerate() in Python Defaultdict in Python Different ways to create Pandas Dataframe sum() function in Python How to Install PIP on Windows ? 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": 24617, "s": 24589, "text": "\n31 Mar, 2020" }, { "code": null, "e": 24717, "s": 24617, "text": "Given starting and end points, write a Python program to print all odd numbers in that given range." }, { "code": null, "e": 24726, "s": 24717, "text": "Example:" }, { "code": null, "e": 24832, "s": 24726, "text": "Input: start = 4, end = 15\nOutput: 5, 7, 9, 11, 13, 15\n\nInput: start = 3, end = 11\nOutput: 3, 5, 7, 9, 11" }, { "code": null, "e": 24897, "s": 24832, "text": "Example #1: Print all odd numbers from given list using for loop" }, { "code": null, "e": 25078, "s": 24897, "text": "Define start and end limit of range. Iterate from start till the range in the list using for loop and check if num % 2 != 0. If the condition satisfies, then only print the number." }, { "code": "# Python program to print odd Numbers in given range start, end = 4, 19 # iterating each number in listfor num in range(start, end + 1): # checking condition if num % 2 != 0: print(num, end = \" \")", "e": 25296, "s": 25078, "text": null }, { "code": null, "e": 25304, "s": 25296, "text": "Output:" }, { "code": null, "e": 25326, "s": 25304, "text": "5 7 9 11 13 15 17 19 " }, { "code": null, "e": 25374, "s": 25326, "text": " Example #2: Taking range limit from user input" }, { "code": "# Python program to print Even Numbers in given range start = int(input(\"Enter the start of range: \"))end = int(input(\"Enter the end of range: \")) # iterating each number in listfor num in range(start, end + 1): # checking condition if num % 2 != 0: print(num, end = \" \")", "e": 25667, "s": 25374, "text": null }, { "code": null, "e": 25675, "s": 25667, "text": "Output:" }, { "code": null, "e": 25742, "s": 25675, "text": "Enter the start of range: 3\nEnter the end of range: 11\n3 5 7 9 11 " }, { "code": null, "e": 25790, "s": 25742, "text": " Example #3: Taking range limit from user input" }, { "code": "# Python program to print Even Numbers in given range start = int(input(\"Enter the start of range: \"))end = int(input(\"Enter the end of range: \")) #create a list that contains only Even numbers in given rangeeven_list = range(start, end + 1)[start%2::2] for num in even_list: print(num, end = \" \")", "e": 26094, "s": 25790, "text": null }, { "code": null, "e": 26102, "s": 26094, "text": "Output:" }, { "code": null, "e": 26169, "s": 26102, "text": "Enter the start of range: 3\nEnter the end of range: 11\n3 5 7 9 11 " }, { "code": null, "e": 26175, "s": 26169, "text": "KenMa" }, { "code": null, "e": 26196, "s": 26175, "text": "Python list-programs" }, { "code": null, "e": 26208, "s": 26196, "text": "python-list" }, { "code": null, "e": 26215, "s": 26208, "text": "Python" }, { "code": null, "e": 26231, "s": 26215, "text": "Python Programs" }, { "code": null, "e": 26250, "s": 26231, "text": "School Programming" }, { "code": null, "e": 26262, "s": 26250, "text": "python-list" }, { "code": null, "e": 26360, "s": 26262, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26369, "s": 26360, "text": "Comments" }, { "code": null, "e": 26382, "s": 26369, "text": "Old Comments" }, { "code": null, "e": 26404, "s": 26382, "text": "Enumerate() in Python" }, { "code": null, "e": 26426, "s": 26404, "text": "Defaultdict in Python" }, { "code": null, "e": 26468, "s": 26426, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 26493, "s": 26468, "text": "sum() function in Python" }, { "code": null, "e": 26525, "s": 26493, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26547, "s": 26525, "text": "Defaultdict in Python" }, { "code": null, "e": 26586, "s": 26547, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 26632, "s": 26586, "text": "Python | Split string into list of characters" }, { "code": null, "e": 26670, "s": 26632, "text": "Python | Convert a list to dictionary" } ]
React Native - Props
In our last chapter, we showed you how to use mutable state. In this chapter, we will show you how to combine the state and the props. Presentational components should get all data by passing props. Only container components should have state. We will now understand what a container component is and also how it works. Now we will update our container component. This component will handle the state and pass the props to the presentational component. Container component is only used for handling state. All functionality related to view(styling etc.) will be handled in the presentational component. If we want to use example from the last chapter we need to remove the Text element from the render function since this element is used for presenting text to the users. This should be inside the presentational component. Let us review the code in the example given below. We will import the PresentationalComponent and pass it to the render function. After we import the PresentationalComponent and pass it to the render function, we need to pass the props. We will pass the props by adding myText = {this.state.myText} and deleteText = {this.deleteText} to <PresentationalComponent>. Now, we will be able to access this inside the presentational component. App.js import React from 'react'; import { StyleSheet, Text, View } from 'react-native'; import PresentationalComponent from './PresentationalComponent' export default class App extends React.Component { state = { myState: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, used do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.' } updateState = () => { this.setState({ myState: 'The state is updated' }) } render() { return ( <View> <PresentationalComponent myState = {this.state.myState} updateState = {this.updateState}/> </View> ); } } We will now understand what a presentational component is and also how it works. Presentational components should be used only for presenting view to the users. These components do not have state. They receive all data and functions as props. The best practice is to use as much presentational components as possible. As we mentioned in our previous chapter, we are using the EC6 function syntax for presentational components. Our component will receive props, return view elements, present text using {props.myText} and call the {props.deleteText} function when a user clicks on the text. PresentationalComponent.js import React, { Component } from 'react' import { Text, View } from 'react-native' const PresentationalComponent = (props) => { return ( <View> <Text onPress = {props.updateState}> {props.myState} </Text> </View> ) } export default PresentationalComponent Now, we have the same functionality as in our State chapter. The only difference is that we refactored our code to the container and the presentational component. You can run the app and see the text as in the following screenshot. If you click on text, it will be removed from the screen. 20 Lectures 1.5 hours Anadi Sharma 61 Lectures 6.5 hours A To Z Mentor 40 Lectures 4.5 hours Eduonix Learning Solutions 56 Lectures 12.5 hours Eduonix Learning Solutions 62 Lectures 4.5 hours Senol Atac 67 Lectures 4.5 hours Senol Atac Print Add Notes Bookmark this page
[ { "code": null, "e": 2479, "s": 2344, "text": "In our last chapter, we showed you how to use mutable state. In this chapter, we will show you how to combine the state and the props." }, { "code": null, "e": 2588, "s": 2479, "text": "Presentational components should get all data by passing props. Only container components should have state." }, { "code": null, "e": 2664, "s": 2588, "text": "We will now understand what a container component is and also how it works." }, { "code": null, "e": 2797, "s": 2664, "text": "Now we will update our container component. This component will handle the state and pass the props to the presentational component." }, { "code": null, "e": 2947, "s": 2797, "text": "Container component is only used for handling state. All functionality related to view(styling etc.) will be handled in the presentational component." }, { "code": null, "e": 3168, "s": 2947, "text": "If we want to use example from the last chapter we need to remove the Text element from the render function since this element is used for presenting text to the users. This should be inside the presentational component." }, { "code": null, "e": 3298, "s": 3168, "text": "Let us review the code in the example given below. We will import the PresentationalComponent and pass it to the render function." }, { "code": null, "e": 3605, "s": 3298, "text": "After we import the PresentationalComponent and pass it to the render function, we need to pass the props. We will pass the props by adding myText = {this.state.myText} and deleteText = {this.deleteText} to <PresentationalComponent>. Now, we will be able to access this inside the presentational component." }, { "code": null, "e": 3612, "s": 3605, "text": "App.js" }, { "code": null, "e": 4591, "s": 3612, "text": "import React from 'react';\nimport { StyleSheet, Text, View } from 'react-native';\nimport PresentationalComponent from './PresentationalComponent'\n\nexport default class App extends React.Component {\n state = {\n myState: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, used do eiusmod\n tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis\n nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis\n aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat\n nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui\n officia deserunt mollit anim id est laborum.'\n }\n updateState = () => {\n this.setState({ myState: 'The state is updated' })\n }\n render() {\n return (\n <View>\n <PresentationalComponent myState = {this.state.myState} updateState = {this.updateState}/>\n </View>\n );\n }\n}" }, { "code": null, "e": 4672, "s": 4591, "text": "We will now understand what a presentational component is and also how it works." }, { "code": null, "e": 4834, "s": 4672, "text": "Presentational components should be used only for presenting view to the users. These components do not have state. They receive all data and functions as props." }, { "code": null, "e": 4909, "s": 4834, "text": "The best practice is to use as much presentational components as possible." }, { "code": null, "e": 5018, "s": 4909, "text": "As we mentioned in our previous chapter, we are using the EC6 function syntax for presentational components." }, { "code": null, "e": 5181, "s": 5018, "text": "Our component will receive props, return view elements, present text using {props.myText} and call the {props.deleteText} function when a user clicks on the text." }, { "code": null, "e": 5208, "s": 5181, "text": "PresentationalComponent.js" }, { "code": null, "e": 5513, "s": 5208, "text": "import React, { Component } from 'react'\nimport { Text, View } from 'react-native'\n\nconst PresentationalComponent = (props) => {\n return (\n <View>\n <Text onPress = {props.updateState}>\n {props.myState}\n </Text>\n </View>\n )\n}\nexport default PresentationalComponent" }, { "code": null, "e": 5676, "s": 5513, "text": "Now, we have the same functionality as in our State chapter. The only difference is that we refactored our code to the container and the presentational component." }, { "code": null, "e": 5745, "s": 5676, "text": "You can run the app and see the text as in the following screenshot." }, { "code": null, "e": 5803, "s": 5745, "text": "If you click on text, it will be removed from the screen." }, { "code": null, "e": 5838, "s": 5803, "text": "\n 20 Lectures \n 1.5 hours \n" }, { "code": null, "e": 5852, "s": 5838, "text": " Anadi Sharma" }, { "code": null, "e": 5887, "s": 5852, "text": "\n 61 Lectures \n 6.5 hours \n" }, { "code": null, "e": 5902, "s": 5887, "text": " A To Z Mentor" }, { "code": null, "e": 5937, "s": 5902, "text": "\n 40 Lectures \n 4.5 hours \n" }, { "code": null, "e": 5965, "s": 5937, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 6001, "s": 5965, "text": "\n 56 Lectures \n 12.5 hours \n" }, { "code": null, "e": 6029, "s": 6001, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 6064, "s": 6029, "text": "\n 62 Lectures \n 4.5 hours \n" }, { "code": null, "e": 6076, "s": 6064, "text": " Senol Atac" }, { "code": null, "e": 6111, "s": 6076, "text": "\n 67 Lectures \n 4.5 hours \n" }, { "code": null, "e": 6123, "s": 6111, "text": " Senol Atac" }, { "code": null, "e": 6130, "s": 6123, "text": " Print" }, { "code": null, "e": 6141, "s": 6130, "text": " Add Notes" } ]
What is the difference between width and innerWidth in jQuery?
Width in jQuery The width is the horizontal measurement of the container, for example, width of a div. It excludes the padding, border, or margin. You can try to run the following code to learn how to get the width of an element in jQuery: Live Demo <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("button").click(function(){ alert("Width of div element: " + $("div").width()); }); }); </script> </head> <body> <div style="height:200px;width:400px;padding:20px;margin:1px;border:1px solid red; background-color:gray;"></div><br> <button>Get Width of div</button> </body> </html> innerWidth in jQuery The innerWidth() returns the inner width of the first matched element. It includes padding, but not border and margin. You can try to run the following code to get the inner width in jQuery: Live Demo <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("button").click(function(){ alert("Inner Width of div element: " + $("div").innerWidth()); }); }); </script> </head> <body> <div style="height:200px;width:400px;padding:20px;margin:1px;border:1px solid red; background-color:gray;"></div><br> <button>Get Inner Width of div</button> </body> </html>
[ { "code": null, "e": 1078, "s": 1062, "text": "Width in jQuery" }, { "code": null, "e": 1209, "s": 1078, "text": "The width is the horizontal measurement of the container, for example, width of a div. It excludes the padding, border, or margin." }, { "code": null, "e": 1302, "s": 1209, "text": "You can try to run the following code to learn how to get the width of an element in jQuery:" }, { "code": null, "e": 1312, "s": 1302, "text": "Live Demo" }, { "code": null, "e": 1771, "s": 1312, "text": "<!DOCTYPE html>\n<html>\n<head>\n<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js\"></script>\n<script>\n$(document).ready(function(){\n $(\"button\").click(function(){\n alert(\"Width of div element: \" + $(\"div\").width());\n });\n});\n</script>\n</head>\n<body>\n\n<div style=\"height:200px;width:400px;padding:20px;margin:1px;border:1px solid red; background-color:gray;\"></div><br>\n<button>Get Width of div</button>\n\n</body>\n</html>" }, { "code": null, "e": 1792, "s": 1771, "text": "innerWidth in jQuery" }, { "code": null, "e": 1911, "s": 1792, "text": "The innerWidth() returns the inner width of the first matched element. It includes padding, but not border and margin." }, { "code": null, "e": 1983, "s": 1911, "text": "You can try to run the following code to get the inner width in jQuery:" }, { "code": null, "e": 1993, "s": 1983, "text": "Live Demo" }, { "code": null, "e": 2470, "s": 1993, "text": "<!DOCTYPE html>\n<html>\n<head>\n<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js\"></script>\n<script>\n$(document).ready(function(){\n $(\"button\").click(function(){\n alert(\"Inner Width of div element: \" + $(\"div\").innerWidth());\n });\n});\n</script>\n</head>\n<body>\n\n<div style=\"height:200px;width:400px;padding:20px;margin:1px;border:1px solid red; background-color:gray;\"></div><br>\n<button>Get Inner Width of div</button>\n\n</body>\n</html>\n" } ]
Max sum in sub-arrays | Practice | GeeksforGeeks
Given an array, find maximum sum of smallest and second smallest elements chosen from all possible sub-arrays. More formally, if we write all (nC2) sub-arrays of array of size >=2 and find the sum of smallest and second smallest, then our answer will be maximum sum among them. Example 1: Input : arr[] = [4, 3, 1, 5, 6] Output : 11 Subarrays with smallest and second smallest are, [4, 3] smallest = 3 second smallest = 4 [4, 3, 1] smallest = 1 second smallest = 3 [4, 3, 1, 5] smallest = 1 second smallest = 3 [4, 3, 1, 5, 6] smallest = 1 second smallest = 3 [3, 1] smallest = 1 second smallest = 3 [3, 1, 5] smallest = 1 second smallest = 3 [3, 1, 5, 6] smallest = 1 second smallest = 3 [1, 5] smallest = 1 second smallest = 5 [1, 5, 6] smallest = 1 second smallest = 5 [5, 6] smallest = 5 second smallest = 6 Maximum sum among all above choices is, 5 + 6 = 11 Input : arr[] = {5, 4, 3, 1, 6} Output : 9 Your Task: You don't need to read input or print anything. Your task is to complete the function pairWithMaxSum() which takes the array Arr[] and its size N as inputs and returns the maximum sum of smallest and second smallest elements chosen from all possible subarrays. Expected Time Complexity: O(N) Expected Auxiliary Space: O(1) Constraints: 2 ≤ N ≤ 105 1 ≤ A[i] ≤ 1018 0 prabhakarsati294262 weeks ago def pairWithMaxSum(self, arr, N): # Your code goes here if (N<2): return -1 res = arr[0]+arr[1] for i in range(1,N-1): res = max(res,arr[i]+arr[i+1]) return res 0 abhishekabhi73521 month ago class Solution { public static long pairWithMaxSum(long arr[], long N) { long max=0; for(int i=0;i<N-1;i++) { if(arr[i]+arr[i+1]>max) { max=arr[i]+arr[i+1]; } } return max; }} 0 mashhadihossain1 month ago SIMPLE JAVA SOLUTION WITHOUT STACK(1.6/7.8 SEC) class Solution { public static long pairWithMaxSum(long arr[], long N) { long max=0; for(int i=0;i<N-1;i++) { if(arr[i]+arr[i+1]>max) { max=arr[i]+arr[i+1]; } } return max; }} 0 mashhadihossain1 month ago SIMPLE JAVA SOLUTION (1.9/7.8 SEC) class Solution { public static long pairWithMaxSum(long arr[], long N) { Stack<Long> stack=new Stack<Long>(); for(int i=0;i<N-1;i++) { stack.push(arr[i]+arr[i+1]); } long max=0; for(long x : stack) { if(x>max) { max=x; } } return max; }} 0 deveshamway3 months ago GFG has gone nuts...... why is this even a stack problem. This should be put in “basic” section of “Array”. SOL : long long pairWithMaxSum(long long arr[], long long N) { long long sum=0; for(int i = 0 ;i<N-1;i++){ if(sum<(arr[i]+arr[i+1])){ sum=arr[i]+arr[i+1]; } } return sum; } +1 kartikeyashokgautam3 months ago Java Solution using STACK :- public static long pairWithMaxSum(long arr[], long N) { Stack<Long> stack = new Stack<Long>(); for(int i=0;i<N-1;i++) { stack.push(arr[i]+arr[i+1]); } long max = stack.pop(); int j=0; while(j< N-2) { max=Math.max(max,stack.peek()); stack.pop(); j++; } return max; } +1 kartikeyashokgautam3 months ago JAVA Solution :- public static long pairWithMaxSum(long arr[], long N) { // Your code goes here long[] brr = new long[(int)N] ; for(int i =0;i<N-1;i++) { brr[i]=arr[i]+arr[i+1]; } long max=brr[0]; for(int j =1;j<N-1;j++) { if(brr[j]>max) { long temp = max; max=brr[j]; brr[j]=temp; } } return max; } 0 feyza3 months ago java public static long pairWithMaxSum(long arr[], long N) { long result = Integer.MIN_VALUE; Stack<Long> stack = new Stack<>(); for(int i=1; i<N; i++){ stack.push(arr[i]+arr[i-1]); if(result < stack.peek()) result = stack.peek(); stack.pop(); } return result; } +2 avinav26113 months ago Easiest C++ Solution +1 chessnoobdj4 months ago C++ long long pairWithMaxSum(long long arr[], long long N) { long long ans = INT_MIN; for(long long i=0; i<N-1; i++) ans = max(ans, arr[i]+arr[i+1]); return ans; } 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": 518, "s": 238, "text": "Given an array, find maximum sum of smallest and second smallest elements chosen from all possible sub-arrays. More formally, if we write all (nC2) sub-arrays of array of size >=2 and find the sum of smallest and second smallest, then our answer will be maximum sum among them.\n " }, { "code": null, "e": 529, "s": 518, "text": "Example 1:" }, { "code": null, "e": 1194, "s": 529, "text": "Input : arr[] = [4, 3, 1, 5, 6]\nOutput : 11\nSubarrays with smallest and \nsecond smallest are,\n[4, 3] \nsmallest = 3 second smallest = 4\n[4, 3, 1] \nsmallest = 1 second smallest = 3\n[4, 3, 1, 5] \nsmallest = 1 second smallest = 3\n[4, 3, 1, 5, 6] \nsmallest = 1 second smallest = 3\n[3, 1] \nsmallest = 1 second smallest = 3\n[3, 1, 5] \nsmallest = 1 second smallest = 3\n[3, 1, 5, 6] \nsmallest = 1 second smallest = 3\n[1, 5] \nsmallest = 1 second smallest = 5\n[1, 5, 6] \nsmallest = 1 second smallest = 5\n[5, 6] \nsmallest = 5 second smallest = 6\nMaximum sum among all \nabove choices is, 5 + 6 = 11" }, { "code": null, "e": 1238, "s": 1194, "text": "Input : arr[] = {5, 4, 3, 1, 6} \nOutput : 9" }, { "code": null, "e": 1619, "s": 1240, "text": "Your Task: \nYou don't need to read input or print anything. Your task is to complete the function pairWithMaxSum() which takes the array Arr[] and its size N as inputs and returns the maximum sum of smallest and second smallest elements chosen from all possible subarrays.\n\nExpected Time Complexity: O(N)\nExpected Auxiliary Space: O(1)\n\nConstraints:\n2 ≤ N ≤ 105\n1 ≤ A[i] ≤ 1018" }, { "code": null, "e": 1621, "s": 1619, "text": "0" }, { "code": null, "e": 1651, "s": 1621, "text": "prabhakarsati294262 weeks ago" }, { "code": null, "e": 1870, "s": 1651, "text": " def pairWithMaxSum(self, arr, N): # Your code goes here if (N<2): return -1 res = arr[0]+arr[1] for i in range(1,N-1): res = max(res,arr[i]+arr[i+1]) return res " }, { "code": null, "e": 1872, "s": 1870, "text": "0" }, { "code": null, "e": 1900, "s": 1872, "text": "abhishekabhi73521 month ago" }, { "code": null, "e": 2166, "s": 1900, "text": "class Solution { public static long pairWithMaxSum(long arr[], long N) { long max=0; for(int i=0;i<N-1;i++) { if(arr[i]+arr[i+1]>max) { max=arr[i]+arr[i+1]; } } return max; }}" }, { "code": null, "e": 2168, "s": 2166, "text": "0" }, { "code": null, "e": 2195, "s": 2168, "text": "mashhadihossain1 month ago" }, { "code": null, "e": 2243, "s": 2195, "text": "SIMPLE JAVA SOLUTION WITHOUT STACK(1.6/7.8 SEC)" }, { "code": null, "e": 2509, "s": 2243, "text": "class Solution { public static long pairWithMaxSum(long arr[], long N) { long max=0; for(int i=0;i<N-1;i++) { if(arr[i]+arr[i+1]>max) { max=arr[i]+arr[i+1]; } } return max; }}" }, { "code": null, "e": 2511, "s": 2509, "text": "0" }, { "code": null, "e": 2538, "s": 2511, "text": "mashhadihossain1 month ago" }, { "code": null, "e": 2573, "s": 2538, "text": "SIMPLE JAVA SOLUTION (1.9/7.8 SEC)" }, { "code": null, "e": 2928, "s": 2573, "text": "class Solution { public static long pairWithMaxSum(long arr[], long N) { Stack<Long> stack=new Stack<Long>(); for(int i=0;i<N-1;i++) { stack.push(arr[i]+arr[i+1]); } long max=0; for(long x : stack) { if(x>max) { max=x; } } return max; }}" }, { "code": null, "e": 2930, "s": 2928, "text": "0" }, { "code": null, "e": 2954, "s": 2930, "text": "deveshamway3 months ago" }, { "code": null, "e": 3012, "s": 2954, "text": "GFG has gone nuts...... why is this even a stack problem." }, { "code": null, "e": 3062, "s": 3012, "text": "This should be put in “basic” section of “Array”." }, { "code": null, "e": 3071, "s": 3064, "text": "SOL : " }, { "code": null, "e": 3302, "s": 3073, "text": "long long pairWithMaxSum(long long arr[], long long N) { long long sum=0; for(int i = 0 ;i<N-1;i++){ if(sum<(arr[i]+arr[i+1])){ sum=arr[i]+arr[i+1]; } } return sum; }" }, { "code": null, "e": 3305, "s": 3302, "text": "+1" }, { "code": null, "e": 3337, "s": 3305, "text": "kartikeyashokgautam3 months ago" }, { "code": null, "e": 3366, "s": 3337, "text": "Java Solution using STACK :-" }, { "code": null, "e": 3430, "s": 3368, "text": " public static long pairWithMaxSum(long arr[], long N) {" }, { "code": null, "e": 3804, "s": 3430, "text": " Stack<Long> stack = new Stack<Long>(); for(int i=0;i<N-1;i++) { stack.push(arr[i]+arr[i+1]); } long max = stack.pop(); int j=0; while(j< N-2) { max=Math.max(max,stack.peek()); stack.pop(); j++; } return max; }" }, { "code": null, "e": 3807, "s": 3804, "text": "+1" }, { "code": null, "e": 3839, "s": 3807, "text": "kartikeyashokgautam3 months ago" }, { "code": null, "e": 3857, "s": 3839, "text": "JAVA Solution :- " }, { "code": null, "e": 4315, "s": 3859, "text": " public static long pairWithMaxSum(long arr[], long N) { // Your code goes here long[] brr = new long[(int)N] ; for(int i =0;i<N-1;i++) { brr[i]=arr[i]+arr[i+1]; } long max=brr[0]; for(int j =1;j<N-1;j++) { if(brr[j]>max) { long temp = max; max=brr[j]; brr[j]=temp; } } return max; }" }, { "code": null, "e": 4317, "s": 4315, "text": "0" }, { "code": null, "e": 4335, "s": 4317, "text": "feyza3 months ago" }, { "code": null, "e": 4730, "s": 4335, "text": " java\n \n public static long pairWithMaxSum(long arr[], long N)\n {\n long result = Integer.MIN_VALUE;\n Stack<Long> stack = new Stack<>();\n for(int i=1; i<N; i++){\n stack.push(arr[i]+arr[i-1]);\n if(result < stack.peek())\n result = stack.peek();\n stack.pop(); \n }\n \n return result;\n }" }, { "code": null, "e": 4733, "s": 4730, "text": "+2" }, { "code": null, "e": 4756, "s": 4733, "text": "avinav26113 months ago" }, { "code": null, "e": 4777, "s": 4756, "text": "Easiest C++ Solution" }, { "code": null, "e": 4782, "s": 4779, "text": "+1" }, { "code": null, "e": 4806, "s": 4782, "text": "chessnoobdj4 months ago" }, { "code": null, "e": 4810, "s": 4806, "text": "C++" }, { "code": null, "e": 5014, "s": 4810, "text": "long long pairWithMaxSum(long long arr[], long long N)\n {\n long long ans = INT_MIN;\n for(long long i=0; i<N-1; i++)\n ans = max(ans, arr[i]+arr[i+1]);\n return ans;\n }" }, { "code": null, "e": 5160, "s": 5014, "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": 5196, "s": 5160, "text": " Login to access your submissions. " }, { "code": null, "e": 5206, "s": 5196, "text": "\nProblem\n" }, { "code": null, "e": 5216, "s": 5206, "text": "\nContest\n" }, { "code": null, "e": 5279, "s": 5216, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 5427, "s": 5279, "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": 5635, "s": 5427, "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": 5741, "s": 5635, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Why the constructor name is same as the class name in Java?
Every class object is created using the same new keyword, so it must have information about the class to which it must create an object. For this reason, the constructor name should be the same as the class name. class MyConstructor{ public MyConstructor() { System.out.println("The constructor name should be same as the class name"); } public static void main(String args[]){ MyConstructor mc = new MyConstructor(); } } In the above program, the constructor name should be the same as the class name (MyConstructor). The constructor name should be same as the class name
[ { "code": null, "e": 1275, "s": 1062, "text": "Every class object is created using the same new keyword, so it must have information about the class to which it must create an object. For this reason, the constructor name should be the same as the class name." }, { "code": null, "e": 1508, "s": 1275, "text": "class MyConstructor{\n public MyConstructor() {\n System.out.println(\"The constructor name should be same as the class name\");\n }\n public static void main(String args[]){\n MyConstructor mc = new MyConstructor();\n }\n}" }, { "code": null, "e": 1605, "s": 1508, "text": "In the above program, the constructor name should be the same as the class name (MyConstructor)." }, { "code": null, "e": 1659, "s": 1605, "text": "The constructor name should be same as the class name" } ]
How to use the PI constant in C++?
Here we will see how to use the PI constant in C++ program. The PI constant is present in the cmath header file. The name of the constant is M_PI. We can simply include that header file, and use the constant to perform operation. In the following example we will see how to find area of a circle using PI constant. #include <iostream> #include <cmath> using namespace std; float area(int radius) { return M_PI * (radius * radius); } int main () { cout << "Area of a circle with radius 7 unit is: " << area(7); } Area of a circle with radius 7 unit is: 153.938
[ { "code": null, "e": 1292, "s": 1062, "text": "Here we will see how to use the PI constant in C++ program. The PI constant is present in the cmath header file. The name of the constant is M_PI. We can simply include that header file, and use the constant to perform operation." }, { "code": null, "e": 1377, "s": 1292, "text": "In the following example we will see how to find area of a circle using PI constant." }, { "code": null, "e": 1580, "s": 1377, "text": "#include <iostream>\n#include <cmath>\nusing namespace std;\nfloat area(int radius) {\n return M_PI * (radius * radius);\n}\nint main () {\n cout << \"Area of a circle with radius 7 unit is: \" << area(7);\n}" }, { "code": null, "e": 1628, "s": 1580, "text": "Area of a circle with radius 7 unit is: 153.938" } ]
Print all prime numbers less than or equal to N in C++
In this problem, we are given a number N and we have to print all prime numbers less than or equal to N. Let’s take an example to understand the topic better − Input: 10 Output: 2 3 5 7 A prime number is a number that can be divided by only one and the number itself. Example: 2, 3. A simple approach is to iterate from 2 to N and divide the number by it. If the number is not divisible, then it’s a prime number. Print the number. Do this till the number is equal to N. This approach is not that efficient. A more effective approach will be checking for prime number by iterating from 2 to √N. Live Demo #include <bits/stdc++.h> using namespace std; bool isPrimeNumber(int n){ if (n <= 1) return false; if (n <= 3) return true; if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } void printPrime(int n){ for (int i = 2; i <= n; i++) { if (isPrimeNumber(i)) cout<<i<<" "; } } int main(){ int n = 41; cout<<"Prime numbers less than or equal to "<<n<<" are \n"; printPrime(n); } Prime numbers less than or equal to 41 are 2 3 5 7 11 13 17 19 23 29 31 37 41
[ { "code": null, "e": 1167, "s": 1062, "text": "In this problem, we are given a number N and we have to print all prime numbers less than or equal to N." }, { "code": null, "e": 1222, "s": 1167, "text": "Let’s take an example to understand the topic better −" }, { "code": null, "e": 1248, "s": 1222, "text": "Input: 10\nOutput: 2 3 5 7" }, { "code": null, "e": 1345, "s": 1248, "text": "A prime number is a number that can be divided by only one and the number itself. Example: 2, 3." }, { "code": null, "e": 1570, "s": 1345, "text": "A simple approach is to iterate from 2 to N and divide the number by it. If the number is not divisible, then it’s a prime number. Print the number. Do this till the number is equal to N. This approach is not that efficient." }, { "code": null, "e": 1657, "s": 1570, "text": "A more effective approach will be checking for prime number by iterating from 2 to √N." }, { "code": null, "e": 1668, "s": 1657, "text": " Live Demo" }, { "code": null, "e": 2220, "s": 1668, "text": "#include <bits/stdc++.h>\nusing namespace std;\nbool isPrimeNumber(int n){\n if (n <= 1)\n return false;\n if (n <= 3)\n return true;\n if (n % 2 == 0 || n % 3 == 0)\n return false;\n for (int i = 5; i * i <= n; i = i + 6)\n if (n % i == 0 || n % (i + 2) == 0)\n return false;\n return true;\n}\nvoid printPrime(int n){\n for (int i = 2; i <= n; i++) {\n if (isPrimeNumber(i))\n cout<<i<<\" \";\n }\n }\nint main(){\n int n = 41;\n cout<<\"Prime numbers less than or equal to \"<<n<<\" are \\n\";\n printPrime(n);\n}" }, { "code": null, "e": 2263, "s": 2220, "text": "Prime numbers less than or equal to 41 are" }, { "code": null, "e": 2298, "s": 2263, "text": "2 3 5 7 11 13 17 19 23 29 31 37 41" } ]
Simulation of 4-bit ALU
Moreover, we write an assembly program in 8085 assembly language just to simulate a 4-bit ALU by using an interface which is based on the logic controller. The Arithmetic Logical Unit always performs an addition, subtraction, AND operation, or OR operation, which is based on the 4-bit inputs for the desired operations to be performed. For the simulation of the Arithmetic Logical Unit all the terminal inputs and outputs are provided by the ports of 8255 as it is indicated in the figure below. The Pins ranging from 7-4 in the Port B are used as the inputs of X3-0; The pins ranging from 3-0 of Port B are used as the inputs ranging from Y3-0; Pins 7 and 6 of Port C used as S1 and S0 inputs; The port A pins of 3-0 are used as the output Z3-0; Pin 4 of Port A is used to provide Cy output in case of add and subtract operations. S1 and S0 inputs determine the operation to be performed by the ALU as per the table that follows. Here S1 and S0 are the inputs and Z is the output. ; FILE NAME ALU_PROG1.ASM ORG C000H PA EQU D8H PB EQU D9H PC EQU DAH CTRL EQU DBH MVI A, 10001010B OUT CTRL ; Configure 8255 ports LOOP: IN PB ; Input X and Y values through Port B MOV B, A ANI 0FH MOV C, A ; C will now have Y input MOV A, B ANI F0H RRC RRC RRC RRC MOV B, A ; B will now have X input IN PC ; Read S1 and S0 values from Port ANI 11000000B RLC RLC ; LS 2 bits of A will now have S1 and S0 CPI 00H JZ ADD ; If S1 = 0 and S0 = 0 do Add operation CPI 01H JZ SUB ; If S1 = 0 and S0 = 1 do Subtract operation CPI 02H JZ AND ; If S1 = 1 and S0 = 0 do AND operation OR: MOV A, B ORA C JMP DISP ADD: MOV A, B ADD C JMP DISP SUB: MOV A, B SUB C JMP DISP AND: MOV A, B ANA C DISP: OUT PA JMP LOOP
[ { "code": null, "e": 1399, "s": 1062, "text": "Moreover, we write an assembly program in 8085 assembly language just to simulate a 4-bit ALU by using an interface which is based on the logic controller. The Arithmetic Logical Unit always performs an addition, subtraction, AND operation, or OR operation, which is based on the 4-bit inputs for the desired operations to be performed." }, { "code": null, "e": 1559, "s": 1399, "text": "For the simulation of the Arithmetic Logical Unit all the terminal inputs and outputs are provided by the ports of 8255 as it is indicated in the figure below." }, { "code": null, "e": 1631, "s": 1559, "text": "The Pins ranging from 7-4 in the Port B are used as the inputs of X3-0;" }, { "code": null, "e": 1709, "s": 1631, "text": "The pins ranging from 3-0 of Port B are used as the inputs ranging from Y3-0;" }, { "code": null, "e": 1758, "s": 1709, "text": "Pins 7 and 6 of Port C used as S1 and S0 inputs;" }, { "code": null, "e": 1810, "s": 1758, "text": "The port A pins of 3-0 are used as the output Z3-0;" }, { "code": null, "e": 1895, "s": 1810, "text": "Pin 4 of Port A is used to provide Cy output in case of add and subtract operations." }, { "code": null, "e": 1994, "s": 1895, "text": "S1 and S0 inputs determine the operation to be performed by the ALU as per the table that follows." }, { "code": null, "e": 2045, "s": 1994, "text": "Here S1 and S0 are the inputs and Z is the output." }, { "code": null, "e": 2760, "s": 2045, "text": "; FILE NAME ALU_PROG1.ASM\nORG C000H\nPA EQU D8H\nPB EQU D9H\nPC EQU DAH\nCTRL EQU DBH\n\nMVI A, 10001010B\nOUT CTRL ; Configure 8255 ports\nLOOP: IN PB ; Input X and Y values through Port B\nMOV B, A\n\nANI 0FH\nMOV C, A ; C will now have Y input\n\nMOV A, B\nANI F0H\nRRC\nRRC\nRRC\nRRC\nMOV B, A ; B will now have X input\n\nIN PC ; Read S1 and S0 values from Port\nANI 11000000B\n\nRLC\nRLC ; LS 2 bits of A will now have S1 and S0\n\nCPI 00H\nJZ ADD ; If S1 = 0 and S0 = 0 do Add operation\n\nCPI 01H\nJZ SUB ; If S1 = 0 and S0 = 1 do Subtract operation\n\nCPI 02H\nJZ AND ; If S1 = 1 and S0 = 0 do AND operation\nOR: MOV A, B\nORA C\nJMP DISP\n\nADD: MOV A, B\nADD C\nJMP DISP\n\nSUB: MOV A, B\nSUB C\nJMP DISP\n\nAND: MOV A, B\nANA C\nDISP: OUT PA\nJMP LOOP\n\n" } ]
Pass arguments from array in PHP to constructor
The Reflection API can be used to pass arguments from array to constructor. The above line creates a new class instance from given arguments − public ReflectionClass::newInstanceArgs ([ array $args ] ) : object It creates a new instance of the class when the arguments are passed to the constructor. Here, args refers to the arguments that need to be passed to the class constructor. Live Demo <?php $my_class = new ReflectionClass('ReflectionFunction'); $my_instance = $my_class->newInstanceArgs(array('substr')); var_dump($my_instance); ?> This will produce the following output − object(ReflectionFunction)#2 (1) { ["name"]=> string(6) "substr" }
[ { "code": null, "e": 1138, "s": 1062, "text": "The Reflection API can be used to pass arguments from array to constructor." }, { "code": null, "e": 1205, "s": 1138, "text": "The above line creates a new class instance from given arguments −" }, { "code": null, "e": 1273, "s": 1205, "text": "public ReflectionClass::newInstanceArgs ([ array $args ] ) : object" }, { "code": null, "e": 1446, "s": 1273, "text": "It creates a new instance of the class when the arguments are passed to the constructor. Here, args refers to the arguments that need to be passed to the class constructor." }, { "code": null, "e": 1457, "s": 1446, "text": " Live Demo" }, { "code": null, "e": 1614, "s": 1457, "text": "<?php\n $my_class = new ReflectionClass('ReflectionFunction');\n $my_instance = $my_class->newInstanceArgs(array('substr'));\n var_dump($my_instance);\n?>" }, { "code": null, "e": 1655, "s": 1614, "text": "This will produce the following output −" }, { "code": null, "e": 1722, "s": 1655, "text": "object(ReflectionFunction)#2 (1) { [\"name\"]=> string(6) \"substr\" }" } ]
Machine Learning — Text Processing | by Javaid Nabi | Towards Data Science
Text Processing is one of the most common task in many ML applications. Below are some examples of such applications. • Language Translation: Translation of a sentence from one language to another.• Sentiment Analysis: To determine, from a text corpus, whether the sentiment towards any topic or product etc. is positive, negative, or neutral.• Spam Filtering: Detect unsolicited and unwanted email/messages. These applications deal with huge amount of text to perform classification or translation and involves a lot of work on the back end. Transforming text into something an algorithm can digest is a complicated process. In this article, we will discuss the steps involved in text processing. Tokenization — convert sentences to words Removing unnecessary punctuation, tags Removing stop words — frequent words such as ”the”, ”is”, etc. that do not have specific semantic Stemming — words are reduced to a root by removing inflection through dropping unnecessary characters, usually a suffix. Lemmatization — Another approach to remove inflection by determining the part of speech and utilizing detailed database of the language. The stemmed form of studies is: studiThe stemmed form of studying is: studyThe lemmatized form of studies is: studyThe lemmatized form of studying is: study Thus stemming & lemmatization help reduce words like ‘studies’, ‘studying’ to a common base form or root word ‘study’. For detailed discussion on Stemming & Lemmatization refer here . Note that not all the steps are mandatory and is based on the application use case. For Spam Filtering we may follow all the above steps but may not for language translation problem. We can use python to do many text preprocessing operations. NLTK — The Natural Language ToolKit is one of the best-known and most-used NLP libraries, useful for all sorts of tasks from t tokenization, stemming, tagging, parsing, and beyond BeautifulSoup — Library for extracting data from HTML and XML documents #using NLTK library, we can do lot of text preprocesingimport nltkfrom nltk.tokenize import word_tokenize#function to split text into wordtokens = word_tokenize("The quick brown fox jumps over the lazy dog")nltk.download('stopwords')print(tokens) OUT: [‘The’, ‘quick’, ‘brown’, ‘fox’, ‘jumps’, ‘over’, ‘the’, ‘lazy’, ‘dog’] from nltk.corpus import stopwordsstop_words = set(stopwords.words(‘english’))tokens = [w for w in tokens if not w in stop_words]print(tokens) OUT: [‘The’, ‘quick’, ‘brown’, ‘fox’, ‘jumps’, ‘lazy’, ‘dog’] #NLTK provides several stemmer interfaces like Porter stemmer, #Lancaster Stemmer, Snowball Stemmerfrom nltk.stem.porter import PorterStemmerporter = PorterStemmer()stems = []for t in tokens: stems.append(porter.stem(t))print(stems) OUT: [‘the’, ‘quick’, ‘brown’, ‘fox’, ‘jump’, ‘lazi’, ‘dog’] In text processing, words of the text represent discrete, categorical features. How do we encode such data in a way which is ready to be used by the algorithms? The mapping from textual data to real valued vectors is called feature extraction. One of the simplest techniques to numerically represent text is Bag of Words. Bag of Words (BOW): We make the list of unique words in the text corpus called vocabulary. Then we can represent each sentence or document as a vector with each word represented as 1 for present and 0 for absent from the vocabulary. Another representation can be count the number of times each word appears in a document. The most popular approach is using the Term Frequency-Inverse Document Frequency (TF-IDF) technique. Term Frequency (TF) = (Number of times term t appears in a document)/(Number of terms in the document) Inverse Document Frequency (IDF) = log(N/n), where, N is the number of documents and n is the number of documents a term t has appeared in. The IDF of a rare word is high, whereas the IDF of a frequent word is likely to be low. Thus having the effect of highlighting words that are distinct. We calculate TF-IDF value of a term as = TF * IDF Let us take an example to calculate TF-IDF of a term in a document. TF('beautiful',Document1) = 2/10, IDF('beautiful')=log(2/2) = 0TF(‘day’,Document1) = 5/10, IDF(‘day’)=log(2/1) = 0.30TF-IDF(‘beautiful’, Document1) = (2/10)*0 = 0TF-IDF(‘day’, Document1) = (5/10)*0.30 = 0.15 As, you can see for Document1 , TF-IDF method heavily penalizes the word ‘beautiful’ but assigns greater weight to ‘day’. This is due to IDF part, which gives more weightage to the words that are distinct. In other words, ‘day’ is an important word for Document1 from the context of the entire corpus. Python scikit-learn library provides efficient tools for text data mining and provides functions to calculate TF-IDF of text vocabulary given a text corpus. One of the major disadvantages of using BOW is that it discards word order thereby ignoring the context and in turn meaning of words in the document. For natural language processing (NLP) maintaining the context of the words is of utmost importance. To solve this problem we use another approach called Word Embedding. Word Embedding: It is a representation of text where words that have the same meaning have a similar representation. In other words it represents words in a coordinate system where related words, based on a corpus of relationships, are placed closer together. Let us discuss some of the well known models of word embedding: Word2vec takes as its input a large corpus of text and produces a vector space with each unique word being assigned a corresponding vector in the space. Word vectors are positioned in the vector space such that words that share common contexts in the corpus are located in close proximity to one another in the space. Word2Vec is very famous at capturing meaning and demonstrating it on tasks like calculating analogy questions of the form a is to b as c is to ?. For example, man is to woman as uncle is to ? (aunt) using a simple vector offset method based on cosine distance. For example, here are vector offsets for three word pairs illustrating the gender relation: This kind of vector composition also lets us answer “King — Man + Woman = ?” question and arrive at the result “Queen” ! All of which is truly remarkable when you think that all of this knowledge simply comes from looking at lots of word in context with no other information provided about their semantics. For more details refer here. The Global Vectors for Word Representation, or GloVe, algorithm is an extension to the word2vec method for efficiently learning word vectors. GloVe constructs an explicit word-context or word co-occurrence matrix using statistics across the whole text corpus. The result is a learning model that may result in generally better word embeddings. Consider the following example: Target words: ice, steamProbe words: solid, gas, water, fashion Let P(k|w) be the probability that the word k appears in the context of word w. Consider a word strongly related to ice, but not to steam, such as solid. P(solid | ice) will be relatively high, and P(solid | steam) will be relatively low. Thus the ratio of P(solid | ice) / P(solid | steam) will be large. If we take a word such as gas that is related to steam but not to ice, the ratio of P(gas | ice) / P(gas | steam) will instead be small. For a word related to both ice and steam, such as water we expect the ratio to be close to one. Refer here for more details. Word embeddings encode each word into a vector that captures some sort of relation and similarity between words within the text corpus. This means even the variations of words like case, spelling, punctuation, and so on will be automatically learned. In turn, this can mean that some of the text cleaning steps described above may no longer be required. There are various approaches to building ML models for various text based applications depending on what is the problem space and data available. Classical ML approaches like ‘Naive Bayes’ or ‘Support Vector Machines’ for spam filtering has been widely used. Deep learning techniques are giving better results for NLP problems like sentiment analysis and language translation. Deep learning models are very slow to train and it has been seen that for simple text classification problems classical ML approaches as well give similar results with quicker training time. Let us build a Sentiment Analyzer over the IMDB movie review dataset using the techniques discussed so far. The IMDB movie review set can be downloaded from here. This dataset for binary sentiment classification contains set of 25,000 highly polar movie reviews for training, and 25,000 for testing. This dataset was used for the very popular paper ‘Learning Word Vectors for Sentiment Analysis’. The dataset is structured as test set and training set of 25000 files each. Let us first read the files into a python dataframe for further processing and visualization. The test and training set are further divided into 12500 ‘positive’ and ‘negative’ reviews each. We read each file and label negative review as ‘0’ and positive review as ‘1’ #convert the dataset from files to a python DataFrameimport pandas as pdimport osfolder = 'aclImdb'labels = {'pos': 1, 'neg': 0}df = pd.DataFrame()for f in ('test', 'train'): for l in ('pos', 'neg'): path = os.path.join(folder, f, l) for file in os.listdir (path) : with open(os.path.join(path, file),'r', encoding='utf-8') as infile: txt = infile.read() df = df.append([[txt, labels[l]]],ignore_index=True)df.columns = ['review', 'sentiment'] Let us save the assembled data as .csv file for further use. To get the frequency distribution of the words in the text, we can utilize the nltk.FreqDist() function, which lists the top words used in the text, providing a rough idea of the main topic in the text data, as shown in the following code: import nltkfrom nltk.tokenize import word_tokenizereviews = df.review.str.cat(sep=' ')#function to split text into wordtokens = word_tokenize(reviews)vocabulary = set(tokens)print(len(vocabulary))frequency_dist = nltk.FreqDist(tokens)sorted(frequency_dist,key=frequency_dist.__getitem__, reverse=True)[0:50] This gives the top 50 words used in the text, though it is obvious that some of the stop words, such as the, frequently occur in the English language. Look closely and you find lot of unnecessary punctuation and tags. By excluding single and two letter words the stop words like the, this, and, that take the top slot in the word frequency distribution plot shown below. Let us remove the stop words to further cleanup the text corpus. from nltk.corpus import stopwordsstop_words = set(stopwords.words('english'))tokens = [w for w in tokens if not w in stop_words] This looks like a cleaned text corpus now and words like went, saw, movie etc. taking the top slots as expected. Another helpful visualization tool wordcloud package helps to create word clouds by placing words on a canvas randomly, with sizes proportional to their frequency in the text. from wordcloud import WordCloudimport matplotlib.pyplot as pltwordcloud = WordCloud().generate_from_frequencies(frequency_dist)plt.imshow(wordcloud)plt.axis("off")plt.show() After cleanup, it is time to build the classifier to identify sentiment of each movie review. From the IMDb dataset, divide test and training sets of 25000 each: X_train = df.loc[:24999, 'review'].valuesy_train = df.loc[:24999, 'sentiment'].valuesX_test = df.loc[25000:, 'review'].valuesy_test = df.loc[25000:, 'sentiment'].values scikit-learn provides some cool tools to do pre-processing on text. We use TfidTransformer to covert the text corpus into the feature vectors, we restrict the maximum features to 10000. For further details about how to useTfidTransformerrefer here. from sklearn.feature_extraction.text import TfidfTransformerfrom sklearn.feature_extraction.text import TfidfVectorizervectorizer = TfidfVectorizer()train_vectors = vectorizer.fit_transform(X_train)test_vectors = vectorizer.transform(X_test)print(train_vectors.shape, test_vectors.shape) There are many algorithms to choose from, we will use a basic Naive Bayes Classifier and train the model on the training set. from sklearn.naive_bayes import MultinomialNBclf = MultinomialNB().fit(train_vectors, y_train) Our Sentiment Analyzer is ready and trained. Now let us test the performance of our model on the test set to predict the sentiment labels. from sklearn.metrics import accuracy_scorepredicted = clf.predict(test_vectors)print(accuracy_score(y_test,predicted))Output 0.791 Wow!!! Basic NB classifier based Sentiment Analyzer does well to give around 79% accuracy. You can try changing features vector length and varying parameters ofTfidTransformerto see the impact on the accuracy of the model. Conclusion: We have discussed the text processing techniques used in NLP in detail. We also demonstrated the use of text processing and build a Sentiment Analyzer with classical ML approach achieved fairly good results. Thanks for reading this article, recommend and share if you like it.
[ { "code": null, "e": 290, "s": 172, "text": "Text Processing is one of the most common task in many ML applications. Below are some examples of such applications." }, { "code": null, "e": 583, "s": 290, "text": "• Language Translation: Translation of a sentence from one language to another.• Sentiment Analysis: To determine, from a text corpus, whether the sentiment towards any topic or product etc. is positive, negative, or neutral.• Spam Filtering: Detect unsolicited and unwanted email/messages." }, { "code": null, "e": 872, "s": 583, "text": "These applications deal with huge amount of text to perform classification or translation and involves a lot of work on the back end. Transforming text into something an algorithm can digest is a complicated process. In this article, we will discuss the steps involved in text processing." }, { "code": null, "e": 914, "s": 872, "text": "Tokenization — convert sentences to words" }, { "code": null, "e": 953, "s": 914, "text": "Removing unnecessary punctuation, tags" }, { "code": null, "e": 1051, "s": 953, "text": "Removing stop words — frequent words such as ”the”, ”is”, etc. that do not have specific semantic" }, { "code": null, "e": 1172, "s": 1051, "text": "Stemming — words are reduced to a root by removing inflection through dropping unnecessary characters, usually a suffix." }, { "code": null, "e": 1309, "s": 1172, "text": "Lemmatization — Another approach to remove inflection by determining the part of speech and utilizing detailed database of the language." }, { "code": null, "e": 1466, "s": 1309, "text": "The stemmed form of studies is: studiThe stemmed form of studying is: studyThe lemmatized form of studies is: studyThe lemmatized form of studying is: study" }, { "code": null, "e": 1833, "s": 1466, "text": "Thus stemming & lemmatization help reduce words like ‘studies’, ‘studying’ to a common base form or root word ‘study’. For detailed discussion on Stemming & Lemmatization refer here . Note that not all the steps are mandatory and is based on the application use case. For Spam Filtering we may follow all the above steps but may not for language translation problem." }, { "code": null, "e": 1893, "s": 1833, "text": "We can use python to do many text preprocessing operations." }, { "code": null, "e": 2073, "s": 1893, "text": "NLTK — The Natural Language ToolKit is one of the best-known and most-used NLP libraries, useful for all sorts of tasks from t tokenization, stemming, tagging, parsing, and beyond" }, { "code": null, "e": 2145, "s": 2073, "text": "BeautifulSoup — Library for extracting data from HTML and XML documents" }, { "code": null, "e": 2392, "s": 2145, "text": "#using NLTK library, we can do lot of text preprocesingimport nltkfrom nltk.tokenize import word_tokenize#function to split text into wordtokens = word_tokenize(\"The quick brown fox jumps over the lazy dog\")nltk.download('stopwords')print(tokens)" }, { "code": null, "e": 2469, "s": 2392, "text": "OUT: [‘The’, ‘quick’, ‘brown’, ‘fox’, ‘jumps’, ‘over’, ‘the’, ‘lazy’, ‘dog’]" }, { "code": null, "e": 2611, "s": 2469, "text": "from nltk.corpus import stopwordsstop_words = set(stopwords.words(‘english’))tokens = [w for w in tokens if not w in stop_words]print(tokens)" }, { "code": null, "e": 2673, "s": 2611, "text": "OUT: [‘The’, ‘quick’, ‘brown’, ‘fox’, ‘jumps’, ‘lazy’, ‘dog’]" }, { "code": null, "e": 2913, "s": 2673, "text": "#NLTK provides several stemmer interfaces like Porter stemmer, #Lancaster Stemmer, Snowball Stemmerfrom nltk.stem.porter import PorterStemmerporter = PorterStemmer()stems = []for t in tokens: stems.append(porter.stem(t))print(stems)" }, { "code": null, "e": 2974, "s": 2913, "text": "OUT: [‘the’, ‘quick’, ‘brown’, ‘fox’, ‘jump’, ‘lazi’, ‘dog’]" }, { "code": null, "e": 3296, "s": 2974, "text": "In text processing, words of the text represent discrete, categorical features. How do we encode such data in a way which is ready to be used by the algorithms? The mapping from textual data to real valued vectors is called feature extraction. One of the simplest techniques to numerically represent text is Bag of Words." }, { "code": null, "e": 3719, "s": 3296, "text": "Bag of Words (BOW): We make the list of unique words in the text corpus called vocabulary. Then we can represent each sentence or document as a vector with each word represented as 1 for present and 0 for absent from the vocabulary. Another representation can be count the number of times each word appears in a document. The most popular approach is using the Term Frequency-Inverse Document Frequency (TF-IDF) technique." }, { "code": null, "e": 3822, "s": 3719, "text": "Term Frequency (TF) = (Number of times term t appears in a document)/(Number of terms in the document)" }, { "code": null, "e": 4114, "s": 3822, "text": "Inverse Document Frequency (IDF) = log(N/n), where, N is the number of documents and n is the number of documents a term t has appeared in. The IDF of a rare word is high, whereas the IDF of a frequent word is likely to be low. Thus having the effect of highlighting words that are distinct." }, { "code": null, "e": 4164, "s": 4114, "text": "We calculate TF-IDF value of a term as = TF * IDF" }, { "code": null, "e": 4232, "s": 4164, "text": "Let us take an example to calculate TF-IDF of a term in a document." }, { "code": null, "e": 4441, "s": 4232, "text": "TF('beautiful',Document1) = 2/10, IDF('beautiful')=log(2/2) = 0TF(‘day’,Document1) = 5/10, IDF(‘day’)=log(2/1) = 0.30TF-IDF(‘beautiful’, Document1) = (2/10)*0 = 0TF-IDF(‘day’, Document1) = (5/10)*0.30 = 0.15" }, { "code": null, "e": 4900, "s": 4441, "text": "As, you can see for Document1 , TF-IDF method heavily penalizes the word ‘beautiful’ but assigns greater weight to ‘day’. This is due to IDF part, which gives more weightage to the words that are distinct. In other words, ‘day’ is an important word for Document1 from the context of the entire corpus. Python scikit-learn library provides efficient tools for text data mining and provides functions to calculate TF-IDF of text vocabulary given a text corpus." }, { "code": null, "e": 5219, "s": 4900, "text": "One of the major disadvantages of using BOW is that it discards word order thereby ignoring the context and in turn meaning of words in the document. For natural language processing (NLP) maintaining the context of the words is of utmost importance. To solve this problem we use another approach called Word Embedding." }, { "code": null, "e": 5479, "s": 5219, "text": "Word Embedding: It is a representation of text where words that have the same meaning have a similar representation. In other words it represents words in a coordinate system where related words, based on a corpus of relationships, are placed closer together." }, { "code": null, "e": 5543, "s": 5479, "text": "Let us discuss some of the well known models of word embedding:" }, { "code": null, "e": 6214, "s": 5543, "text": "Word2vec takes as its input a large corpus of text and produces a vector space with each unique word being assigned a corresponding vector in the space. Word vectors are positioned in the vector space such that words that share common contexts in the corpus are located in close proximity to one another in the space. Word2Vec is very famous at capturing meaning and demonstrating it on tasks like calculating analogy questions of the form a is to b as c is to ?. For example, man is to woman as uncle is to ? (aunt) using a simple vector offset method based on cosine distance. For example, here are vector offsets for three word pairs illustrating the gender relation:" }, { "code": null, "e": 6550, "s": 6214, "text": "This kind of vector composition also lets us answer “King — Man + Woman = ?” question and arrive at the result “Queen” ! All of which is truly remarkable when you think that all of this knowledge simply comes from looking at lots of word in context with no other information provided about their semantics. For more details refer here." }, { "code": null, "e": 6894, "s": 6550, "text": "The Global Vectors for Word Representation, or GloVe, algorithm is an extension to the word2vec method for efficiently learning word vectors. GloVe constructs an explicit word-context or word co-occurrence matrix using statistics across the whole text corpus. The result is a learning model that may result in generally better word embeddings." }, { "code": null, "e": 6926, "s": 6894, "text": "Consider the following example:" }, { "code": null, "e": 6990, "s": 6926, "text": "Target words: ice, steamProbe words: solid, gas, water, fashion" }, { "code": null, "e": 7558, "s": 6990, "text": "Let P(k|w) be the probability that the word k appears in the context of word w. Consider a word strongly related to ice, but not to steam, such as solid. P(solid | ice) will be relatively high, and P(solid | steam) will be relatively low. Thus the ratio of P(solid | ice) / P(solid | steam) will be large. If we take a word such as gas that is related to steam but not to ice, the ratio of P(gas | ice) / P(gas | steam) will instead be small. For a word related to both ice and steam, such as water we expect the ratio to be close to one. Refer here for more details." }, { "code": null, "e": 7912, "s": 7558, "text": "Word embeddings encode each word into a vector that captures some sort of relation and similarity between words within the text corpus. This means even the variations of words like case, spelling, punctuation, and so on will be automatically learned. In turn, this can mean that some of the text cleaning steps described above may no longer be required." }, { "code": null, "e": 8058, "s": 7912, "text": "There are various approaches to building ML models for various text based applications depending on what is the problem space and data available." }, { "code": null, "e": 8480, "s": 8058, "text": "Classical ML approaches like ‘Naive Bayes’ or ‘Support Vector Machines’ for spam filtering has been widely used. Deep learning techniques are giving better results for NLP problems like sentiment analysis and language translation. Deep learning models are very slow to train and it has been seen that for simple text classification problems classical ML approaches as well give similar results with quicker training time." }, { "code": null, "e": 8588, "s": 8480, "text": "Let us build a Sentiment Analyzer over the IMDB movie review dataset using the techniques discussed so far." }, { "code": null, "e": 8877, "s": 8588, "text": "The IMDB movie review set can be downloaded from here. This dataset for binary sentiment classification contains set of 25,000 highly polar movie reviews for training, and 25,000 for testing. This dataset was used for the very popular paper ‘Learning Word Vectors for Sentiment Analysis’." }, { "code": null, "e": 9222, "s": 8877, "text": "The dataset is structured as test set and training set of 25000 files each. Let us first read the files into a python dataframe for further processing and visualization. The test and training set are further divided into 12500 ‘positive’ and ‘negative’ reviews each. We read each file and label negative review as ‘0’ and positive review as ‘1’" }, { "code": null, "e": 9724, "s": 9222, "text": "#convert the dataset from files to a python DataFrameimport pandas as pdimport osfolder = 'aclImdb'labels = {'pos': 1, 'neg': 0}df = pd.DataFrame()for f in ('test', 'train'): for l in ('pos', 'neg'): path = os.path.join(folder, f, l) for file in os.listdir (path) : with open(os.path.join(path, file),'r', encoding='utf-8') as infile: txt = infile.read() df = df.append([[txt, labels[l]]],ignore_index=True)df.columns = ['review', 'sentiment']" }, { "code": null, "e": 9785, "s": 9724, "text": "Let us save the assembled data as .csv file for further use." }, { "code": null, "e": 10025, "s": 9785, "text": "To get the frequency distribution of the words in the text, we can utilize the nltk.FreqDist() function, which lists the top words used in the text, providing a rough idea of the main topic in the text data, as shown in the following code:" }, { "code": null, "e": 10333, "s": 10025, "text": "import nltkfrom nltk.tokenize import word_tokenizereviews = df.review.str.cat(sep=' ')#function to split text into wordtokens = word_tokenize(reviews)vocabulary = set(tokens)print(len(vocabulary))frequency_dist = nltk.FreqDist(tokens)sorted(frequency_dist,key=frequency_dist.__getitem__, reverse=True)[0:50]" }, { "code": null, "e": 10484, "s": 10333, "text": "This gives the top 50 words used in the text, though it is obvious that some of the stop words, such as the, frequently occur in the English language." }, { "code": null, "e": 10704, "s": 10484, "text": "Look closely and you find lot of unnecessary punctuation and tags. By excluding single and two letter words the stop words like the, this, and, that take the top slot in the word frequency distribution plot shown below." }, { "code": null, "e": 10769, "s": 10704, "text": "Let us remove the stop words to further cleanup the text corpus." }, { "code": null, "e": 10898, "s": 10769, "text": "from nltk.corpus import stopwordsstop_words = set(stopwords.words('english'))tokens = [w for w in tokens if not w in stop_words]" }, { "code": null, "e": 11011, "s": 10898, "text": "This looks like a cleaned text corpus now and words like went, saw, movie etc. taking the top slots as expected." }, { "code": null, "e": 11187, "s": 11011, "text": "Another helpful visualization tool wordcloud package helps to create word clouds by placing words on a canvas randomly, with sizes proportional to their frequency in the text." }, { "code": null, "e": 11361, "s": 11187, "text": "from wordcloud import WordCloudimport matplotlib.pyplot as pltwordcloud = WordCloud().generate_from_frequencies(frequency_dist)plt.imshow(wordcloud)plt.axis(\"off\")plt.show()" }, { "code": null, "e": 11523, "s": 11361, "text": "After cleanup, it is time to build the classifier to identify sentiment of each movie review. From the IMDb dataset, divide test and training sets of 25000 each:" }, { "code": null, "e": 11692, "s": 11523, "text": "X_train = df.loc[:24999, 'review'].valuesy_train = df.loc[:24999, 'sentiment'].valuesX_test = df.loc[25000:, 'review'].valuesy_test = df.loc[25000:, 'sentiment'].values" }, { "code": null, "e": 11941, "s": 11692, "text": "scikit-learn provides some cool tools to do pre-processing on text. We use TfidTransformer to covert the text corpus into the feature vectors, we restrict the maximum features to 10000. For further details about how to useTfidTransformerrefer here." }, { "code": null, "e": 12229, "s": 11941, "text": "from sklearn.feature_extraction.text import TfidfTransformerfrom sklearn.feature_extraction.text import TfidfVectorizervectorizer = TfidfVectorizer()train_vectors = vectorizer.fit_transform(X_train)test_vectors = vectorizer.transform(X_test)print(train_vectors.shape, test_vectors.shape)" }, { "code": null, "e": 12355, "s": 12229, "text": "There are many algorithms to choose from, we will use a basic Naive Bayes Classifier and train the model on the training set." }, { "code": null, "e": 12450, "s": 12355, "text": "from sklearn.naive_bayes import MultinomialNBclf = MultinomialNB().fit(train_vectors, y_train)" }, { "code": null, "e": 12589, "s": 12450, "text": "Our Sentiment Analyzer is ready and trained. Now let us test the performance of our model on the test set to predict the sentiment labels." }, { "code": null, "e": 12722, "s": 12589, "text": "from sklearn.metrics import accuracy_scorepredicted = clf.predict(test_vectors)print(accuracy_score(y_test,predicted))Output 0.791" }, { "code": null, "e": 12945, "s": 12722, "text": "Wow!!! Basic NB classifier based Sentiment Analyzer does well to give around 79% accuracy. You can try changing features vector length and varying parameters ofTfidTransformerto see the impact on the accuracy of the model." }, { "code": null, "e": 13165, "s": 12945, "text": "Conclusion: We have discussed the text processing techniques used in NLP in detail. We also demonstrated the use of text processing and build a Sentiment Analyzer with classical ML approach achieved fairly good results." } ]
Linux and Unix Test Disk I/O Performance with DD Command
Do you know how to check the performance of a hard drive like checking the read and write speed on your Linux operating systems? then, this article is for you!! which is basically created to provide you an overview of DD command, which is geared towards better guidance to new users and as an exploration tour for getting started to the Linux world. DD is a command-line utility for Unix and Unix-like operating systems where the primary purpose is to copy a file and converting the format of the data during the process. Open your Linux root terminal and add the following command- $ sudo dd if=/dev/zero of=/tmp/test1.img bs=1G count=1 oflag=dsync Output should be like this- tp@linux:~$ sudo dd if=/dev/zero of=/tmp/test1.img bs=1G count=1 oflag=dsync [sudo] password for tp: 1+0 records in 1+0 records out 1073741824 bytes (1.1 GB) copied, 11.9635 s, 89.8 MB/s tp@linux:~$ Please note that, 1GB is copied during the test and 89.8 MB/second is served throughout fthe test. Chunks of DD command should be like this – Before testing the first flush caches data, use the following command- $ echo 3 | sudo tee /proc/sys/vm/drop_caches time time dd if=/path/to/bigfile of=/dev/null bs=8k Run the following command to test the data with cache- tp@linux:~$ dd if=/dev/zero of=/tmp/laptop.bin bs=1G count=1 oflag=direct 1+0 records in 1+0 records out 1073741824 bytes (1.1 GB) copied, 11.4265 s, 94.0 MB/s The above command copies 1.1GB of data and 94.0 MB/s is served for the test. To deactivate cache, use the following command – $ sudo hdparm -W0 /dev/sda The output should be like this – tp@linux:~$ sudo hdparm -W0 /dev/sda /dev/sda: setting drive write-caching to 0 (off) write-caching = 0 (off) Run the following command to test the data without cache - $ dd if=/dev/zero of=/tmp/laptop.bin bs=1G count=1 oflag=direct The output should be like this – tp@linux:~$ dd if=/dev/zero of=/tmp/laptop.bin bs=1G count=1 oflag=direct 1+0 records in 1+0 records out 1073741824 bytes (1.1 GB) copied, 11.5062 s, 93.3 MB/s The above command copies 1.1GB of data and 93.3 MB/s is served for the test. Congratulations! Now, you know how to test the disk I/O Performance with DD Command. In our next articles, we will come up with more Linux based tricks and tips. Keep reading!
[ { "code": null, "e": 1412, "s": 1062, "text": "Do you know how to check the performance of a hard drive like checking the read and write speed on your Linux operating systems? then, this article is for you!! which is basically created to provide you an overview of DD command, which is geared towards better guidance to new users and as an exploration tour for getting started to the Linux world." }, { "code": null, "e": 1584, "s": 1412, "text": "DD is a command-line utility for Unix and Unix-like operating systems where the primary purpose is to copy a file and converting the format of the data during the process." }, { "code": null, "e": 1645, "s": 1584, "text": "Open your Linux root terminal and add the following command-" }, { "code": null, "e": 1712, "s": 1645, "text": "$ sudo dd if=/dev/zero of=/tmp/test1.img bs=1G count=1 oflag=dsync" }, { "code": null, "e": 1740, "s": 1712, "text": "Output should be like this-" }, { "code": null, "e": 1939, "s": 1740, "text": "tp@linux:~$ sudo dd if=/dev/zero of=/tmp/test1.img bs=1G count=1 oflag=dsync\n[sudo] password for tp:\n1+0 records in\n1+0 records out\n1073741824 bytes (1.1 GB) copied, 11.9635 s, 89.8 MB/s\ntp@linux:~$" }, { "code": null, "e": 2038, "s": 1939, "text": "Please note that, 1GB is copied during the test and 89.8 MB/second is served throughout fthe test." }, { "code": null, "e": 2081, "s": 2038, "text": "Chunks of DD command should be like this –" }, { "code": null, "e": 2152, "s": 2081, "text": "Before testing the first flush caches data, use the following command-" }, { "code": null, "e": 2249, "s": 2152, "text": "$ echo 3 | sudo tee /proc/sys/vm/drop_caches\ntime time dd if=/path/to/bigfile of=/dev/null bs=8k" }, { "code": null, "e": 2304, "s": 2249, "text": "Run the following command to test the data with cache-" }, { "code": null, "e": 2464, "s": 2304, "text": "tp@linux:~$ dd if=/dev/zero of=/tmp/laptop.bin bs=1G count=1 oflag=direct\n1+0 records in\n1+0 records out\n1073741824 bytes (1.1 GB) copied, 11.4265 s, 94.0 MB/s" }, { "code": null, "e": 2541, "s": 2464, "text": "The above command copies 1.1GB of data and 94.0 MB/s is served for the test." }, { "code": null, "e": 2590, "s": 2541, "text": "To deactivate cache, use the following command –" }, { "code": null, "e": 2617, "s": 2590, "text": "$ sudo hdparm -W0 /dev/sda" }, { "code": null, "e": 2650, "s": 2617, "text": "The output should be like this –" }, { "code": null, "e": 2760, "s": 2650, "text": "tp@linux:~$ sudo hdparm -W0 /dev/sda\n/dev/sda:\nsetting drive write-caching to 0 (off)\nwrite-caching = 0 (off)" }, { "code": null, "e": 2819, "s": 2760, "text": "Run the following command to test the data without cache -" }, { "code": null, "e": 2883, "s": 2819, "text": "$ dd if=/dev/zero of=/tmp/laptop.bin bs=1G count=1 oflag=direct" }, { "code": null, "e": 2916, "s": 2883, "text": "The output should be like this –" }, { "code": null, "e": 3076, "s": 2916, "text": "tp@linux:~$ dd if=/dev/zero of=/tmp/laptop.bin bs=1G count=1 oflag=direct\n1+0 records in\n1+0 records out\n1073741824 bytes (1.1 GB) copied, 11.5062 s, 93.3 MB/s" }, { "code": null, "e": 3153, "s": 3076, "text": "The above command copies 1.1GB of data and 93.3 MB/s is served for the test." }, { "code": null, "e": 3329, "s": 3153, "text": "Congratulations! Now, you know how to test the disk I/O Performance with DD Command. In our next articles, we will come up with more Linux based tricks and tips. Keep reading!" } ]
Python dictionary len() Method
Python dictionary method len() gives the total length of the dictionary. This would be equal to the number of items in the dictionary. Following is the syntax for len() method − len(dict) dict − This is the dictionary, whose length needs to be calculated. dict − This is the dictionary, whose length needs to be calculated. This method returns the length. The following example shows the usage of len() method. #!/usr/bin/python dict = {'Name': 'Zara', 'Age': 7}; print "Length : %d" % len (dict) When we run above program, it produces following result − Length : 2 187 Lectures 17.5 hours Malhar Lathkar 55 Lectures 8 hours Arnab Chakraborty 136 Lectures 11 hours In28Minutes Official 75 Lectures 13 hours Eduonix Learning Solutions 70 Lectures 8.5 hours Lets Kode It 63 Lectures 6 hours Abhilash Nelson Print Add Notes Bookmark this page
[ { "code": null, "e": 2380, "s": 2244, "text": "Python dictionary method len() gives the total length of the dictionary. This would be equal to the number of items in the dictionary." }, { "code": null, "e": 2423, "s": 2380, "text": "Following is the syntax for len() method −" }, { "code": null, "e": 2434, "s": 2423, "text": "len(dict)\n" }, { "code": null, "e": 2502, "s": 2434, "text": "dict − This is the dictionary, whose length needs to be calculated." }, { "code": null, "e": 2570, "s": 2502, "text": "dict − This is the dictionary, whose length needs to be calculated." }, { "code": null, "e": 2602, "s": 2570, "text": "This method returns the length." }, { "code": null, "e": 2657, "s": 2602, "text": "The following example shows the usage of len() method." }, { "code": null, "e": 2744, "s": 2657, "text": "#!/usr/bin/python\n\ndict = {'Name': 'Zara', 'Age': 7};\nprint \"Length : %d\" % len (dict)" }, { "code": null, "e": 2802, "s": 2744, "text": "When we run above program, it produces following result −" }, { "code": null, "e": 2814, "s": 2802, "text": "Length : 2\n" }, { "code": null, "e": 2851, "s": 2814, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 2867, "s": 2851, "text": " Malhar Lathkar" }, { "code": null, "e": 2900, "s": 2867, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 2919, "s": 2900, "text": " Arnab Chakraborty" }, { "code": null, "e": 2954, "s": 2919, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 2976, "s": 2954, "text": " In28Minutes Official" }, { "code": null, "e": 3010, "s": 2976, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 3038, "s": 3010, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3073, "s": 3038, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 3087, "s": 3073, "text": " Lets Kode It" }, { "code": null, "e": 3120, "s": 3087, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 3137, "s": 3120, "text": " Abhilash Nelson" }, { "code": null, "e": 3144, "s": 3137, "text": " Print" }, { "code": null, "e": 3155, "s": 3144, "text": " Add Notes" } ]
basename Command in Linux with examples - GeeksforGeeks
15 May, 2019 basename strips directory information and suffixes from file names i.e. it prints the file name NAME with any leading directory components removed. The basename command can be easily used by simply writing basename followed by the file name or the full pathname. Syntax of basename command : $basename NAME [SUFFIX] or $basename OPTION NAME where, NAME refers to the file name or file full pathname and OPTION refers to the options compatible with the basename command and in case, if you want to strip off the suffix of a file you can give the filename followed by the SUFFIX name you want to get rid off. Example : /* basename removes directory path and returns the file name, kt */ $basename /usr/local/bin/kt kt In the first case, the basename command removes the directories name from the full path name given of file kt and in the second case basename removes the suffix .html from kt.html. -a, – -multiple option : This option lets you support multiple arguments and treat each as a NAME i.e you can give multiple file names or full path names with the use of -a option./* -a is used for multiple inputs */ $basename -a /usr/local/bin/kt /usr/local/bin/kt.html kt kt.html /* -a is used for multiple inputs */ $basename -a /usr/local/bin/kt /usr/local/bin/kt.html kt kt.html -s, – -suffix = SUFFIX option : This option removes a trailing suffix SUFFIX,such as a file extension. /*.html suffix is removed from kt.html when followed by -s option */ $basename -s .html kt.html kt /*.html suffix is removed from kt.html when followed by -s option */ $basename -s .html kt.html kt -z option : This separates the output with NULL rather than a newline./* The outputs of the two arguments passed are not separated by a newline*/ $basename -az /usr/local/bin/kt kt.html ktkt /* The outputs of the two arguments passed are not separated by a newline*/ $basename -az /usr/local/bin/kt kt.html ktkt – -help option : This displays the help information and exit. – -version option : This displays the version information and exit. There are many utilities available which are only useful when it comes to shell scripts and doesn’t have any practical application when used by itself and basename comes under this category. Example of a shell script which converts gif image files into png image files with the help of basename command : /*shell script to convert the gif image file format into png image file format */ #!/bin/sh for file in *.gif;do #exit if there are no files if [! -f $file];then exit fi b='basename $file .gif' echo NOW $b.gif is $b.png giftopnm $b.gif | pnmtopng >$b.png done In the above shell script basename command is used to extract the file names with extension .gif without the extension so that they can be converted into .png files. References : basename command linux-command Linux-file-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 UDP Server-Client implementation in C Conditional Statements | Shell Script Cat command in Linux with examples Tail command in Linux with examples touch command in Linux with Examples Mutex lock for Linux Thread Synchronization echo command in Linux with Examples tee command in Linux with examples Compiling with g++
[ { "code": null, "e": 24012, "s": 23984, "text": "\n15 May, 2019" }, { "code": null, "e": 24160, "s": 24012, "text": "basename strips directory information and suffixes from file names i.e. it prints the file name NAME with any leading directory components removed." }, { "code": null, "e": 24275, "s": 24160, "text": "The basename command can be easily used by simply writing basename followed by the file name or the full pathname." }, { "code": null, "e": 24304, "s": 24275, "text": "Syntax of basename command :" }, { "code": null, "e": 24362, "s": 24304, "text": "$basename NAME [SUFFIX]\n or\n$basename OPTION NAME\n" }, { "code": null, "e": 24628, "s": 24362, "text": "where, NAME refers to the file name or file full pathname and OPTION refers to the options compatible with the basename command and in case, if you want to strip off the suffix of a file you can give the filename followed by the SUFFIX name you want to get rid off." }, { "code": null, "e": 24638, "s": 24628, "text": "Example :" }, { "code": null, "e": 24742, "s": 24638, "text": "/* basename removes directory path and \n returns the file name, kt */\n$basename /usr/local/bin/kt\nkt\n" }, { "code": null, "e": 24923, "s": 24742, "text": "In the first case, the basename command removes the directories name from the full path name given of file kt and in the second case basename removes the suffix .html from kt.html." }, { "code": null, "e": 25206, "s": 24923, "text": "-a, – -multiple option : This option lets you support multiple arguments and treat each as a NAME i.e you can give multiple file names or full path names with the use of -a option./* -a is used for multiple inputs */\n$basename -a /usr/local/bin/kt /usr/local/bin/kt.html\nkt\nkt.html\n" }, { "code": null, "e": 25309, "s": 25206, "text": "/* -a is used for multiple inputs */\n$basename -a /usr/local/bin/kt /usr/local/bin/kt.html\nkt\nkt.html\n" }, { "code": null, "e": 25516, "s": 25309, "text": "-s, – -suffix = SUFFIX option : This option removes a trailing suffix SUFFIX,such as a file extension.\n/*.html suffix is removed from kt.html \n when followed by -s option */\n$basename -s .html kt.html\nkt\n" }, { "code": null, "e": 25621, "s": 25516, "text": "\n/*.html suffix is removed from kt.html \n when followed by -s option */\n$basename -s .html kt.html\nkt\n" }, { "code": null, "e": 25816, "s": 25621, "text": "-z option : This separates the output with NULL rather than a newline./* The outputs of the two arguments passed\n are not separated by a newline*/\n$basename -az /usr/local/bin/kt kt.html\nktkt\n" }, { "code": null, "e": 25941, "s": 25816, "text": "/* The outputs of the two arguments passed\n are not separated by a newline*/\n$basename -az /usr/local/bin/kt kt.html\nktkt\n" }, { "code": null, "e": 26003, "s": 25941, "text": "– -help option : This displays the help information and exit." }, { "code": null, "e": 26071, "s": 26003, "text": "– -version option : This displays the version information and exit." }, { "code": null, "e": 26262, "s": 26071, "text": "There are many utilities available which are only useful when it comes to shell scripts and doesn’t have any practical application when used by itself and basename comes under this category." }, { "code": null, "e": 26376, "s": 26262, "text": "Example of a shell script which converts gif image files into png image files with the help of basename command :" }, { "code": null, "e": 26670, "s": 26376, "text": "/*shell script to convert the\ngif image file format into\npng image file format */\n\n#!/bin/sh\nfor file in *.gif;do\n #exit if there are no files\n if [! -f $file];then\n exit\n fi\n b='basename $file .gif'\n echo NOW $b.gif is $b.png\n giftopnm $b.gif | pnmtopng >$b.png\ndone\n" }, { "code": null, "e": 26836, "s": 26670, "text": "In the above shell script basename command is used to extract the file names with extension .gif without the extension so that they can be converted into .png files." }, { "code": null, "e": 26866, "s": 26836, "text": "References : basename command" }, { "code": null, "e": 26880, "s": 26866, "text": "linux-command" }, { "code": null, "e": 26900, "s": 26880, "text": "Linux-file-commands" }, { "code": null, "e": 26911, "s": 26900, "text": "Linux-Unix" }, { "code": null, "e": 27009, "s": 26911, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27044, "s": 27009, "text": "tar command in Linux with examples" }, { "code": null, "e": 27082, "s": 27044, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 27120, "s": 27082, "text": "Conditional Statements | Shell Script" }, { "code": null, "e": 27155, "s": 27120, "text": "Cat command in Linux with examples" }, { "code": null, "e": 27191, "s": 27155, "text": "Tail command in Linux with examples" }, { "code": null, "e": 27228, "s": 27191, "text": "touch command in Linux with Examples" }, { "code": null, "e": 27272, "s": 27228, "text": "Mutex lock for Linux Thread Synchronization" }, { "code": null, "e": 27308, "s": 27272, "text": "echo command in Linux with Examples" }, { "code": null, "e": 27343, "s": 27308, "text": "tee command in Linux with examples" } ]
Amazon WoW Internship Interview Experience 2021 - GeeksforGeeks
09 Jan, 2022 Difficulty Level: Medium-Hard Online Assessment 1: Date – 17/08/2021 Mettl Platform Time – 90 minutes 9 Sections – 41 Questions 1 Coding questions + 40 Objectives MCQ Topics (5 Questions Each Section) Data Structures and Algorithms Networking Linux Pseudocode SQL Queries Databases Software Testing Software Engineering Data Structures and Algorithms Networking Linux Pseudocode SQL Queries Databases Software Testing Software Engineering Online Assessment 2: Date – 25/08/2021 4 Sections Code Debugging (6 Code Snippets) – 20 minutes Coding Test (2 Coding Questions) – 70 minutes Workstyles Assessment – 20 minuntes Reasoning Ability (24 Questions) – 35 minutes Code Debugging (6 Code Snippets) – 20 minutes Coding Test (2 Coding Questions) – 70 minutes Workstyles Assessment – 20 minuntes Reasoning Ability (24 Questions) – 35 minutes Interview Round: Date – 10/10/2021 Started with the Introduction. Without wasting any second, he came to the coding part He asked a coding question- Given an array of strings. Print first non-repeating string from the stream of strings in the given array.Input -> ["a","b","c","b","a"] Output -> ["a","a","a","a","c"] I gave 3 different approaches Approach 1: Brute Force He asked me to optimize it. Approach 2: I gave the second approach by using a queue and a map. But queue operations needed O(n) time so he asked to optimize it and do it in constant time by using some other linear data structure. Approach 3: I didn’t know the solution prior so I kept thinking about it. After discussing and thinking a lot I came up with a solution. I explained my approach by using a doubly-linked list and a map. Then he asked me to code it down. I gave the whole working code. Given an array of strings. Print first non-repeating string from the stream of strings in the given array.Input -> ["a","b","c","b","a"] Output -> ["a","a","a","a","c"] I gave 3 different approaches Approach 1: Brute Force He asked me to optimize it. Approach 2: I gave the second approach by using a queue and a map. But queue operations needed O(n) time so he asked to optimize it and do it in constant time by using some other linear data structure. Approach 3: I didn’t know the solution prior so I kept thinking about it. After discussing and thinking a lot I came up with a solution. I explained my approach by using a doubly-linked list and a map. Then he asked me to code it down. I gave the whole working code. Input -> ["a","b","c","b","a"] Output -> ["a","a","a","a","c"] I gave 3 different approaches Approach 1: Brute Force He asked me to optimize it. Approach 2: I gave the second approach by using a queue and a map. But queue operations needed O(n) time so he asked to optimize it and do it in constant time by using some other linear data structure. Approach 3: I didn’t know the solution prior so I kept thinking about it. After discussing and thinking a lot I came up with a solution. I explained my approach by using a doubly-linked list and a map. Then he asked me to code it down. I gave the whole working code. I was finally hired for the Internship at Amazon. I would like to thank GeeksforGeeks which helped me a lot in my preparation. Amazon Amazon-WoW Internship Interview Experiences Amazon Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Arista Networks Interview | Set 4 (On-Campus for Internship) Arista Networks Interview | Set 7 (For Internship) Josh Technology Interview Experience for Frontend Developer (On-Campus) Amazon(Barcelona) Interview Experience for SDE | Off-Campus Internship Amazon Interview Experience | Set 304 (On-Campus for Internship) Difference between ANN, CNN and RNN Amazon Interview Questions Zoho Interview | Set 1 (On-Campus) Commonly Asked Java Programming Interview Questions | Set 2 Amazon Interview Experience for SDE-1 (On-Campus)
[ { "code": null, "e": 25109, "s": 25081, "text": "\n09 Jan, 2022" }, { "code": null, "e": 25140, "s": 25109, "text": "Difficulty Level: Medium-Hard" }, { "code": null, "e": 25161, "s": 25140, "text": "Online Assessment 1:" }, { "code": null, "e": 25179, "s": 25161, "text": "Date – 17/08/2021" }, { "code": null, "e": 25204, "s": 25179, "text": "Mettl Platform " }, { "code": null, "e": 25224, "s": 25204, "text": "Time – 90 minutes " }, { "code": null, "e": 25258, "s": 25224, "text": "9 Sections – 41 Questions " }, { "code": null, "e": 25301, "s": 25258, "text": "1 Coding questions + 40 Objectives " }, { "code": null, "e": 25348, "s": 25301, "text": "MCQ Topics (5 Questions Each Section) " }, { "code": null, "e": 25524, "s": 25348, "text": "Data Structures and Algorithms Networking Linux Pseudocode SQL Queries Databases Software Testing Software Engineering " }, { "code": null, "e": 25563, "s": 25524, "text": "Data Structures and Algorithms " }, { "code": null, "e": 25582, "s": 25563, "text": "Networking " }, { "code": null, "e": 25596, "s": 25582, "text": "Linux " }, { "code": null, "e": 25615, "s": 25596, "text": "Pseudocode " }, { "code": null, "e": 25635, "s": 25615, "text": "SQL Queries " }, { "code": null, "e": 25653, "s": 25635, "text": "Databases " }, { "code": null, "e": 25678, "s": 25653, "text": "Software Testing " }, { "code": null, "e": 25707, "s": 25678, "text": "Software Engineering " }, { "code": null, "e": 25746, "s": 25707, "text": "Online Assessment 2: Date – 25/08/2021" }, { "code": null, "e": 25765, "s": 25746, "text": "4 Sections " }, { "code": null, "e": 25968, "s": 25765, "text": "Code Debugging (6 Code Snippets) – 20 minutes Coding Test (2 Coding Questions) – 70 minutes Workstyles Assessment – 20 minuntes Reasoning Ability (24 Questions) – 35 minutes " }, { "code": null, "e": 26022, "s": 25968, "text": "Code Debugging (6 Code Snippets) – 20 minutes " }, { "code": null, "e": 26076, "s": 26022, "text": "Coding Test (2 Coding Questions) – 70 minutes " }, { "code": null, "e": 26120, "s": 26076, "text": "Workstyles Assessment – 20 minuntes " }, { "code": null, "e": 26174, "s": 26120, "text": "Reasoning Ability (24 Questions) – 35 minutes " }, { "code": null, "e": 26209, "s": 26174, "text": "Interview Round: Date – 10/10/2021" }, { "code": null, "e": 26303, "s": 26209, "text": "Started with the Introduction. Without wasting any second, he came to the coding part " }, { "code": null, "e": 26339, "s": 26303, "text": "He asked a coding question- " }, { "code": null, "e": 27137, "s": 26339, "text": "Given an array of strings. Print first non-repeating string from the stream of strings in the given array.Input -> [\"a\",\"b\",\"c\",\"b\",\"a\"] \nOutput -> [\"a\",\"a\",\"a\",\"a\",\"c\"] I gave 3 different approaches Approach 1: Brute Force He asked me to optimize it. Approach 2: I gave the second approach by using a queue and a map. But queue operations needed O(n) time so he asked to optimize it and do it in constant time by using some other linear data structure. Approach 3: I didn’t know the solution prior so I kept thinking about it. After discussing and thinking a lot I came up with a solution. I explained my approach by using a doubly-linked list and a map. Then he asked me to code it down. I gave the whole working code. " }, { "code": null, "e": 27935, "s": 27137, "text": "Given an array of strings. Print first non-repeating string from the stream of strings in the given array.Input -> [\"a\",\"b\",\"c\",\"b\",\"a\"] \nOutput -> [\"a\",\"a\",\"a\",\"a\",\"c\"] I gave 3 different approaches Approach 1: Brute Force He asked me to optimize it. Approach 2: I gave the second approach by using a queue and a map. But queue operations needed O(n) time so he asked to optimize it and do it in constant time by using some other linear data structure. Approach 3: I didn’t know the solution prior so I kept thinking about it. After discussing and thinking a lot I came up with a solution. I explained my approach by using a doubly-linked list and a map. Then he asked me to code it down. I gave the whole working code. " }, { "code": null, "e": 28014, "s": 27935, "text": "Input -> [\"a\",\"b\",\"c\",\"b\",\"a\"] \nOutput -> [\"a\",\"a\",\"a\",\"a\",\"c\"] " }, { "code": null, "e": 28052, "s": 28014, "text": "I gave 3 different approaches " }, { "code": null, "e": 28084, "s": 28052, "text": "Approach 1: Brute Force " }, { "code": null, "e": 28120, "s": 28084, "text": "He asked me to optimize it. " }, { "code": null, "e": 28195, "s": 28120, "text": "Approach 2: I gave the second approach by using a queue and a map. " }, { "code": null, "e": 28338, "s": 28195, "text": "But queue operations needed O(n) time so he asked to optimize it and do it in constant time by using some other linear data structure. " }, { "code": null, "e": 28483, "s": 28338, "text": "Approach 3: I didn’t know the solution prior so I kept thinking about it. After discussing and thinking a lot I came up with a solution. " }, { "code": null, "e": 28590, "s": 28483, "text": "I explained my approach by using a doubly-linked list and a map. Then he asked me to code it down. " }, { "code": null, "e": 28635, "s": 28590, "text": "I gave the whole working code. " }, { "code": null, "e": 28762, "s": 28635, "text": "I was finally hired for the Internship at Amazon. I would like to thank GeeksforGeeks which helped me a lot in my preparation." }, { "code": null, "e": 28769, "s": 28762, "text": "Amazon" }, { "code": null, "e": 28780, "s": 28769, "text": "Amazon-WoW" }, { "code": null, "e": 28791, "s": 28780, "text": "Internship" }, { "code": null, "e": 28813, "s": 28791, "text": "Interview Experiences" }, { "code": null, "e": 28820, "s": 28813, "text": "Amazon" }, { "code": null, "e": 28918, "s": 28820, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28927, "s": 28918, "text": "Comments" }, { "code": null, "e": 28940, "s": 28927, "text": "Old Comments" }, { "code": null, "e": 29001, "s": 28940, "text": "Arista Networks Interview | Set 4 (On-Campus for Internship)" }, { "code": null, "e": 29052, "s": 29001, "text": "Arista Networks Interview | Set 7 (For Internship)" }, { "code": null, "e": 29124, "s": 29052, "text": "Josh Technology Interview Experience for Frontend Developer (On-Campus)" }, { "code": null, "e": 29195, "s": 29124, "text": "Amazon(Barcelona) Interview Experience for SDE | Off-Campus Internship" }, { "code": null, "e": 29260, "s": 29195, "text": "Amazon Interview Experience | Set 304 (On-Campus for Internship)" }, { "code": null, "e": 29296, "s": 29260, "text": "Difference between ANN, CNN and RNN" }, { "code": null, "e": 29323, "s": 29296, "text": "Amazon Interview Questions" }, { "code": null, "e": 29358, "s": 29323, "text": "Zoho Interview | Set 1 (On-Campus)" }, { "code": null, "e": 29418, "s": 29358, "text": "Commonly Asked Java Programming Interview Questions | Set 2" } ]
CSS Floating Animation
06 Jul, 2021 In this article, we will explain the very basics of CSS animations along with a demonstration of how to add a floating animation. CSS animations need the following. The animation declaration. The keyframes which defines the properties for getting animation. It also provides properties which says when and how they get animated. Basically Animation is the shorthand property for the following properties: animation-name, animation-duration, animation-timing-function, animation-delay, animation-iteration-count, animation-direction, animation-fill-mode, and animation-play-state. For this article, we will be using animation-name, animation-duration, animation-iteration-count, animation-timing-function. animation-name: Floating (this refers to @keyframe defined below). animation-duration: 3s (this refers to the numbers of seconds your animation will take from start to finish). animation-iteration-count: Infinite (the number of loops for your animation before stopping). animation-timing-function: ease-in-out (The timing for begin animations and end animation). You can combine them under same keyword as shown in the following. animation: floating 3s ease-in-out infinite Let us talk about @keyframes. It give the control over animation. You can change your animation as you like by using this property. First start with the @keyframes rule followed by name of the animation (In this case, it is “floating”). Inside the @keyframes, you can see 3 percentage values have been declared. It is followed by a code snippet containing properties and their values. These percentages represent the breakpoints along the animation sequence. The 0% selector contains a block that execute at the beginning of the animation. The 50% selector contains a block that execute at the halfway point. The 100% selector contains a block that execute once animation is complete. At each of these break points, we have property transform. The transform property which allows the user to rotate, skew, scale, or translate a given element. In this case, we will be using translate property. Basically translate helps us to place things vertically and horizontally. index.html html <!DOCTYPE html><html> <head> <title>Floating Animation</title> <link rel="stylesheet" type="text/css" href="style.css"></head> <body> <div class="floating" style= "height: 150px; width: 150px; background: rgb(200, 200, 200); padding: 10px"> Arsalan </div></body> </html> style.css css .floating { animation-name: floating; animation-duration: 3s; animation-iteration-count: infinite; animation-timing-function: ease-in-out; margin-left: 30px; margin-top: 5px;} @keyframes floating { 0% { transform: translate(0, 0px); } 50% { transform: translate(0, 15px); } 100% { transform: translate(0, -0px); } } Output: Supported Browser: Google Chrome Internet Explorer Firefox Opera Safari ysachin2314 CSS-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. Types of CSS (Cascading Style Sheet) Design a Tribute Page using HTML & CSS How to set space between the flexbox ? How to position a div at the bottom of its container using CSS? How to Upload Image into Database and Display it using PHP ? REST API (Introduction) Hide or show elements in HTML using display property How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ? Types of CSS (Cascading Style Sheet)
[ { "code": null, "e": 28, "s": 0, "text": "\n06 Jul, 2021" }, { "code": null, "e": 195, "s": 28, "text": "In this article, we will explain the very basics of CSS animations along with a demonstration of how to add a floating animation. CSS animations need the following. " }, { "code": null, "e": 222, "s": 195, "text": "The animation declaration." }, { "code": null, "e": 359, "s": 222, "text": "The keyframes which defines the properties for getting animation. It also provides properties which says when and how they get animated." }, { "code": null, "e": 737, "s": 359, "text": "Basically Animation is the shorthand property for the following properties: animation-name, animation-duration, animation-timing-function, animation-delay, animation-iteration-count, animation-direction, animation-fill-mode, and animation-play-state. For this article, we will be using animation-name, animation-duration, animation-iteration-count, animation-timing-function. " }, { "code": null, "e": 804, "s": 737, "text": "animation-name: Floating (this refers to @keyframe defined below)." }, { "code": null, "e": 914, "s": 804, "text": "animation-duration: 3s (this refers to the numbers of seconds your animation will take from start to finish)." }, { "code": null, "e": 1008, "s": 914, "text": "animation-iteration-count: Infinite (the number of loops for your animation before stopping)." }, { "code": null, "e": 1100, "s": 1008, "text": "animation-timing-function: ease-in-out (The timing for begin animations and end animation)." }, { "code": null, "e": 1169, "s": 1102, "text": "You can combine them under same keyword as shown in the following." }, { "code": null, "e": 1215, "s": 1171, "text": "animation: floating 3s ease-in-out infinite" }, { "code": null, "e": 1676, "s": 1215, "text": "Let us talk about @keyframes. It give the control over animation. You can change your animation as you like by using this property. First start with the @keyframes rule followed by name of the animation (In this case, it is “floating”). Inside the @keyframes, you can see 3 percentage values have been declared. It is followed by a code snippet containing properties and their values. These percentages represent the breakpoints along the animation sequence. " }, { "code": null, "e": 1757, "s": 1676, "text": "The 0% selector contains a block that execute at the beginning of the animation." }, { "code": null, "e": 1826, "s": 1757, "text": "The 50% selector contains a block that execute at the halfway point." }, { "code": null, "e": 1902, "s": 1826, "text": "The 100% selector contains a block that execute once animation is complete." }, { "code": null, "e": 2198, "s": 1902, "text": "At each of these break points, we have property transform. The transform property which allows the user to rotate, skew, scale, or translate a given element. In this case, we will be using translate property. Basically translate helps us to place things vertically and horizontally. index.html " }, { "code": null, "e": 2203, "s": 2198, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title>Floating Animation</title> <link rel=\"stylesheet\" type=\"text/css\" href=\"style.css\"></head> <body> <div class=\"floating\" style= \"height: 150px; width: 150px; background: rgb(200, 200, 200); padding: 10px\"> Arsalan </div></body> </html>", "e": 2537, "s": 2203, "text": null }, { "code": null, "e": 2549, "s": 2537, "text": "style.css " }, { "code": null, "e": 2553, "s": 2549, "text": "css" }, { "code": ".floating { animation-name: floating; animation-duration: 3s; animation-iteration-count: infinite; animation-timing-function: ease-in-out; margin-left: 30px; margin-top: 5px;} @keyframes floating { 0% { transform: translate(0, 0px); } 50% { transform: translate(0, 15px); } 100% { transform: translate(0, -0px); } }", "e": 2903, "s": 2553, "text": null }, { "code": null, "e": 2913, "s": 2903, "text": "Output: " }, { "code": null, "e": 2932, "s": 2913, "text": "Supported Browser:" }, { "code": null, "e": 2946, "s": 2932, "text": "Google Chrome" }, { "code": null, "e": 2964, "s": 2946, "text": "Internet Explorer" }, { "code": null, "e": 2972, "s": 2964, "text": "Firefox" }, { "code": null, "e": 2978, "s": 2972, "text": "Opera" }, { "code": null, "e": 2985, "s": 2978, "text": "Safari" }, { "code": null, "e": 2997, "s": 2985, "text": "ysachin2314" }, { "code": null, "e": 3006, "s": 2997, "text": "CSS-Misc" }, { "code": null, "e": 3010, "s": 3006, "text": "CSS" }, { "code": null, "e": 3015, "s": 3010, "text": "HTML" }, { "code": null, "e": 3032, "s": 3015, "text": "Web Technologies" }, { "code": null, "e": 3059, "s": 3032, "text": "Web technologies Questions" }, { "code": null, "e": 3064, "s": 3059, "text": "HTML" }, { "code": null, "e": 3162, "s": 3064, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3199, "s": 3162, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 3238, "s": 3199, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 3277, "s": 3238, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 3341, "s": 3277, "text": "How to position a div at the bottom of its container using CSS?" }, { "code": null, "e": 3402, "s": 3341, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 3426, "s": 3402, "text": "REST API (Introduction)" }, { "code": null, "e": 3479, "s": 3426, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 3539, "s": 3479, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 3600, "s": 3539, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" } ]
Spurious Tuples in DBMS
24 Jun, 2020 In Database Management System (DBMS), data is represented in a tabular form through attributes and tuples i.e., columns and rows.There are various operations (insert, delete, update, modify, etc.) that we can perform on tables. One such operation is join. When we combine two tables into one, we call it a join and it is denoted by ⨝. Spurious Tuples :Spurious Tuples are those rows in a table, which occur as a result of joining two tables in wrong manner. They are extra tuples (rows) which might not be required. If relation is denoted by R, and its decomposed relations are denoted by R1, R2, R3....Rn, then, condition for not getting any Spurious Tuple is denoted by, R1 ⨝ R2 ⨝ R3 .... ⨝ Rn = R Whereas condition for getting Spurious Tuples is denoted by, R ⊂ R1 ⨝ R2 ⨝ R3 .... ⨝ Rn Example-1:Example to check if given relation contains Spurious Tuples.Let R be Relation, and R1 and R2 be relations which we get after decomposing R. After performing join operation of relations R1 and R2 (R1 ⨝ R2), we get back original relation R. The condition for no spurious tuples, R1 ⨝ R2 = R, is met. Hence, we do not get any Spurious Tuples. Conclusion – No Spurious Tuple exists. Example-2:Example to check if given relation contains Spurious Tuples.Let R be Relation, and R1 and R2 be relations which we get after decomposing R. After performing join operation of relations R1 and R2 (R1 ⨝ R2), we do not get back original relation R. The condition for spurious tuples, R ⊂ R1 ⨝ R2, is met. Hence, we get Spurious Tuples. Conclusion – Spurious Tuples exist. Note –Rows in DBMS are called tuples. Whereas, columns in DBMS are called attributes. Spurious Tuples can be remembered as extra rows in table. The natural join leading to Spurious Tuples is called Lossy Join. The natural join not resulting in Spurious Tuples is called Lossless Join. DBMS DBMS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Types of Functional dependencies in DBMS MySQL | Regular expressions (Regexp) Difference between OLAP and OLTP in DBMS What is Temporary Table in SQL? Difference between Where and Having Clause in SQL SQL | DDL, DML, TCL and DCL Introduction of Relational Algebra in DBMS Relational Model in DBMS Difference between Star Schema and Snowflake Schema What is Cursor in SQL ?
[ { "code": null, "e": 52, "s": 24, "text": "\n24 Jun, 2020" }, { "code": null, "e": 387, "s": 52, "text": "In Database Management System (DBMS), data is represented in a tabular form through attributes and tuples i.e., columns and rows.There are various operations (insert, delete, update, modify, etc.) that we can perform on tables. One such operation is join. When we combine two tables into one, we call it a join and it is denoted by ⨝." }, { "code": null, "e": 568, "s": 387, "text": "Spurious Tuples :Spurious Tuples are those rows in a table, which occur as a result of joining two tables in wrong manner. They are extra tuples (rows) which might not be required." }, { "code": null, "e": 725, "s": 568, "text": "If relation is denoted by R, and its decomposed relations are denoted by R1, R2, R3....Rn, then, condition for not getting any Spurious Tuple is denoted by," }, { "code": null, "e": 752, "s": 725, "text": "R1 ⨝ R2 ⨝ R3 .... ⨝ Rn = R" }, { "code": null, "e": 813, "s": 752, "text": "Whereas condition for getting Spurious Tuples is denoted by," }, { "code": null, "e": 840, "s": 813, "text": "R ⊂ R1 ⨝ R2 ⨝ R3 .... ⨝ Rn" }, { "code": null, "e": 990, "s": 840, "text": "Example-1:Example to check if given relation contains Spurious Tuples.Let R be Relation, and R1 and R2 be relations which we get after decomposing R." }, { "code": null, "e": 1089, "s": 990, "text": "After performing join operation of relations R1 and R2 (R1 ⨝ R2), we get back original relation R." }, { "code": null, "e": 1190, "s": 1089, "text": "The condition for no spurious tuples, R1 ⨝ R2 = R, is met. Hence, we do not get any Spurious Tuples." }, { "code": null, "e": 1229, "s": 1190, "text": "Conclusion – No Spurious Tuple exists." }, { "code": null, "e": 1379, "s": 1229, "text": "Example-2:Example to check if given relation contains Spurious Tuples.Let R be Relation, and R1 and R2 be relations which we get after decomposing R." }, { "code": null, "e": 1485, "s": 1379, "text": "After performing join operation of relations R1 and R2 (R1 ⨝ R2), we do not get back original relation R." }, { "code": null, "e": 1572, "s": 1485, "text": "The condition for spurious tuples, R ⊂ R1 ⨝ R2, is met. Hence, we get Spurious Tuples." }, { "code": null, "e": 1608, "s": 1572, "text": "Conclusion – Spurious Tuples exist." }, { "code": null, "e": 1893, "s": 1608, "text": "Note –Rows in DBMS are called tuples. Whereas, columns in DBMS are called attributes. Spurious Tuples can be remembered as extra rows in table. The natural join leading to Spurious Tuples is called Lossy Join. The natural join not resulting in Spurious Tuples is called Lossless Join." }, { "code": null, "e": 1898, "s": 1893, "text": "DBMS" }, { "code": null, "e": 1903, "s": 1898, "text": "DBMS" }, { "code": null, "e": 2001, "s": 1903, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2042, "s": 2001, "text": "Types of Functional dependencies in DBMS" }, { "code": null, "e": 2079, "s": 2042, "text": "MySQL | Regular expressions (Regexp)" }, { "code": null, "e": 2120, "s": 2079, "text": "Difference between OLAP and OLTP in DBMS" }, { "code": null, "e": 2152, "s": 2120, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 2202, "s": 2152, "text": "Difference between Where and Having Clause in SQL" }, { "code": null, "e": 2230, "s": 2202, "text": "SQL | DDL, DML, TCL and DCL" }, { "code": null, "e": 2273, "s": 2230, "text": "Introduction of Relational Algebra in DBMS" }, { "code": null, "e": 2298, "s": 2273, "text": "Relational Model in DBMS" }, { "code": null, "e": 2350, "s": 2298, "text": "Difference between Star Schema and Snowflake Schema" } ]
Suspend/Resume tasks in FreeRTOS using Arduino
If you wish to suspend a task in FreeRTOS, there is a function vTaskSuspend() that can be used. The syntax is − Syntax void vTaskSuspend( TaskHandle_t xTaskToSuspend ); As you can see, it takes the handle of the task to suspend as the argument and returns nothing. A suspended task can be resumed using vTaskResume(). The syntax is − Syntax void vTaskResume( TaskHandle_t xTaskToResume ); This again takes the handle of the task to be resumed, and returns nothing. In order to see an example, we will walk-through the code given in −https://exploreembedded.com/wiki/Task_Suspend_and_Resume As you can see, four Task handles are declared initially, and the tasks are created in the setup. /************************************************************************ *************************** ExploreEmbedded Copyright Notice ************************************************************************* *************************** * File: 07-TaskSuspendAndResume * Version: 15.0 * Author: ExploreEmbedded * Website: http://www.exploreembedded.com/wiki * Description: File contains the free rtos example to demonstarte task Suspend and Resume. This code has been developed and tested on ExploreEmbedded boards. We strongly believe that the library works on any of development boards for respective controllers. Check this link http://www.exploreembedded.com/wiki for awesome tutorials on 8051,PIC,AVR,ARM,Robotics,RTOS,IOT. ExploreEmbedded invests substantial time and effort developing open source HW and SW tools, to support consider buying the ExploreEmbedded boards. The ExploreEmbedded libraries and examples are licensed under the terms of the new-bsd license(two-clause bsd license). See also: http://www.opensource.org/licenses/bsd-license.php EXPLOREEMBEDDED DISCLAIMS ANY KIND OF HARDWARE FAILURE RESULTING OUT OF USAGE OF LIBRARIES, DIRECTLY OR INDIRECTLY. FILES MAY BE SUBJECT TO CHANGE WITHOUT PRIOR NOTICE. THE REVISION HISTORY CONTAINS THE INFORMATION RELATED TO UPDATES. Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, provided that this copyright notices appear in all copies and that both those copyright notices and this permission notice appear in supporting documentation. ************************************************************************* *************************/ #include <Arduino_FreeRTOS.h> TaskHandle_t TaskHandle_1; TaskHandle_t TaskHandle_2; TaskHandle_t TaskHandle_3; TaskHandle_t TaskHandle_4; void setup() { Serial.begin(9600); Serial.println(F("In Setup function")); /* Create 4-tasks with priorities 1-4. Capture the Task details to respective handlers */ xTaskCreate(MyTask1, "Task1", 100, NULL, 1, &TaskHandle_1); xTaskCreate(MyTask2, "Task2", 100, NULL, 2, &TaskHandle_2); xTaskCreate(MyTask3, "Task3", 100, NULL, 3, &TaskHandle_3); xTaskCreate(MyTask4, "Task4", 100, NULL, 4, &TaskHandle_4); } Note that Task1 has the lowest priority and Task4 has the highest priority. The loop just contains a print statement and a delay. void loop() { // Hooked to Idle Task, will run when CPU is Idle Serial.println(F("Loop function")); delay(50); } Now, coming to the individual task codes, Task4 suspends Task2, Task3 and then itself. Task 1 resumes these tasks one by one, and then deletes itself. Tasks 2 and 3 just delete themselves after printing a statement. /* Task1 with priority 1 */ static void MyTask1(void* pvParameters) { Serial.println(F("Task1 Resuming Task2")); vTaskResume(TaskHandle_2); Serial.println(F("Task1 Resuming Task3")); vTaskResume(TaskHandle_3); Serial.println(F("Task1 Resuming Task4")); vTaskResume(TaskHandle_4); Serial.println(F("Task1 Deleting Itself")); vTaskDelete(TaskHandle_1); } /* Task2 with priority 2 */ static void MyTask2(void* pvParameters) { Serial.println(F("Task2, Deleting itself")); vTaskDelete(NULL); // Delete own task by passing NULL(TaskHandle_2 can also be used) } /* Task3 with priority 3 */ static void MyTask3(void* pvParameters) { Serial.println(F("Task3, Deleting Itself")); vTaskDelete(NULL); // Delete own task by passing NULL(TaskHandle_3 can also be used) } /* Task4 with priority 4 */ static void MyTask4(void* pvParameters) { Serial.println(F("Task4 Running, Suspending all tasks")); vTaskSuspend(TaskHandle_2); //Suspend Task2/3 vTaskSuspend(TaskHandle_3); vTaskSuspend(NULL); //Suspend Own Task Serial.println(F("Back in Task4, Deleting Itself")); vTaskDelete(TaskHandle_4); } Thus, Task4, with the highest priority starts first, and suspends Tasks 2, 3 and itself. Thus, Task1 gets control. Task1 resumes Task2. Since Task2 has a higher priority, it takes over control, prints a statement and deletes itself. Control goes back to Task1, which then resumes Task3. Task3 does its work, deletes itself and thus control goes back to Task1. Same thing happens with Task4, and once Task4 has been deleted, Task1 also deletes itself, and only the print statements in loop are visible on the Serial Monitor.
[ { "code": null, "e": 1174, "s": 1062, "text": "If you wish to suspend a task in FreeRTOS, there is a function vTaskSuspend() that can be used. The syntax is −" }, { "code": null, "e": 1181, "s": 1174, "text": "Syntax" }, { "code": null, "e": 1231, "s": 1181, "text": "void vTaskSuspend( TaskHandle_t xTaskToSuspend );" }, { "code": null, "e": 1396, "s": 1231, "text": "As you can see, it takes the handle of the task to suspend as the argument and returns nothing. A suspended task can be resumed using vTaskResume(). The syntax is −" }, { "code": null, "e": 1403, "s": 1396, "text": "Syntax" }, { "code": null, "e": 1451, "s": 1403, "text": "void vTaskResume( TaskHandle_t xTaskToResume );" }, { "code": null, "e": 1527, "s": 1451, "text": "This again takes the handle of the task to be resumed, and returns nothing." }, { "code": null, "e": 1652, "s": 1527, "text": "In order to see an example, we will walk-through the code given in −https://exploreembedded.com/wiki/Task_Suspend_and_Resume" }, { "code": null, "e": 1750, "s": 1652, "text": "As you can see, four Task handles are declared initially, and the tasks are created in the setup." }, { "code": null, "e": 4048, "s": 1750, "text": "/************************************************************************\n***************************\n ExploreEmbedded Copyright Notice\n*************************************************************************\n***************************\n * File: 07-TaskSuspendAndResume\n * Version: 15.0\n * Author: ExploreEmbedded\n * Website: http://www.exploreembedded.com/wiki\n * Description: File contains the free rtos example to demonstarte task Suspend and Resume.\nThis code has been developed and tested on ExploreEmbedded boards.\nWe strongly believe that the library works on any of development boards for\nrespective controllers.\nCheck this link http://www.exploreembedded.com/wiki for awesome tutorials\non 8051,PIC,AVR,ARM,Robotics,RTOS,IOT.\nExploreEmbedded invests substantial time and effort developing open source\nHW and SW tools, to support consider\nbuying the ExploreEmbedded boards.\n\nThe ExploreEmbedded libraries and examples are licensed under the terms of\nthe new-bsd license(two-clause bsd license).\nSee also: http://www.opensource.org/licenses/bsd-license.php\nEXPLOREEMBEDDED DISCLAIMS ANY KIND OF HARDWARE FAILURE RESULTING OUT OF\nUSAGE OF LIBRARIES, DIRECTLY OR\nINDIRECTLY. FILES MAY BE SUBJECT TO CHANGE WITHOUT PRIOR NOTICE. THE\nREVISION HISTORY CONTAINS THE INFORMATION RELATED TO UPDATES.\n\nPermission to use, copy, modify, and distribute this software and its\ndocumentation for any purpose and without fee is hereby granted, provided\nthat this copyright notices appear in all copies and that both those\ncopyright notices and this permission notice appear in supporting\ndocumentation.\n*************************************************************************\n*************************/\n\n#include <Arduino_FreeRTOS.h>\n\nTaskHandle_t TaskHandle_1;\nTaskHandle_t TaskHandle_2;\nTaskHandle_t TaskHandle_3;\nTaskHandle_t TaskHandle_4;\n\nvoid setup()\n{\n Serial.begin(9600);\n Serial.println(F(\"In Setup function\"));\n\n/* Create 4-tasks with priorities 1-4. Capture the Task details to respective handlers */\n xTaskCreate(MyTask1, \"Task1\", 100, NULL, 1, &TaskHandle_1);\n xTaskCreate(MyTask2, \"Task2\", 100, NULL, 2, &TaskHandle_2);\n xTaskCreate(MyTask3, \"Task3\", 100, NULL, 3, &TaskHandle_3);\n xTaskCreate(MyTask4, \"Task4\", 100, NULL, 4, &TaskHandle_4);\n}" }, { "code": null, "e": 4124, "s": 4048, "text": "Note that Task1 has the lowest priority and Task4 has the highest priority." }, { "code": null, "e": 4178, "s": 4124, "text": "The loop just contains a print statement and a delay." }, { "code": null, "e": 4300, "s": 4178, "text": "void loop()\n{\n // Hooked to Idle Task, will run when CPU is Idle\n Serial.println(F(\"Loop function\"));\n delay(50);\n}" }, { "code": null, "e": 4516, "s": 4300, "text": "Now, coming to the individual task codes, Task4 suspends Task2, Task3 and then itself. Task 1 resumes these tasks one by one, and then deletes itself. Tasks 2 and 3 just delete themselves after printing a statement." }, { "code": null, "e": 5674, "s": 4516, "text": "/* Task1 with priority 1 */\nstatic void MyTask1(void* pvParameters)\n{\n Serial.println(F(\"Task1 Resuming Task2\"));\n vTaskResume(TaskHandle_2);\n\n Serial.println(F(\"Task1 Resuming Task3\"));\n vTaskResume(TaskHandle_3);\n\n Serial.println(F(\"Task1 Resuming Task4\"));\n vTaskResume(TaskHandle_4);\n\n Serial.println(F(\"Task1 Deleting Itself\"));\n vTaskDelete(TaskHandle_1);\n}\n\n/* Task2 with priority 2 */\nstatic void MyTask2(void* pvParameters)\n{\n Serial.println(F(\"Task2, Deleting itself\"));\n vTaskDelete(NULL);\n// Delete own task by passing NULL(TaskHandle_2 can also be used)\n}\n\n/* Task3 with priority 3 */\nstatic void MyTask3(void* pvParameters)\n{\n Serial.println(F(\"Task3, Deleting Itself\"));\n vTaskDelete(NULL);\n // Delete own task by passing NULL(TaskHandle_3 can also be used)\n}\n\n/* Task4 with priority 4 */\nstatic void MyTask4(void* pvParameters)\n{\n Serial.println(F(\"Task4 Running, Suspending all tasks\"));\n vTaskSuspend(TaskHandle_2); //Suspend Task2/3\n vTaskSuspend(TaskHandle_3);\n vTaskSuspend(NULL); //Suspend Own Task\n\n Serial.println(F(\"Back in Task4, Deleting Itself\"));\n vTaskDelete(TaskHandle_4);\n}" }, { "code": null, "e": 6198, "s": 5674, "text": "Thus, Task4, with the highest priority starts first, and suspends Tasks 2, 3 and itself. Thus, Task1 gets control. Task1 resumes Task2. Since Task2 has a higher priority, it takes over control, prints a statement and deletes itself. Control goes back to Task1, which then resumes Task3. Task3 does its work, deletes itself and thus control goes back to Task1. Same thing happens with Task4, and once Task4 has been deleted, Task1 also deletes itself, and only the print statements in loop are visible on the Serial Monitor." } ]
Essential Dictionary Mutation For Python Programmers | by Emmett Boudreau | Towards Data Science
The dictionary data-type is arguably the most important data structure in the Python programming language. This is even more true for Data Scientists who often work with labeled data that works exactly the same as a dictionary. In many ways, data frames are simply tabular views for the exact same thing that a dictionary does along with some helpful functions for data processing. The data structure also serves as the foundation of JSON, which is a very popular data format both for storage and transmission via requests. Python has a pretty awesome implementation of the dictionary data structure, and there are a lot of things that the data structure is capable of doing out of the box. Needless to say, knowing the ins and outs of the dictionary data structure is going to come in handy in Data Science work. There is a lot to learn, but today I wanted to review some of the dictionary methods that I think are very exceptional and useful, especially for Data Science. notebook We have all heard of sorting Pandas series and data frames, but did you know you can do essentially the same thing with a dictionary? We can sort both by by the alphabet and also by numerical value. This is convenient because it allows us to sort all keys and their pairs at the same time. This can also be done with tuples and other data types, but for now we will stick to the dictionary. Consider the following dictionary: cities: dict = { "Detroit": 3619342323, "Las Vegas": 99870, "Las Angeles": 9525067, "Boulder": 17098246, "Atlanta": 2780400, "Paducah": 752612, "Tampa": 9596961,} We can sort this dictionary using the sorted() method along with a dict cast. For the key, we will use the numerical values in our dictionary. In order to do this with each key, we will need to use a lambda expression in order to evaluate the key for each value. If you would like to learn more about lambda and what it is used for, I have an article I wrote on it a while back that I think is worth a read! You can check out that article here: towardsdatascience.com Let us go ahead and sort our dictionary: citysorted = dict(sorted(cities.items(), key = lambda kv: kv[1], reverse=False)) Now our dictionary looks like this: {'Las Vegas': 99870, 'Paducah': 752612, 'Atlanta': 2780400, 'Las Angeles': 9525067, 'Tampa': 9596961, 'Boulder': 17098246, 'Detroit': 3619342323} Just to prove we can do this with the alphabetical feature as well, I will now sort it by the [0] position of the keys: {'Atlanta': 2780400, 'Boulder': 17098246, 'Detroit': 3619342323, 'Las Angeles': 9525067, 'Las Vegas': 99870, 'Paducah': 752612, 'Tampa': 9596961} Merging is one of the tools that the Pandas module provides that sets it apart from just using the dictionary data structure. In order to merge dictionaries together, we do not necessarily need to write a function, as we can simply use the update function contained within the dict class. However, I like to write a function to do so in order to copy the dictionary rather than mutating the other, as I often focus on retaining the form of data when programming. That being said, it is a relatively simple operation that mostly involves calls on the functions that are already provided in the dictionary type. The first thing we are going to do to write this merge function is consider our arguments and output, we want to provide two dictionaries and get a single dictionary back. Let us put that into a function call: def merge_dicts(one: dict, two: dict): Now we will want to copy the dictionary so that we do not end up mutating the original type, because that could be quite catastrophic if we were to accidentally destroy the data in the first one — especially if we were to mess up this function on the first try. Since we are not working with the individual data-types contained within our dictionary, there is no need to do a deep copy, so we can get by pretty easily using a shallow copy. temp: dict = one.copy()newdict: dict = one.copy() Finally, we will call the update function and return our new dictionary: newdict.update(two) return(newdict) For a final result that looks like this: def merge_dicts(one: dict, two: dict): newdict = one.copy() newdict.update(two) return(newdict) Now we will create a new dictionary to call this with: additional_cities: dict = { "Dover": 8323, "Colorado Springs": 4990, "Seattle": 95067,} Now let us pass both of our dictionaries through our function! allcities = merge_dicts(additional_cities, cities) And this is the result: {'Dover': 8323, 'Colorado Springs': 4990, 'Seattle': 95067, 'Detroit': 3619342323, 'Las Vegas': 99870, 'Las Angeles': 9525067, 'Boulder': 17098246, 'Atlanta': 2780400, 'Paducah': 752612, 'Tampa': 9596961} Cool! Dictionaries are often used to store data in Python. A lot of this data is iteratively added overtime, and sometimes there might be missing values or keys caught up in the mix than can create problems if we do not have a way to deal with them properly. For this problem, the solution is to use the setdefault() function that is included with the dictionary class. In the following example, I will do exactly that and default incoming keys without pairs to be assigned to the mean of our data: allcities.setdefault("Unknown", sum(allcities.values()) / len(allcities.values())) This will append the default to our dictionary while also making incoming data default to these two values. As I mentioned before, the JSON data format is quite popular for sending, receiving, and even storing data for web-development and Data Science. However, likely one of the most popular formats for real data storage outside of a data base is Comma Separated Value, or CSV files. These files are great because they contain far less syntactical chars than a format like JSON. Using the CSV module, we can get a CSV reader that will translate our CSV files into data for us! Let us import it and try it out!: import csv Now we can create a new reader object by calling on the csv.DictReader() class with the open() method in order to get our CSV file into a string: reader = csv.DictReader(open("spreader.csv", "r")) Now we can iterate that reader type, providing us with keys and corresponding values: for row in reader: print(row){'hello': 'how', 'medium': 'is'}{'hello': 'everyone', 'medium': 'doing?'} Finally, we can push these into a dictionary with the update() function that we used before: for row in reader: z[row["Code"]] = row About a month ago, I wrote a really cool article on how you can actually visualize dictionaries in a tabular fashion just like you would a data frame. Since this was such a cool trick, I decided to add it at the end of this list so that dictionary conquerors could find a better way to look at their data. If you are interested in reading that article, you may check it out here: towardsdatascience.com The dictionary data structure is one that is nearly essential for software engineering work, and is even more crucial for Data Science work. The data structure makes it far easier to deal with multiple corresponding lists at once, and is unmatched in convenience and capability by the other data structures that are packaged with the language. I think that knowing how to use dictionaries effectively can set you apart from the crowd and create a significant impact on your work, and using some of these tips can certainly make the use of dictionaries a bit easier. Thank you very much for reading my article!
[ { "code": null, "e": 553, "s": 171, "text": "The dictionary data-type is arguably the most important data structure in the Python programming language. This is even more true for Data Scientists who often work with labeled data that works exactly the same as a dictionary. In many ways, data frames are simply tabular views for the exact same thing that a dictionary does along with some helpful functions for data processing." }, { "code": null, "e": 1145, "s": 553, "text": "The data structure also serves as the foundation of JSON, which is a very popular data format both for storage and transmission via requests. Python has a pretty awesome implementation of the dictionary data structure, and there are a lot of things that the data structure is capable of doing out of the box. Needless to say, knowing the ins and outs of the dictionary data structure is going to come in handy in Data Science work. There is a lot to learn, but today I wanted to review some of the dictionary methods that I think are very exceptional and useful, especially for Data Science." }, { "code": null, "e": 1154, "s": 1145, "text": "notebook" }, { "code": null, "e": 1580, "s": 1154, "text": "We have all heard of sorting Pandas series and data frames, but did you know you can do essentially the same thing with a dictionary? We can sort both by by the alphabet and also by numerical value. This is convenient because it allows us to sort all keys and their pairs at the same time. This can also be done with tuples and other data types, but for now we will stick to the dictionary. Consider the following dictionary:" }, { "code": null, "e": 1764, "s": 1580, "text": "cities: dict = { \"Detroit\": 3619342323, \"Las Vegas\": 99870, \"Las Angeles\": 9525067, \"Boulder\": 17098246, \"Atlanta\": 2780400, \"Paducah\": 752612, \"Tampa\": 9596961,}" }, { "code": null, "e": 2209, "s": 1764, "text": "We can sort this dictionary using the sorted() method along with a dict cast. For the key, we will use the numerical values in our dictionary. In order to do this with each key, we will need to use a lambda expression in order to evaluate the key for each value. If you would like to learn more about lambda and what it is used for, I have an article I wrote on it a while back that I think is worth a read! You can check out that article here:" }, { "code": null, "e": 2232, "s": 2209, "text": "towardsdatascience.com" }, { "code": null, "e": 2273, "s": 2232, "text": "Let us go ahead and sort our dictionary:" }, { "code": null, "e": 2354, "s": 2273, "text": "citysorted = dict(sorted(cities.items(), key = lambda kv: kv[1], reverse=False))" }, { "code": null, "e": 2390, "s": 2354, "text": "Now our dictionary looks like this:" }, { "code": null, "e": 2536, "s": 2390, "text": "{'Las Vegas': 99870, 'Paducah': 752612, 'Atlanta': 2780400, 'Las Angeles': 9525067, 'Tampa': 9596961, 'Boulder': 17098246, 'Detroit': 3619342323}" }, { "code": null, "e": 2656, "s": 2536, "text": "Just to prove we can do this with the alphabetical feature as well, I will now sort it by the [0] position of the keys:" }, { "code": null, "e": 2802, "s": 2656, "text": "{'Atlanta': 2780400, 'Boulder': 17098246, 'Detroit': 3619342323, 'Las Angeles': 9525067, 'Las Vegas': 99870, 'Paducah': 752612, 'Tampa': 9596961}" }, { "code": null, "e": 3622, "s": 2802, "text": "Merging is one of the tools that the Pandas module provides that sets it apart from just using the dictionary data structure. In order to merge dictionaries together, we do not necessarily need to write a function, as we can simply use the update function contained within the dict class. However, I like to write a function to do so in order to copy the dictionary rather than mutating the other, as I often focus on retaining the form of data when programming. That being said, it is a relatively simple operation that mostly involves calls on the functions that are already provided in the dictionary type. The first thing we are going to do to write this merge function is consider our arguments and output, we want to provide two dictionaries and get a single dictionary back. Let us put that into a function call:" }, { "code": null, "e": 3661, "s": 3622, "text": "def merge_dicts(one: dict, two: dict):" }, { "code": null, "e": 4101, "s": 3661, "text": "Now we will want to copy the dictionary so that we do not end up mutating the original type, because that could be quite catastrophic if we were to accidentally destroy the data in the first one — especially if we were to mess up this function on the first try. Since we are not working with the individual data-types contained within our dictionary, there is no need to do a deep copy, so we can get by pretty easily using a shallow copy." }, { "code": null, "e": 4151, "s": 4101, "text": "temp: dict = one.copy()newdict: dict = one.copy()" }, { "code": null, "e": 4224, "s": 4151, "text": "Finally, we will call the update function and return our new dictionary:" }, { "code": null, "e": 4260, "s": 4224, "text": "newdict.update(two) return(newdict)" }, { "code": null, "e": 4301, "s": 4260, "text": "For a final result that looks like this:" }, { "code": null, "e": 4406, "s": 4301, "text": "def merge_dicts(one: dict, two: dict): newdict = one.copy() newdict.update(two) return(newdict)" }, { "code": null, "e": 4461, "s": 4406, "text": "Now we will create a new dictionary to call this with:" }, { "code": null, "e": 4558, "s": 4461, "text": "additional_cities: dict = { \"Dover\": 8323, \"Colorado Springs\": 4990, \"Seattle\": 95067,}" }, { "code": null, "e": 4621, "s": 4558, "text": "Now let us pass both of our dictionaries through our function!" }, { "code": null, "e": 4672, "s": 4621, "text": "allcities = merge_dicts(additional_cities, cities)" }, { "code": null, "e": 4696, "s": 4672, "text": "And this is the result:" }, { "code": null, "e": 4901, "s": 4696, "text": "{'Dover': 8323, 'Colorado Springs': 4990, 'Seattle': 95067, 'Detroit': 3619342323, 'Las Vegas': 99870, 'Las Angeles': 9525067, 'Boulder': 17098246, 'Atlanta': 2780400, 'Paducah': 752612, 'Tampa': 9596961}" }, { "code": null, "e": 4907, "s": 4901, "text": "Cool!" }, { "code": null, "e": 5400, "s": 4907, "text": "Dictionaries are often used to store data in Python. A lot of this data is iteratively added overtime, and sometimes there might be missing values or keys caught up in the mix than can create problems if we do not have a way to deal with them properly. For this problem, the solution is to use the setdefault() function that is included with the dictionary class. In the following example, I will do exactly that and default incoming keys without pairs to be assigned to the mean of our data:" }, { "code": null, "e": 5483, "s": 5400, "text": "allcities.setdefault(\"Unknown\", sum(allcities.values()) / len(allcities.values()))" }, { "code": null, "e": 5591, "s": 5483, "text": "This will append the default to our dictionary while also making incoming data default to these two values." }, { "code": null, "e": 6096, "s": 5591, "text": "As I mentioned before, the JSON data format is quite popular for sending, receiving, and even storing data for web-development and Data Science. However, likely one of the most popular formats for real data storage outside of a data base is Comma Separated Value, or CSV files. These files are great because they contain far less syntactical chars than a format like JSON. Using the CSV module, we can get a CSV reader that will translate our CSV files into data for us! Let us import it and try it out!:" }, { "code": null, "e": 6107, "s": 6096, "text": "import csv" }, { "code": null, "e": 6253, "s": 6107, "text": "Now we can create a new reader object by calling on the csv.DictReader() class with the open() method in order to get our CSV file into a string:" }, { "code": null, "e": 6304, "s": 6253, "text": "reader = csv.DictReader(open(\"spreader.csv\", \"r\"))" }, { "code": null, "e": 6390, "s": 6304, "text": "Now we can iterate that reader type, providing us with keys and corresponding values:" }, { "code": null, "e": 6496, "s": 6390, "text": "for row in reader: print(row){'hello': 'how', 'medium': 'is'}{'hello': 'everyone', 'medium': 'doing?'}" }, { "code": null, "e": 6589, "s": 6496, "text": "Finally, we can push these into a dictionary with the update() function that we used before:" }, { "code": null, "e": 6632, "s": 6589, "text": "for row in reader: z[row[\"Code\"]] = row" }, { "code": null, "e": 7012, "s": 6632, "text": "About a month ago, I wrote a really cool article on how you can actually visualize dictionaries in a tabular fashion just like you would a data frame. Since this was such a cool trick, I decided to add it at the end of this list so that dictionary conquerors could find a better way to look at their data. If you are interested in reading that article, you may check it out here:" }, { "code": null, "e": 7035, "s": 7012, "text": "towardsdatascience.com" } ]
Getting the return value of Javascript code in Selenium.
We can get the return value of Javascript code with Selenium webdriver. Selenium can run Javascript commands with the help of executeScript method. The Javascript command to be executed is passed as an argument to the method. We shall be returning the value from the Javascript code with the help of the keyword return. Also we have to add the statement import org.openqa.selenium.JavascriptExecutor to work with Javascript. JavascriptExecutor j = (JavascriptExecutor) driver; j.executeScript("return document.getElementsByName('txtSearchText')[0].value") Let us obtain the value entered in the edit box. The output should be Selenium. 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; import org.openqa.selenium.JavascriptExecutor; public class JavascriptValue{ 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/tutor_connect/index.php"; driver.get(url); driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS); // identify element and enter text WebElement t=driver.findElement(By.id("txtSearchText")); t.sendKeys("Selenium"); // Javascript executor to return value JavascriptExecutor j = (JavascriptExecutor) driver; String s = (String) j.executeScript("return document.getElementsByName('txtSearchText')[0].value"); System.out.print("Value is: " +s); driver.quit(); } }
[ { "code": null, "e": 1288, "s": 1062, "text": "We can get the return value of Javascript code with Selenium webdriver. Selenium can run Javascript commands with the help of executeScript method. The Javascript command to be executed is passed as an argument to the method." }, { "code": null, "e": 1487, "s": 1288, "text": "We shall be returning the value from the Javascript code with the help of the keyword return. Also we have to add the statement import org.openqa.selenium.JavascriptExecutor to work with Javascript." }, { "code": null, "e": 1618, "s": 1487, "text": "JavascriptExecutor j = (JavascriptExecutor) driver;\nj.executeScript(\"return document.getElementsByName('txtSearchText')[0].value\")" }, { "code": null, "e": 1698, "s": 1618, "text": "Let us obtain the value entered in the edit box. The output should be Selenium." }, { "code": null, "e": 1718, "s": 1698, "text": "Code Implementation" }, { "code": null, "e": 2769, "s": 1718, "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;\nimport org.openqa.selenium.JavascriptExecutor;\npublic class JavascriptValue{\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/tutor_connect/index.php\";\n driver.get(url);\n driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS);\n // identify element and enter text\n WebElement t=driver.findElement(By.id(\"txtSearchText\"));\n t.sendKeys(\"Selenium\");\n // Javascript executor to return value\n JavascriptExecutor j = (JavascriptExecutor) driver;\n String s = (String) j.executeScript(\"return document.getElementsByName('txtSearchText')[0].value\");\n System.out.print(\"Value is: \" +s);\n driver.quit();\n }\n}" } ]
jsoup - Using Selector Syntax
Following example will showcase use of selector methods after parsing an HTML String into a Document object. jsoup supports selectors similar to CSS Selectors. Document document = Jsoup.parse(html); Element sampleDiv = document.getElementById("sampleDiv"); Elements links = sampleDiv.getElementsByTag("a"); Where document − document object represents the HTML DOM. document − document object represents the HTML DOM. Jsoup − main class to parse the given HTML String. Jsoup − main class to parse the given HTML String. html − HTML String. html − HTML String. sampleDiv − Element object represent the html node element identified by id "sampleDiv". sampleDiv − Element object represent the html node element identified by id "sampleDiv". links − Elements object represents the multiple node elements identified by tag "a". links − Elements object represents the multiple node elements identified by tag "a". The document.select(expression) method parses the given CSS selector expression to select a html dom element. Create the following java program using any editor of your choice in say C:/> jsoup. JsoupTester.java import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; public class JsoupTester { public static void main(String[] args) { String html = "<html><head><title>Sample Title</title></head>" + "<body>" + "<p>Sample Content</p>" + "<div id='sampleDiv'><a href='www.google.com'>Google</a>" + "<h3><a>Sample</a><h3>" +"</div>" + "<div id='imageDiv' class='header'><img name='google' src='google.png' />" + "<img name='yahoo' src='yahoo.jpg' />" +"</div>" +"</body></html>"; Document document = Jsoup.parse(html); //a with href Elements links = document.select("a[href]"); for (Element link : links) { System.out.println("Href: " + link.attr("href")); System.out.println("Text: " + link.text()); } // img with src ending .png Elements pngs = document.select("img[src$=.png]"); for (Element png : pngs) { System.out.println("Name: " + png.attr("name")); } // div with class=header Element headerDiv = document.select("div.header").first(); System.out.println("Id: " + headerDiv.id()); // direct a after h3 Elements sampleLinks = document.select("h3 > a"); for (Element link : sampleLinks) { System.out.println("Text: " + link.text()); } } } Compile the class using javac compiler as follows: C:\jsoup>javac JsoupTester.java Now run the JsoupTester to see the result. C:\jsoup>java JsoupTester See the result. Href: www.google.com Text: Google Name: google Id: imageDiv Text: Sample Print Add Notes Bookmark this page
[ { "code": null, "e": 2190, "s": 2030, "text": "Following example will showcase use of selector methods after parsing an HTML String into a Document object. jsoup supports selectors similar to CSS Selectors." }, { "code": null, "e": 2338, "s": 2190, "text": "Document document = Jsoup.parse(html);\nElement sampleDiv = document.getElementById(\"sampleDiv\");\nElements links = sampleDiv.getElementsByTag(\"a\");\n" }, { "code": null, "e": 2344, "s": 2338, "text": "Where" }, { "code": null, "e": 2396, "s": 2344, "text": "document − document object represents the HTML DOM." }, { "code": null, "e": 2448, "s": 2396, "text": "document − document object represents the HTML DOM." }, { "code": null, "e": 2499, "s": 2448, "text": "Jsoup − main class to parse the given HTML String." }, { "code": null, "e": 2550, "s": 2499, "text": "Jsoup − main class to parse the given HTML String." }, { "code": null, "e": 2570, "s": 2550, "text": "html − HTML String." }, { "code": null, "e": 2590, "s": 2570, "text": "html − HTML String." }, { "code": null, "e": 2679, "s": 2590, "text": "sampleDiv − Element object represent the html node element identified by id \"sampleDiv\"." }, { "code": null, "e": 2768, "s": 2679, "text": "sampleDiv − Element object represent the html node element identified by id \"sampleDiv\"." }, { "code": null, "e": 2853, "s": 2768, "text": "links − Elements object represents the multiple node elements identified by tag \"a\"." }, { "code": null, "e": 2938, "s": 2853, "text": "links − Elements object represents the multiple node elements identified by tag \"a\"." }, { "code": null, "e": 3048, "s": 2938, "text": "The document.select(expression) method parses the given CSS selector expression to select a html dom element." }, { "code": null, "e": 3133, "s": 3048, "text": "Create the following java program using any editor of your choice in say C:/> jsoup." }, { "code": null, "e": 3150, "s": 3133, "text": "JsoupTester.java" }, { "code": null, "e": 4590, "s": 3150, "text": "import org.jsoup.Jsoup;\nimport org.jsoup.nodes.Document;\nimport org.jsoup.nodes.Element;\nimport org.jsoup.select.Elements;\n\npublic class JsoupTester {\n public static void main(String[] args) {\n \n String html = \"<html><head><title>Sample Title</title></head>\"\n + \"<body>\"\n + \"<p>Sample Content</p>\"\n + \"<div id='sampleDiv'><a href='www.google.com'>Google</a>\"\n + \"<h3><a>Sample</a><h3>\"\n +\"</div>\"\n + \"<div id='imageDiv' class='header'><img name='google' src='google.png' />\"\n + \"<img name='yahoo' src='yahoo.jpg' />\"\n +\"</div>\"\n +\"</body></html>\";\n Document document = Jsoup.parse(html);\n\n //a with href\n Elements links = document.select(\"a[href]\");\n\n for (Element link : links) {\n System.out.println(\"Href: \" + link.attr(\"href\"));\n System.out.println(\"Text: \" + link.text());\n }\n\n // img with src ending .png\n Elements pngs = document.select(\"img[src$=.png]\");\n\n for (Element png : pngs) {\n System.out.println(\"Name: \" + png.attr(\"name\"));\n }\n\n // div with class=header\n Element headerDiv = document.select(\"div.header\").first();\n System.out.println(\"Id: \" + headerDiv.id());\n \n // direct a after h3\n Elements sampleLinks = document.select(\"h3 > a\"); \n\n for (Element link : sampleLinks) {\n System.out.println(\"Text: \" + link.text());\n }\n }\n}" }, { "code": null, "e": 4641, "s": 4590, "text": "Compile the class using javac compiler as follows:" }, { "code": null, "e": 4674, "s": 4641, "text": "C:\\jsoup>javac JsoupTester.java\n" }, { "code": null, "e": 4717, "s": 4674, "text": "Now run the JsoupTester to see the result." }, { "code": null, "e": 4744, "s": 4717, "text": "C:\\jsoup>java JsoupTester\n" }, { "code": null, "e": 4760, "s": 4744, "text": "See the result." }, { "code": null, "e": 4834, "s": 4760, "text": "Href: www.google.com\nText: Google\nName: google\nId: imageDiv\nText: Sample\n" }, { "code": null, "e": 4841, "s": 4834, "text": " Print" }, { "code": null, "e": 4852, "s": 4841, "text": " Add Notes" } ]