title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Python | Toggle button in kivy using .kv file
24 Nov, 2021 Kivy is a platform independent GUI tool in Python. As it can be run on Android, IOS, linux and Windows etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktops applications. ???????? Kivy Tutorial – Learn Kivy with Examples. The ToggleButton widget acts like a checkbox. When you touch or click it, the state toggles between ‘normal’ and ‘down’ (as opposed to a Button that is only ‘down’ as long as it is pressed).Toggle buttons can also be grouped to make radio buttons – only one button in a group can be in a ‘down’ state. The group name can be a string or any other hashable Python object: btn1 = ToggleButton(text='Male', group='sex', ) btn2 = ToggleButton(text='Female', group='sex', state='down') btn3 = ToggleButton(text='Mixed', group='sex') Only one of the buttons can be ‘down’/checked at the same time. To configure the ToggleButton, you can use the same properties that you can use for a Button class. Basic Approach: 1) import kivy 2) import kivyApp 3) import toggle button 4) import Gridlayout 5) Set minimum version(optional) 6) create layout class 7) create App class 8) create the, kv file 9) return Layout/widget/Class(according to requirement) 10) Run an instance of the class Implementation of the Approach:.py code: Python3 # Program to explain how to use Toggle button in kivy # import kivy module import kivy # base Class of your App inherits from the App class. # app:always refers to the instance of your application from kivy.app import App # this restrict the kivy version i.e # below this kivy version you cannot # use the app or software kivy.require('1.9.0') # The ToggleButton widget acts like a checkbox.# To use this you must have to import it.from kivy.uix.togglebutton import ToggleButton # The GridLayout arranges children in a matrix.# It takes the available space and divides it# into columns and rows, then adds# widgets to the resulting “cells”.from kivy.uix.gridlayout import GridLayout # Create the Layout Classclass Toggle_btn(GridLayout): pass # Create the App Classclass ToggleApp(App): def build(self): return Toggle_btn() # Run the Appif __name__=='__main__': ToggleApp().run() .kv code: Python3 # .kv file implementation of the code <Toggle_btn>: # Columns divides screen in two parts cols:2 # Create Toggle button 1 RelativeLayout: canvas: Color: rgb: 0, 0, 1 Rectangle: size: root.width, root.height ToggleButton: size_hint: None, None size: 0.25 * root.width, 0.25 * root.height pos: 0.125 * root.width, 0.350 * root.height text: 'Toggle Button 1' group: 'geometry' # Create Toggle button 2 RelativeLayout: canvas: Color: rgb: 0, 1, 1 Rectangle: size: root.width, root.height ToggleButton: size_hint: None, None size: 0.25 * root.width, 0.25 * root.height pos: 0.125 * root.width, 0.350 * root.height text: 'Toggle Button 2' group: 'geometry' Output: anikakapoor gabaa406 abhishek0719kadiyan Python-gui Python-kivy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Nov, 2021" }, { "code": null, "e": 265, "s": 28, "text": "Kivy is a platform independent GUI tool in Python. As it can be run on Android, IOS, linux and Windows etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktops applications. " }, { "code": null, "e": 316, "s": 265, "text": "???????? Kivy Tutorial – Learn Kivy with Examples." }, { "code": null, "e": 689, "s": 318, "text": "The ToggleButton widget acts like a checkbox. When you touch or click it, the state toggles between ‘normal’ and ‘down’ (as opposed to a Button that is only ‘down’ as long as it is pressed).Toggle buttons can also be grouped to make radio buttons – only one button in a group can be in a ‘down’ state. The group name can be a string or any other hashable Python object: " }, { "code": null, "e": 846, "s": 689, "text": "btn1 = ToggleButton(text='Male', group='sex', )\nbtn2 = ToggleButton(text='Female', group='sex', state='down')\nbtn3 = ToggleButton(text='Mixed', group='sex')" }, { "code": null, "e": 1011, "s": 846, "text": "Only one of the buttons can be ‘down’/checked at the same time. To configure the ToggleButton, you can use the same properties that you can use for a Button class. " }, { "code": null, "e": 1294, "s": 1011, "text": "Basic Approach:\n\n1) import kivy\n2) import kivyApp\n3) import toggle button\n4) import Gridlayout\n5) Set minimum version(optional)\n6) create layout class\n7) create App class\n8) create the, kv file\n9) return Layout/widget/Class(according to requirement)\n10) Run an instance of the class" }, { "code": null, "e": 1337, "s": 1294, "text": "Implementation of the Approach:.py code: " }, { "code": null, "e": 1345, "s": 1337, "text": "Python3" }, { "code": "# Program to explain how to use Toggle button in kivy # import kivy module import kivy # base Class of your App inherits from the App class. # app:always refers to the instance of your application from kivy.app import App # this restrict the kivy version i.e # below this kivy version you cannot # use the app or software kivy.require('1.9.0') # The ToggleButton widget acts like a checkbox.# To use this you must have to import it.from kivy.uix.togglebutton import ToggleButton # The GridLayout arranges children in a matrix.# It takes the available space and divides it# into columns and rows, then adds# widgets to the resulting “cells”.from kivy.uix.gridlayout import GridLayout # Create the Layout Classclass Toggle_btn(GridLayout): pass # Create the App Classclass ToggleApp(App): def build(self): return Toggle_btn() # Run the Appif __name__=='__main__': ToggleApp().run()", "e": 2276, "s": 1345, "text": null }, { "code": null, "e": 2288, "s": 2276, "text": ".kv code: " }, { "code": null, "e": 2296, "s": 2288, "text": "Python3" }, { "code": "# .kv file implementation of the code <Toggle_btn>: # Columns divides screen in two parts cols:2 # Create Toggle button 1 RelativeLayout: canvas: Color: rgb: 0, 0, 1 Rectangle: size: root.width, root.height ToggleButton: size_hint: None, None size: 0.25 * root.width, 0.25 * root.height pos: 0.125 * root.width, 0.350 * root.height text: 'Toggle Button 1' group: 'geometry' # Create Toggle button 2 RelativeLayout: canvas: Color: rgb: 0, 1, 1 Rectangle: size: root.width, root.height ToggleButton: size_hint: None, None size: 0.25 * root.width, 0.25 * root.height pos: 0.125 * root.width, 0.350 * root.height text: 'Toggle Button 2' group: 'geometry'", "e": 3209, "s": 2296, "text": null }, { "code": null, "e": 3219, "s": 3209, "text": "Output: " }, { "code": null, "e": 3233, "s": 3221, "text": "anikakapoor" }, { "code": null, "e": 3242, "s": 3233, "text": "gabaa406" }, { "code": null, "e": 3262, "s": 3242, "text": "abhishek0719kadiyan" }, { "code": null, "e": 3273, "s": 3262, "text": "Python-gui" }, { "code": null, "e": 3285, "s": 3273, "text": "Python-kivy" }, { "code": null, "e": 3292, "s": 3285, "text": "Python" }, { "code": null, "e": 3390, "s": 3292, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3422, "s": 3390, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3449, "s": 3422, "text": "Python Classes and Objects" }, { "code": null, "e": 3470, "s": 3449, "text": "Python OOPs Concepts" }, { "code": null, "e": 3493, "s": 3470, "text": "Introduction To PYTHON" }, { "code": null, "e": 3549, "s": 3493, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 3580, "s": 3549, "text": "Python | os.path.join() method" }, { "code": null, "e": 3622, "s": 3580, "text": "Check if element exists in list in Python" }, { "code": null, "e": 3664, "s": 3622, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 3703, "s": 3664, "text": "Python | Get unique values from a list" } ]
Program to implement Inverse Interpolation using Lagrange Formula
27 Dec, 2021 Given task is to find the value of x for a given y of an unknown function y = f(x) where values of some points (x, y) pairs are given.Let, y = f(x) be an unknown function where x in an independent variable. For different values of x, say [Tex]x_k, k=0, 1, 2, 3...m) [/Tex]values of respective [Tex]y_k = f(x_k), k=0, 1, 2, 3...m) [/Tex]given.The process of finding the value of the independent variable x for a given value of y lying between two tabulated values with the help of the given set of observation for an unknown function is known as Inverse Interpolation.This is often used to check whether the correctness of output y for an unknown function f i.e how much argument x for this output y differs from the original input.The problem of inverse interpolation can be solved using Lagrange’s Formula.Lagrange’s Formula: The formula for inverse interpolation is similar to interpolation formula but few changes.Here to solve the problem of inverse interpolation the places of x and y are interchanged. The formula for inverse interpolation is:This method can even be used when the points are unequally spaced. Here x is expressed as a function of y.Examples: Input: Find the value of x where y = 4.5 and the given points are: Output: 2.79501 Explanation: Here num of data points given = 4 and y = 4.5 So, putting the values of all x and y in the inverse interpolation formula given above we get, From here we get, The value of x = 2.79501 where the value of y = 4.5 Graph: Algorithm: Here, data is a list of points consisting of x and y and n is the num of data points. STEP – 1 : Initialize the final value x = 0 STEP – 2 : FOR i = 1 to n do STEP – 3 : Initialize xi = data[i].x STEP – 4 : FOR j = 1 to n do STEP – 5 : IF i != j do STEP – 6 : Multiply xi by ( y – data[j].y ) and divide by ( data[i].y – data[j].y ) ENDIF ENDFOR STEP – 7 : Add xi to x ENDFOR STEP – 8 : Return final value of x STEP – 9 : END Implementation: C++ Java Python3 C# Javascript // C++ code for solving inverse interpolation #include <bits/stdc++.h>using namespace std; // Consider a structure// to keep each pair of// x and y togetherstruct Data { double x, y;}; // Function to calculate// the inverse interpolation double inv_interpolate(Data d[], int n, double y){ // Initialize final x double x = 0; int i, j; for (i = 0; i < n; i++) { // Calculate each term // of the given formula double xi = d[i].x; for (j = 0; j < n; j++) { if (j != i) { xi = xi * (y - d[j].y) / (d[i].y - d[j].y); } } // Add term to final result x += xi; } return x;} // Driver Codeint main(){ // Sample dataset of 4 points // Here we find the value // of x when y = 4.5 Data d[] = { { 1.27, 2.3 }, { 2.25, 2.95 }, { 2.5, 3.5 }, { 3.6, 5.1 } }; // Size of dataset int n = 4; // Sample y value double y = 4.5; // Using the Inverse Interpolation // function to find the // value of x when y = 4.5 cout << "Value of x at y = 4.5 : " << inv_interpolate(d, n, y); return 0;} // Java code for solving inverse interpolationclass GFG{ // Consider a structure// to keep each pair of// x and y togetherstatic class Data{ double x, y; public Data(double x, double y) { super(); this.x = x; this.y = y; } }; // Function to calculate// the inverse interpolationstatic double inv_interpolate(Data []d, int n, double y){ // Initialize final x double x = 0; int i, j; for (i = 0; i < n; i++) { // Calculate each term // of the given formula double xi = d[i].x; for (j = 0; j < n; j++) { if (j != i) { xi = xi * (y - d[j].y) / (d[i].y - d[j].y); } } // Add term to final result x += xi; } return x;} // Driver Codepublic static void main(String[] args){ // Sample dataset of 4 points // Here we find the value // of x when y = 4.5 Data []d = { new Data( 1.27, 2.3 ), new Data( 2.25, 2.95 ), new Data( 2.5, 3.5 ), new Data( 3.6, 5.1 ) }; // Size of dataset int n = 4; // Sample y value double y = 4.5; // Using the Inverse Interpolation // function to find the // value of x when y = 4.5 System.out.printf("Value of x at y = 4.5 : %.5f" , inv_interpolate(d, n, y));}} // This code is contributed by Rajput-Ji # Python3 code for solving# inverse interpolation # Consider a structure# to keep each pair of# x and y togetherclass Data: def __init__(self, x, y): self.x = x self.y = y # Function to calculate# the inverse interpolationdef inv_interpolate(d: list, n: int, y: float) -> float: # Initialize final x x = 0 for i in range(n): # Calculate each term # of the given formula xi = d[i].x for j in range(n): if j != i: xi = (xi * (y - d[j].y) / (d[i].y - d[j].y)) # Add term to final result x += xi return x # Driver Codeif __name__ == "__main__": # Sample dataset of 4 points # Here we find the value # of x when y = 4.5 d = [Data(1.27, 2.3), Data(2.25, 2.95), Data(2.5, 3.5), Data(3.6, 5.1)] # Size of dataset n = 4 # Sample y value y = 4.5 # Using the Inverse Interpolation # function to find the # value of x when y = 4.5 print("Value of x at y = 4.5 :", round(inv_interpolate(d, n, y), 5)) # This code is contributed by# sanjeev2552 // C# code for solving inverse interpolationusing System; class GFG{ // Consider a structure to keep// each pair of x and y togetherclass Data{ public double x, y; public Data(double x, double y) { this.x = x; this.y = y; }}; // Function to calculate the// inverse interpolationstatic double inv_interpolate(Data []d, int n, double y){ // Initialize readonly x double x = 0; int i, j; for (i = 0; i < n; i++) { // Calculate each term // of the given formula double xi = d[i].x; for (j = 0; j < n; j++) { if (j != i) { xi = xi * (y - d[j].y) / (d[i].y - d[j].y); } } // Add term to readonly result x += xi; } return x;} // Driver Codepublic static void Main(String[] args){ // Sample dataset of 4 points // Here we find the value // of x when y = 4.5 Data []d = {new Data(1.27, 2.3), new Data(2.25, 2.95), new Data(2.5, 3.5), new Data(3.6, 5.1)}; // Size of dataset int n = 4; // Sample y value double y = 4.5; // Using the Inverse Interpolation // function to find the // value of x when y = 4.5 Console.Write("Value of x at y = 4.5 : {0:f5}", inv_interpolate(d, n, y));}} // This code is contributed by Rajput-Ji <script>// javascript code for solving inverse interpolation // Consider a structure // to keep each pair of // x and y together class Data { constructor(x , y) { this.x = x; this.y = y; } }; // Function to calculate // the inverse interpolation function inv_interpolate( d , n , y) { // Initialize final x var x = 0; var i, j; for (i = 0; i < n; i++) { // Calculate each term // of the given formula var xi = d[i].x; for (j = 0; j < n; j++) { if (j != i) { xi = xi * (y - d[j].y) / (d[i].y - d[j].y); } } // Add term to final result x += xi; } return x; } // Driver Code // Sample dataset of 4 points // Here we find the value // of x when y = 4.5 var d = [ new Data(1.27, 2.3), new Data(2.25, 2.95), new Data(2.5, 3.5), new Data(3.6, 5.1) ]; // Size of dataset var n = 4; // Sample y value var y = 4.5; // Using the Inverse Interpolation // function to find the // value of x when y = 4.5 document.write("Value of x at y = 4.5 : ", inv_interpolate(d, n, y).toFixed(5)); // This code is contributed by gauravrajput1</script> Value of x at y = 4.5 : 2.79501 Complexity: The time complexity of the given solution is O(n^2) and space complexity is O(1) Rajput-Ji sanjeev2552 GauravRajput1 Algebra Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Operators in C / C++ Prime Numbers Minimum number of jumps to reach end Program to find GCD or HCF of two numbers Find minimum number of coins that make a given value The Knight's tour problem | Backtracking-1 Algorithm to solve Rubik's Cube Program for Decimal to Binary Conversion Modulo 10^9+7 (1000000007)
[ { "code": null, "e": 52, "s": 24, "text": "\n27 Dec, 2021" }, { "code": null, "e": 1223, "s": 52, "text": "Given task is to find the value of x for a given y of an unknown function y = f(x) where values of some points (x, y) pairs are given.Let, y = f(x) be an unknown function where x in an independent variable. For different values of x, say [Tex]x_k, k=0, 1, 2, 3...m) [/Tex]values of respective [Tex]y_k = f(x_k), k=0, 1, 2, 3...m) [/Tex]given.The process of finding the value of the independent variable x for a given value of y lying between two tabulated values with the help of the given set of observation for an unknown function is known as Inverse Interpolation.This is often used to check whether the correctness of output y for an unknown function f i.e how much argument x for this output y differs from the original input.The problem of inverse interpolation can be solved using Lagrange’s Formula.Lagrange’s Formula: The formula for inverse interpolation is similar to interpolation formula but few changes.Here to solve the problem of inverse interpolation the places of x and y are interchanged. The formula for inverse interpolation is:This method can even be used when the points are unequally spaced. Here x is expressed as a function of y.Examples: " }, { "code": null, "e": 1292, "s": 1223, "text": "Input: Find the value of x where y = 4.5 and the given points are: " }, { "code": null, "e": 1534, "s": 1292, "text": "Output: 2.79501 Explanation: Here num of data points given = 4 and y = 4.5 So, putting the values of all x and y in the inverse interpolation formula given above we get, From here we get, The value of x = 2.79501 where the value of y = 4.5 " }, { "code": null, "e": 1543, "s": 1534, "text": "Graph: " }, { "code": null, "e": 1641, "s": 1543, "text": "Algorithm: Here, data is a list of points consisting of x and y and n is the num of data points. " }, { "code": null, "e": 2026, "s": 1641, "text": "STEP – 1 : Initialize the final value x = 0 STEP – 2 : FOR i = 1 to n do STEP – 3 : Initialize xi = data[i].x STEP – 4 : FOR j = 1 to n do STEP – 5 : IF i != j do STEP – 6 : Multiply xi by ( y – data[j].y ) and divide by ( data[i].y – data[j].y ) ENDIF ENDFOR STEP – 7 : Add xi to x ENDFOR STEP – 8 : Return final value of x STEP – 9 : END " }, { "code": null, "e": 2044, "s": 2026, "text": "Implementation: " }, { "code": null, "e": 2048, "s": 2044, "text": "C++" }, { "code": null, "e": 2053, "s": 2048, "text": "Java" }, { "code": null, "e": 2061, "s": 2053, "text": "Python3" }, { "code": null, "e": 2064, "s": 2061, "text": "C#" }, { "code": null, "e": 2075, "s": 2064, "text": "Javascript" }, { "code": "// C++ code for solving inverse interpolation #include <bits/stdc++.h>using namespace std; // Consider a structure// to keep each pair of// x and y togetherstruct Data { double x, y;}; // Function to calculate// the inverse interpolation double inv_interpolate(Data d[], int n, double y){ // Initialize final x double x = 0; int i, j; for (i = 0; i < n; i++) { // Calculate each term // of the given formula double xi = d[i].x; for (j = 0; j < n; j++) { if (j != i) { xi = xi * (y - d[j].y) / (d[i].y - d[j].y); } } // Add term to final result x += xi; } return x;} // Driver Codeint main(){ // Sample dataset of 4 points // Here we find the value // of x when y = 4.5 Data d[] = { { 1.27, 2.3 }, { 2.25, 2.95 }, { 2.5, 3.5 }, { 3.6, 5.1 } }; // Size of dataset int n = 4; // Sample y value double y = 4.5; // Using the Inverse Interpolation // function to find the // value of x when y = 4.5 cout << \"Value of x at y = 4.5 : \" << inv_interpolate(d, n, y); return 0;}", "e": 3296, "s": 2075, "text": null }, { "code": "// Java code for solving inverse interpolationclass GFG{ // Consider a structure// to keep each pair of// x and y togetherstatic class Data{ double x, y; public Data(double x, double y) { super(); this.x = x; this.y = y; } }; // Function to calculate// the inverse interpolationstatic double inv_interpolate(Data []d, int n, double y){ // Initialize final x double x = 0; int i, j; for (i = 0; i < n; i++) { // Calculate each term // of the given formula double xi = d[i].x; for (j = 0; j < n; j++) { if (j != i) { xi = xi * (y - d[j].y) / (d[i].y - d[j].y); } } // Add term to final result x += xi; } return x;} // Driver Codepublic static void main(String[] args){ // Sample dataset of 4 points // Here we find the value // of x when y = 4.5 Data []d = { new Data( 1.27, 2.3 ), new Data( 2.25, 2.95 ), new Data( 2.5, 3.5 ), new Data( 3.6, 5.1 ) }; // Size of dataset int n = 4; // Sample y value double y = 4.5; // Using the Inverse Interpolation // function to find the // value of x when y = 4.5 System.out.printf(\"Value of x at y = 4.5 : %.5f\" , inv_interpolate(d, n, y));}} // This code is contributed by Rajput-Ji", "e": 4703, "s": 3296, "text": null }, { "code": "# Python3 code for solving# inverse interpolation # Consider a structure# to keep each pair of# x and y togetherclass Data: def __init__(self, x, y): self.x = x self.y = y # Function to calculate# the inverse interpolationdef inv_interpolate(d: list, n: int, y: float) -> float: # Initialize final x x = 0 for i in range(n): # Calculate each term # of the given formula xi = d[i].x for j in range(n): if j != i: xi = (xi * (y - d[j].y) / (d[i].y - d[j].y)) # Add term to final result x += xi return x # Driver Codeif __name__ == \"__main__\": # Sample dataset of 4 points # Here we find the value # of x when y = 4.5 d = [Data(1.27, 2.3), Data(2.25, 2.95), Data(2.5, 3.5), Data(3.6, 5.1)] # Size of dataset n = 4 # Sample y value y = 4.5 # Using the Inverse Interpolation # function to find the # value of x when y = 4.5 print(\"Value of x at y = 4.5 :\", round(inv_interpolate(d, n, y), 5)) # This code is contributed by# sanjeev2552", "e": 5849, "s": 4703, "text": null }, { "code": "// C# code for solving inverse interpolationusing System; class GFG{ // Consider a structure to keep// each pair of x and y togetherclass Data{ public double x, y; public Data(double x, double y) { this.x = x; this.y = y; }}; // Function to calculate the// inverse interpolationstatic double inv_interpolate(Data []d, int n, double y){ // Initialize readonly x double x = 0; int i, j; for (i = 0; i < n; i++) { // Calculate each term // of the given formula double xi = d[i].x; for (j = 0; j < n; j++) { if (j != i) { xi = xi * (y - d[j].y) / (d[i].y - d[j].y); } } // Add term to readonly result x += xi; } return x;} // Driver Codepublic static void Main(String[] args){ // Sample dataset of 4 points // Here we find the value // of x when y = 4.5 Data []d = {new Data(1.27, 2.3), new Data(2.25, 2.95), new Data(2.5, 3.5), new Data(3.6, 5.1)}; // Size of dataset int n = 4; // Sample y value double y = 4.5; // Using the Inverse Interpolation // function to find the // value of x when y = 4.5 Console.Write(\"Value of x at y = 4.5 : {0:f5}\", inv_interpolate(d, n, y));}} // This code is contributed by Rajput-Ji", "e": 7279, "s": 5849, "text": null }, { "code": "<script>// javascript code for solving inverse interpolation // Consider a structure // to keep each pair of // x and y together class Data { constructor(x , y) { this.x = x; this.y = y; } }; // Function to calculate // the inverse interpolation function inv_interpolate( d , n , y) { // Initialize final x var x = 0; var i, j; for (i = 0; i < n; i++) { // Calculate each term // of the given formula var xi = d[i].x; for (j = 0; j < n; j++) { if (j != i) { xi = xi * (y - d[j].y) / (d[i].y - d[j].y); } } // Add term to final result x += xi; } return x; } // Driver Code // Sample dataset of 4 points // Here we find the value // of x when y = 4.5 var d = [ new Data(1.27, 2.3), new Data(2.25, 2.95), new Data(2.5, 3.5), new Data(3.6, 5.1) ]; // Size of dataset var n = 4; // Sample y value var y = 4.5; // Using the Inverse Interpolation // function to find the // value of x when y = 4.5 document.write(\"Value of x at y = 4.5 : \", inv_interpolate(d, n, y).toFixed(5)); // This code is contributed by gauravrajput1</script>", "e": 8656, "s": 7279, "text": null }, { "code": null, "e": 8688, "s": 8656, "text": "Value of x at y = 4.5 : 2.79501" }, { "code": null, "e": 8784, "s": 8690, "text": "Complexity: The time complexity of the given solution is O(n^2) and space complexity is O(1) " }, { "code": null, "e": 8794, "s": 8784, "text": "Rajput-Ji" }, { "code": null, "e": 8806, "s": 8794, "text": "sanjeev2552" }, { "code": null, "e": 8820, "s": 8806, "text": "GauravRajput1" }, { "code": null, "e": 8828, "s": 8820, "text": "Algebra" }, { "code": null, "e": 8841, "s": 8828, "text": "Mathematical" }, { "code": null, "e": 8854, "s": 8841, "text": "Mathematical" }, { "code": null, "e": 8952, "s": 8854, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8976, "s": 8952, "text": "Merge two sorted arrays" }, { "code": null, "e": 8997, "s": 8976, "text": "Operators in C / C++" }, { "code": null, "e": 9011, "s": 8997, "text": "Prime Numbers" }, { "code": null, "e": 9048, "s": 9011, "text": "Minimum number of jumps to reach end" }, { "code": null, "e": 9090, "s": 9048, "text": "Program to find GCD or HCF of two numbers" }, { "code": null, "e": 9143, "s": 9090, "text": "Find minimum number of coins that make a given value" }, { "code": null, "e": 9186, "s": 9143, "text": "The Knight's tour problem | Backtracking-1" }, { "code": null, "e": 9218, "s": 9186, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 9259, "s": 9218, "text": "Program for Decimal to Binary Conversion" } ]
DP on Trees | Set-3 ( Diameter of N-ary Tree )
16 Jun, 2022 Given an N-ary tree T of N nodes, the task is to calculate the longest path between any two nodes(also known as the diameter of the tree). Example 1: Example 2: Different approaches to solving these problems have already been discussed: https://www.geeksforgeeks.org/diameter-n-ary-tree/ https://www.geeksforgeeks.org/diameter-n-ary-tree-using-bfs/ In this post, we will be discussing an approach that uses Dynamic Programming on Trees. Prerequisites: DP on Trees | Set 1 DP on Trees | Set 2 There are two possibilities for the diameter to exist: Case 1: Suppose the diameter starts from a node and ends at some node in its subtree. Let’s say that there exists a node x such that the longest path starts from node x and goes into its subtree and ends at some node in the subtree itself. Let’s define this path length by dp1[x]. Case 2: Suppose the diameter or the longest path starts in the subtree of a node x, passes through it, and ends in its subtree. Let’s define this path by dp2[x]. If for all nodes x, we take a maximum of dp1[x], and dp2[x], then we will get the diameter of the tree. For the case-1, to find dp1[node], we need to find the maximum of all dp1[x], where x is the children of node. And dp1[node] will be equal to 1 + max(dp1[children1], dp1[children2], ..). For the case-2, to find dp2[node], we need to find the two maximum of all dp1[x], where x is the children of node. And dp2[node] will be equal to 1 + max 2 of(dp1[children1], dp1[children2], ..) + max(dp1[children1], dp1[children2], ..). This will ensure a complete path passing through the current node into its subtree.We can easily run a DFS and find the maximum of both dp1[node] and dp2[node] for every to get the diameter of the tree. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to find diameter of a tree// using DFS.#include <bits/stdc++.h>using namespace std; int diameter = -1; // Function to find the diameter of the tree// using Dynamic Programmingint dfs(int node, int parent, int dp1[], int dp2[], list<int>* adj){ // Store the first maximum and secondmax int firstmax = -1; int secondmax = -1; // Traverse for all children of node for (auto i = adj[node].begin(); i != adj[node].end(); ++i) { if (*i == parent) continue; // Call DFS function again dfs(*i, node, dp1, dp2, adj); // Find first max if (firstmax == -1) { firstmax = dp1[*i]; } else if (dp1[*i] >= firstmax) // Secondmaximum { secondmax = firstmax; firstmax = dp1[*i]; } else if (dp1[*i] > secondmax) // Find secondmaximum { secondmax = dp1[*i]; } } // Base case for every node dp1[node] = 1; if (firstmax != -1) // Add dp1[node] += firstmax; // Find dp[2] if (secondmax != -1) dp2[node] = 1 + firstmax + secondmax; diameter = max(diameter, max(dp1[node], dp2[node])); // Return maximum of both return max(dp1[node], dp2[node]);} // Driver Codeint main(){ int n = 5; /* Constructed tree is 1 / \ 2 3 / \ 4 5 */ list<int>* adj = new list<int>[n + 1]; /*create undirected edges */ adj[1].push_back(2); adj[2].push_back(1); adj[1].push_back(3); adj[3].push_back(1); adj[2].push_back(4); adj[4].push_back(2); adj[2].push_back(5); adj[5].push_back(2); int dp1[n + 1], dp2[n + 1]; memset(dp1, 0, sizeof dp1); memset(dp2, 0, sizeof dp2); // Find diameter by calling function dfs(1, 1, dp1, dp2, adj) cout << "Diameter of the given tree is " << diameter << endl; return 0;} // Java program to find diameter of a tree using DFS.import java.util.*;public class Main{ // Function to find the diameter of the tree // using Dynamic Programming static int dfs(int node, int parent, int[] dp1, int[] dp2, Vector<Vector<Integer>> adj) { // Store the first maximum and secondmax int firstmax = -1; int secondmax = -1; // Traverse for all children of node for (int i = 0; i < adj.get(node).size(); ++i) { if (adj.get(node).get(i) == parent) continue; // Call DFS function again dfs(adj.get(node).get(i), node, dp1, dp2, adj); // Find first max if (firstmax == -1) { firstmax = dp1[adj.get(node).get(i)]; } // Secondmaximum else if (dp1[adj.get(node).get(i)] >= firstmax) { secondmax = firstmax; firstmax = dp1[adj.get(node).get(i)]; } // Find secondmaximum else if (dp1[adj.get(node).get(i)] > secondmax) { secondmax = dp1[adj.get(node).get(i)]; } } // Base case for every node dp1[node] = 1; if (firstmax != -1) // Add dp1[node] += firstmax; // Find dp[2] if (secondmax != -1) dp2[node] = 1 + firstmax + secondmax; // Return maximum of both return Math.max(dp1[node], dp2[node]); } public static void main(String[] args) { int n = 5; /* Constructed tree is 1 / \ 2 3 / \ 4 5 */ Vector<Vector<Integer>> adj = new Vector<Vector<Integer>>(); for(int i = 0; i < n + 1; i++) { adj.add(new Vector<Integer>()); } /*create undirected edges */ adj.get(1).add(2); adj.get(2).add(1); adj.get(1).add(3); adj.get(3).add(1); adj.get(2).add(4); adj.get(4).add(2); adj.get(2).add(5); adj.get(5).add(2); int[] dp1 = new int[n + 1]; int[] dp2 = new int[n + 1]; for(int i = 0; i < n + 1; i++) { dp1[i] = 0; dp2[i] = 0; } // Find diameter by calling function System.out.println("Diameter of the given tree is " + dfs(1, 1, dp1, dp2, adj)); }} // This code is contributed by divyeshrabadiya07. # Python3 program to find diameter# of a tree using DFS. # Function to find the diameter of the# tree using Dynamic Programmingdef dfs(node, parent, dp1, dp2, adj): # Store the first maximum and secondmax firstmax, secondmax = -1, -1 # Traverse for all children of node for i in adj[node]: if i == parent: continue # Call DFS function again dfs(i, node, dp1, dp2, adj) # Find first max if firstmax == -1: firstmax = dp1[i] elif dp1[i] >= firstmax: # Secondmaximum secondmax = firstmax firstmax = dp1[i] elif dp1[i] > secondmax: # Find secondmaximum secondmax = dp1[i] # Base case for every node dp1[node] = 1 if firstmax != -1: # Add dp1[node] += firstmax # Find dp[2] if secondmax != -1: dp2[node] = 1 + firstmax + secondmax diameter = max(diameter, max(dp1[node], dp2[node])); # Return maximum of both return max(dp1[node], dp2[node]) # Driver Codeif __name__ == "__main__": n, diameter = 5, -1 adj = [[] for i in range(n + 1)] # create undirected edges adj[1].append(2) adj[2].append(1) adj[1].append(3) adj[3].append(1) adj[2].append(4) adj[4].append(2) adj[2].append(5) adj[5].append(2) dp1 = [0] * (n + 1) dp2 = [0] * (n + 1) # Find diameter by calling function dfs(1, 1, dp1, dp2, adj) print("Diameter of the given tree is", diameter ) # This code is contributed by Rituraj Jain // C# program to find diameter of a tree using DFS.using System;using System.Collections.Generic;class GFG { // Function to find the diameter of the tree // using Dynamic Programming static int dfs(int node, int parent, int[] dp1, int[] dp2, List<List<int>> adj) { // Store the first maximum and secondmax int firstmax = -1; int secondmax = -1; // Traverse for all children of node for (int i = 0; i < adj[node].Count; ++i) { if (adj[node][i] == parent) continue; // Call DFS function again dfs(adj[node][i], node, dp1, dp2, adj); // Find first max if (firstmax == -1) { firstmax = dp1[adj[node][i]]; } // Secondmaximum else if (dp1[adj[node][i]] >= firstmax) { secondmax = firstmax; firstmax = dp1[adj[node][i]]; } // Find secondmaximum else if (dp1[adj[node][i]] > secondmax) { secondmax = dp1[adj[node][i]]; } } // Base case for every node dp1[node] = 1; if (firstmax != -1) // Add dp1[node] += firstmax; // Find dp[2] if (secondmax != -1) dp2[node] = 1 + firstmax + secondmax; // diameter = Math.Max(diameter, Math.Max(dp1[node], dp2[node])); // Return maximum of both return Math.Max(dp1[node], dp2[node]); } static void Main() { int n = 5; /* Constructed tree is 1 / \ 2 3 / \ 4 5 */ List<List<int>> adj = new List<List<int>>(); for(int i = 0; i < n + 1; i++) { adj.Add(new List<int>()); } /*create undirected edges */ adj[1].Add(2); adj[2].Add(1); adj[1].Add(3); adj[3].Add(1); adj[2].Add(4); adj[4].Add(2); adj[2].Add(5); adj[5].Add(2); int[] dp1 = new int[n + 1]; int[] dp2 = new int[n + 1]; for(int i = 0; i < n + 1; i++) { dp1[i] = 0; dp2[i] = 0; } // Find diameter by calling function Console.WriteLine("Diameter of the given tree is " + dfs(1, 1, dp1, dp2, adj)); }} // This code is contributed by decode2207. <script> // JavaScript program to find diameter of a tree using DFS. let diameter = -1; // Function to find the diameter of the tree // using Dynamic Programming function dfs(node, parent, dp1, dp2, adj) { // Store the first maximum and secondmax let firstmax = -1; let secondmax = -1; // Traverse for all children of node for (let i = 0; i < adj[node].length; ++i) { if (adj[node][i] == parent) continue; // Call DFS function again dfs(adj[node][i], node, dp1, dp2, adj); // Find first max if (firstmax == -1) { firstmax = dp1[adj[node][i]]; } // Secondmaximum else if (dp1[adj[node][i]] >= firstmax) { secondmax = firstmax; firstmax = dp1[adj[node][i]]; } // Find secondmaximum else if (dp1[adj[node][i]] > secondmax) { secondmax = dp1[adj[node][i]]; } } // Base case for every node dp1[node] = 1; if (firstmax != -1) // Add dp1[node] += firstmax; // Find dp[2] if (secondmax != -1) dp2[node] = 1 + firstmax + secondmax; diameter = Math.max(diameter, Math.max(dp1[node], dp2[node])); // Return maximum of both return Math.max(dp1[node], dp2[node]); } let n = 5; /* Constructed tree is 1 / \ 2 3 / \ 4 5 */ let adj = new Array(n + 1); for(let i = 0; i < n + 1; i++) { adj[i] = []; } /*create undirected edges */ adj[1].push(2); adj[2].push(1); adj[1].push(3); adj[3].push(1); adj[2].push(4); adj[4].push(2); adj[2].push(5); adj[5].push(2); let dp1 = new Array(n + 1); let dp2 = new Array(n + 1); dp1.fill(0); dp2.fill(0); // Find diameter by calling function dfs(1, 1, dp1, dp2, adj) document.write("Diameter of the given tree is " + diameter); </script> Diameter of the given tree is 4 Time Complexity: O(n), as we are using recursion to traverse n times, where n is the total number of nodes in the tree. Auxiliary Space: O(n), as we are using extra space for the dp arrays. rituraj_jain mukesh07 decode2207 divyeshrabadiya07 2yrj0 lalitgupta5 rohitsingh57 DFS n-ary-tree Dynamic Programming Tree Dynamic Programming DFS Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Floyd Warshall Algorithm | DP-16 Matrix Chain Multiplication | DP-8 Sieve of Eratosthenes Bellman–Ford Algorithm | DP-23 Find if there is a path between two vertices in an undirected graph Tree Traversals (Inorder, Preorder and Postorder) Binary Tree | Set 1 (Introduction) Level Order Binary Tree Traversal AVL Tree | Set 1 (Insertion) Introduction to Data Structures
[ { "code": null, "e": 54, "s": 26, "text": "\n16 Jun, 2022" }, { "code": null, "e": 206, "s": 54, "text": "Given an N-ary tree T of N nodes, the task is to calculate the longest path between any two nodes(also known as the diameter of the tree). Example 1: " }, { "code": null, "e": 219, "s": 206, "text": "Example 2: " }, { "code": null, "e": 299, "s": 221, "text": "Different approaches to solving these problems have already been discussed: " }, { "code": null, "e": 350, "s": 299, "text": "https://www.geeksforgeeks.org/diameter-n-ary-tree/" }, { "code": null, "e": 411, "s": 350, "text": "https://www.geeksforgeeks.org/diameter-n-ary-tree-using-bfs/" }, { "code": null, "e": 516, "s": 411, "text": "In this post, we will be discussing an approach that uses Dynamic Programming on Trees. Prerequisites: " }, { "code": null, "e": 536, "s": 516, "text": "DP on Trees | Set 1" }, { "code": null, "e": 556, "s": 536, "text": "DP on Trees | Set 2" }, { "code": null, "e": 613, "s": 556, "text": "There are two possibilities for the diameter to exist: " }, { "code": null, "e": 894, "s": 613, "text": "Case 1: Suppose the diameter starts from a node and ends at some node in its subtree. Let’s say that there exists a node x such that the longest path starts from node x and goes into its subtree and ends at some node in the subtree itself. Let’s define this path length by dp1[x]." }, { "code": null, "e": 1056, "s": 894, "text": "Case 2: Suppose the diameter or the longest path starts in the subtree of a node x, passes through it, and ends in its subtree. Let’s define this path by dp2[x]." }, { "code": null, "e": 1840, "s": 1056, "text": "If for all nodes x, we take a maximum of dp1[x], and dp2[x], then we will get the diameter of the tree. For the case-1, to find dp1[node], we need to find the maximum of all dp1[x], where x is the children of node. And dp1[node] will be equal to 1 + max(dp1[children1], dp1[children2], ..). For the case-2, to find dp2[node], we need to find the two maximum of all dp1[x], where x is the children of node. And dp2[node] will be equal to 1 + max 2 of(dp1[children1], dp1[children2], ..) + max(dp1[children1], dp1[children2], ..). This will ensure a complete path passing through the current node into its subtree.We can easily run a DFS and find the maximum of both dp1[node] and dp2[node] for every to get the diameter of the tree. Below is the implementation of the above approach: " }, { "code": null, "e": 1844, "s": 1840, "text": "C++" }, { "code": null, "e": 1849, "s": 1844, "text": "Java" }, { "code": null, "e": 1857, "s": 1849, "text": "Python3" }, { "code": null, "e": 1860, "s": 1857, "text": "C#" }, { "code": null, "e": 1871, "s": 1860, "text": "Javascript" }, { "code": "// C++ program to find diameter of a tree// using DFS.#include <bits/stdc++.h>using namespace std; int diameter = -1; // Function to find the diameter of the tree// using Dynamic Programmingint dfs(int node, int parent, int dp1[], int dp2[], list<int>* adj){ // Store the first maximum and secondmax int firstmax = -1; int secondmax = -1; // Traverse for all children of node for (auto i = adj[node].begin(); i != adj[node].end(); ++i) { if (*i == parent) continue; // Call DFS function again dfs(*i, node, dp1, dp2, adj); // Find first max if (firstmax == -1) { firstmax = dp1[*i]; } else if (dp1[*i] >= firstmax) // Secondmaximum { secondmax = firstmax; firstmax = dp1[*i]; } else if (dp1[*i] > secondmax) // Find secondmaximum { secondmax = dp1[*i]; } } // Base case for every node dp1[node] = 1; if (firstmax != -1) // Add dp1[node] += firstmax; // Find dp[2] if (secondmax != -1) dp2[node] = 1 + firstmax + secondmax; diameter = max(diameter, max(dp1[node], dp2[node])); // Return maximum of both return max(dp1[node], dp2[node]);} // Driver Codeint main(){ int n = 5; /* Constructed tree is 1 / \\ 2 3 / \\ 4 5 */ list<int>* adj = new list<int>[n + 1]; /*create undirected edges */ adj[1].push_back(2); adj[2].push_back(1); adj[1].push_back(3); adj[3].push_back(1); adj[2].push_back(4); adj[4].push_back(2); adj[2].push_back(5); adj[5].push_back(2); int dp1[n + 1], dp2[n + 1]; memset(dp1, 0, sizeof dp1); memset(dp2, 0, sizeof dp2); // Find diameter by calling function dfs(1, 1, dp1, dp2, adj) cout << \"Diameter of the given tree is \" << diameter << endl; return 0;}", "e": 3751, "s": 1871, "text": null }, { "code": "// Java program to find diameter of a tree using DFS.import java.util.*;public class Main{ // Function to find the diameter of the tree // using Dynamic Programming static int dfs(int node, int parent, int[] dp1, int[] dp2, Vector<Vector<Integer>> adj) { // Store the first maximum and secondmax int firstmax = -1; int secondmax = -1; // Traverse for all children of node for (int i = 0; i < adj.get(node).size(); ++i) { if (adj.get(node).get(i) == parent) continue; // Call DFS function again dfs(adj.get(node).get(i), node, dp1, dp2, adj); // Find first max if (firstmax == -1) { firstmax = dp1[adj.get(node).get(i)]; } // Secondmaximum else if (dp1[adj.get(node).get(i)] >= firstmax) { secondmax = firstmax; firstmax = dp1[adj.get(node).get(i)]; } // Find secondmaximum else if (dp1[adj.get(node).get(i)] > secondmax) { secondmax = dp1[adj.get(node).get(i)]; } } // Base case for every node dp1[node] = 1; if (firstmax != -1) // Add dp1[node] += firstmax; // Find dp[2] if (secondmax != -1) dp2[node] = 1 + firstmax + secondmax; // Return maximum of both return Math.max(dp1[node], dp2[node]); } public static void main(String[] args) { int n = 5; /* Constructed tree is 1 / \\ 2 3 / \\ 4 5 */ Vector<Vector<Integer>> adj = new Vector<Vector<Integer>>(); for(int i = 0; i < n + 1; i++) { adj.add(new Vector<Integer>()); } /*create undirected edges */ adj.get(1).add(2); adj.get(2).add(1); adj.get(1).add(3); adj.get(3).add(1); adj.get(2).add(4); adj.get(4).add(2); adj.get(2).add(5); adj.get(5).add(2); int[] dp1 = new int[n + 1]; int[] dp2 = new int[n + 1]; for(int i = 0; i < n + 1; i++) { dp1[i] = 0; dp2[i] = 0; } // Find diameter by calling function System.out.println(\"Diameter of the given tree is \" + dfs(1, 1, dp1, dp2, adj)); }} // This code is contributed by divyeshrabadiya07.", "e": 6228, "s": 3751, "text": null }, { "code": "# Python3 program to find diameter# of a tree using DFS. # Function to find the diameter of the# tree using Dynamic Programmingdef dfs(node, parent, dp1, dp2, adj): # Store the first maximum and secondmax firstmax, secondmax = -1, -1 # Traverse for all children of node for i in adj[node]: if i == parent: continue # Call DFS function again dfs(i, node, dp1, dp2, adj) # Find first max if firstmax == -1: firstmax = dp1[i] elif dp1[i] >= firstmax: # Secondmaximum secondmax = firstmax firstmax = dp1[i] elif dp1[i] > secondmax: # Find secondmaximum secondmax = dp1[i] # Base case for every node dp1[node] = 1 if firstmax != -1: # Add dp1[node] += firstmax # Find dp[2] if secondmax != -1: dp2[node] = 1 + firstmax + secondmax diameter = max(diameter, max(dp1[node], dp2[node])); # Return maximum of both return max(dp1[node], dp2[node]) # Driver Codeif __name__ == \"__main__\": n, diameter = 5, -1 adj = [[] for i in range(n + 1)] # create undirected edges adj[1].append(2) adj[2].append(1) adj[1].append(3) adj[3].append(1) adj[2].append(4) adj[4].append(2) adj[2].append(5) adj[5].append(2) dp1 = [0] * (n + 1) dp2 = [0] * (n + 1) # Find diameter by calling function dfs(1, 1, dp1, dp2, adj) print(\"Diameter of the given tree is\", diameter ) # This code is contributed by Rituraj Jain", "e": 7768, "s": 6228, "text": null }, { "code": "// C# program to find diameter of a tree using DFS.using System;using System.Collections.Generic;class GFG { // Function to find the diameter of the tree // using Dynamic Programming static int dfs(int node, int parent, int[] dp1, int[] dp2, List<List<int>> adj) { // Store the first maximum and secondmax int firstmax = -1; int secondmax = -1; // Traverse for all children of node for (int i = 0; i < adj[node].Count; ++i) { if (adj[node][i] == parent) continue; // Call DFS function again dfs(adj[node][i], node, dp1, dp2, adj); // Find first max if (firstmax == -1) { firstmax = dp1[adj[node][i]]; } // Secondmaximum else if (dp1[adj[node][i]] >= firstmax) { secondmax = firstmax; firstmax = dp1[adj[node][i]]; } // Find secondmaximum else if (dp1[adj[node][i]] > secondmax) { secondmax = dp1[adj[node][i]]; } } // Base case for every node dp1[node] = 1; if (firstmax != -1) // Add dp1[node] += firstmax; // Find dp[2] if (secondmax != -1) dp2[node] = 1 + firstmax + secondmax; // diameter = Math.Max(diameter, Math.Max(dp1[node], dp2[node])); // Return maximum of both return Math.Max(dp1[node], dp2[node]); } static void Main() { int n = 5; /* Constructed tree is 1 / \\ 2 3 / \\ 4 5 */ List<List<int>> adj = new List<List<int>>(); for(int i = 0; i < n + 1; i++) { adj.Add(new List<int>()); } /*create undirected edges */ adj[1].Add(2); adj[2].Add(1); adj[1].Add(3); adj[3].Add(1); adj[2].Add(4); adj[4].Add(2); adj[2].Add(5); adj[5].Add(2); int[] dp1 = new int[n + 1]; int[] dp2 = new int[n + 1]; for(int i = 0; i < n + 1; i++) { dp1[i] = 0; dp2[i] = 0; } // Find diameter by calling function Console.WriteLine(\"Diameter of the given tree is \" + dfs(1, 1, dp1, dp2, adj)); }} // This code is contributed by decode2207.", "e": 10036, "s": 7768, "text": null }, { "code": "<script> // JavaScript program to find diameter of a tree using DFS. let diameter = -1; // Function to find the diameter of the tree // using Dynamic Programming function dfs(node, parent, dp1, dp2, adj) { // Store the first maximum and secondmax let firstmax = -1; let secondmax = -1; // Traverse for all children of node for (let i = 0; i < adj[node].length; ++i) { if (adj[node][i] == parent) continue; // Call DFS function again dfs(adj[node][i], node, dp1, dp2, adj); // Find first max if (firstmax == -1) { firstmax = dp1[adj[node][i]]; } // Secondmaximum else if (dp1[adj[node][i]] >= firstmax) { secondmax = firstmax; firstmax = dp1[adj[node][i]]; } // Find secondmaximum else if (dp1[adj[node][i]] > secondmax) { secondmax = dp1[adj[node][i]]; } } // Base case for every node dp1[node] = 1; if (firstmax != -1) // Add dp1[node] += firstmax; // Find dp[2] if (secondmax != -1) dp2[node] = 1 + firstmax + secondmax; diameter = Math.max(diameter, Math.max(dp1[node], dp2[node])); // Return maximum of both return Math.max(dp1[node], dp2[node]); } let n = 5; /* Constructed tree is 1 / \\ 2 3 / \\ 4 5 */ let adj = new Array(n + 1); for(let i = 0; i < n + 1; i++) { adj[i] = []; } /*create undirected edges */ adj[1].push(2); adj[2].push(1); adj[1].push(3); adj[3].push(1); adj[2].push(4); adj[4].push(2); adj[2].push(5); adj[5].push(2); let dp1 = new Array(n + 1); let dp2 = new Array(n + 1); dp1.fill(0); dp2.fill(0); // Find diameter by calling function dfs(1, 1, dp1, dp2, adj) document.write(\"Diameter of the given tree is \" + diameter); </script>", "e": 12111, "s": 10036, "text": null }, { "code": null, "e": 12143, "s": 12111, "text": "Diameter of the given tree is 4" }, { "code": null, "e": 12265, "s": 12145, "text": "Time Complexity: O(n), as we are using recursion to traverse n times, where n is the total number of nodes in the tree." }, { "code": null, "e": 12335, "s": 12265, "text": "Auxiliary Space: O(n), as we are using extra space for the dp arrays." }, { "code": null, "e": 12348, "s": 12335, "text": "rituraj_jain" }, { "code": null, "e": 12357, "s": 12348, "text": "mukesh07" }, { "code": null, "e": 12368, "s": 12357, "text": "decode2207" }, { "code": null, "e": 12386, "s": 12368, "text": "divyeshrabadiya07" }, { "code": null, "e": 12392, "s": 12386, "text": "2yrj0" }, { "code": null, "e": 12404, "s": 12392, "text": "lalitgupta5" }, { "code": null, "e": 12417, "s": 12404, "text": "rohitsingh57" }, { "code": null, "e": 12421, "s": 12417, "text": "DFS" }, { "code": null, "e": 12432, "s": 12421, "text": "n-ary-tree" }, { "code": null, "e": 12452, "s": 12432, "text": "Dynamic Programming" }, { "code": null, "e": 12457, "s": 12452, "text": "Tree" }, { "code": null, "e": 12477, "s": 12457, "text": "Dynamic Programming" }, { "code": null, "e": 12481, "s": 12477, "text": "DFS" }, { "code": null, "e": 12486, "s": 12481, "text": "Tree" }, { "code": null, "e": 12584, "s": 12486, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 12617, "s": 12584, "text": "Floyd Warshall Algorithm | DP-16" }, { "code": null, "e": 12652, "s": 12617, "text": "Matrix Chain Multiplication | DP-8" }, { "code": null, "e": 12674, "s": 12652, "text": "Sieve of Eratosthenes" }, { "code": null, "e": 12705, "s": 12674, "text": "Bellman–Ford Algorithm | DP-23" }, { "code": null, "e": 12773, "s": 12705, "text": "Find if there is a path between two vertices in an undirected graph" }, { "code": null, "e": 12823, "s": 12773, "text": "Tree Traversals (Inorder, Preorder and Postorder)" }, { "code": null, "e": 12858, "s": 12823, "text": "Binary Tree | Set 1 (Introduction)" }, { "code": null, "e": 12892, "s": 12858, "text": "Level Order Binary Tree Traversal" }, { "code": null, "e": 12921, "s": 12892, "text": "AVL Tree | Set 1 (Insertion)" } ]
How to Design Color Picker using jQuery UI ?
11 Jan, 2022 A ColorPicker is a jQuery UI framework tool or widget which provides a color-palette dropdown box to the user to select the color for some colorful work. It is usually connected to a text-box so that user selection of color from the color palette can be transferred to the textbox. The dropdown box can be HSV (Hue, Saturation, Value) picker or predefined RGB color palette as shown in the image. It is a very useful user interface tool as the user on the other end need not remember or know the difficult color codes. This tool can be understood as an image or text editor. Glimpse of ColorPicker using jQuery UI: If you want to attach the color-palette dropdown box on the website then you need JqueryUI Colorpicker library and include the required JavaScript(jquery.colorpicker.js) and CSS(jquery.colorpicker.css) dependencies in your PHP or HTML codes to display any jQuery UI widget. We have to use the jQuery and jQuery UI libraries and styles. You can change the files to match your style requirements. In this article, we will create the structure of the color picker in an HTML page. In the HTML web page, user input control is provided for user selection. The user input control is attached to the jQuery UI color picker widget by jQuery code. Below is the complete implementation. Creating Structure: In this section, we are creating the basic page structure and also attaching the required link which will be used. Links for the jQuery UI: <script src=”https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.js”></script> <script src=”https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.js”></script> <link href=”http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/themes/ui-lightness/jquery-ui.css” rel=”stylesheet” type=”text/css” /> HTML Code: This example displays a simple color picker popup. As mentioned above, the downloaded dependent files (CSS and JS) for color picker are kept in folder colorpicker-master. Make sure the developer gives the correct path according to his own localhost path in the code. HTML <!DOCTYPE html><html> <head> <title>jQueryUI | Color Picker</title></head> <body> <h1>GeeksforGeeks</h1> <b>jQueryUI | Color Picker </b> <div class="height"></div> <br/> <body> Pick a color : <input type="text" id="my_color_picker"> </body></body> </html> Designing Structure: In the previous section, we have created the basic code of using color picker widget. In this section, we will design the structure and attach the color picker widget to our input control where we are going to set options to override the color picker plugin’s default options. Overriding the default options with your own options settings can be done in the script part of the HTML code. It is designed in a flexible way for users to choose the options needed for their applications. Links to the downloaded file: <script src=”colorpicker-master/jquery.colorpicker.js”></script> <link href=”colorpicker-master/jquery.colorpicker.css” rel=”stylesheet” type=”text/css” /> CSS Code: CSS <style> h1 { color: green; } body { text-align: center; } .height { height: 10px; }</style> JS Code: Javascript <script> $(document).ready(function() { $(function() { $("#my_color_picker").colorpicker(); }); });</script> Program: HTML <!DOCTYPE html><html> <head> <title>jQueryUI | Color Picker</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.js"> </script> <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.js"> </script> <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/themes/ui-lightness/jquery-ui.css" rel="stylesheet" type="text/css" /> <!-- Include Pre-compiled files from link or download the files in your localhost folder --> <script src="colorpicker-master/jquery.colorpicker.js"> </script> <link href="colorpicker-master/jquery.colorpicker.css" rel="stylesheet" type="text/css" /> <style> h1 { color: green; } body { text-align: center; } .height { height: 10px; } </style></head> <body> <h1>GeeksforGeeks</h1> <b>jQueryUI | Color Picker </b> <div class="height"></div> <br/> <body> Pick a color : <input type="text" id="my_color_picker"> <script> $(document).ready(function() { $(function() { $("#my_color_picker").colorpicker(); }); }); </script> </body></body> </html> Output: Managing the initial color and color format: While displaying the colorpicker we can manage the initial color and color format. We can use the following jQuery code in the script section to get the result. Javascript <script> $(function() { $( '#colorpickerId').colorpicker({ color:'#00FF00', colorFormat: ['#HEX'] }); }); </script> Managing the dialog: While displaying the color picker we can manage the dialog to be draggable if the header is visible and the dialog is not inline. We can use the following jQuery code in the script section to get the result. Javascript <script> $(function() { $( '#colorpickerId').colorpicker({ draggable:true, }); }); </script> Managing the modal window: While displaying the color picker we can manage the color picker window as a modal window. We can use the following jQuery code in the script section to get the result. Javascript <script> $(function() { $( '#colorpickerId').colorpicker({ modal: true, }); }); </script> Managing the none, close, and cancel buttons: While displaying the colorpicker we can manage the buttons like none, close, and cancel. We can use the following jQuery code in the script section to get the result. Javascript <script> $(function() { $( '#colorpickerId').colorpicker({ showNoneButton: true, showCloseButton: true, showCancelButton: true, }); }); </script> sumitgumber28 surinderdawra388 CSS-Misc HTML-Misc jQuery-Misc jQuery-UI CSS HTML JQuery Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n11 Jan, 2022" }, { "code": null, "e": 603, "s": 28, "text": "A ColorPicker is a jQuery UI framework tool or widget which provides a color-palette dropdown box to the user to select the color for some colorful work. It is usually connected to a text-box so that user selection of color from the color palette can be transferred to the textbox. The dropdown box can be HSV (Hue, Saturation, Value) picker or predefined RGB color palette as shown in the image. It is a very useful user interface tool as the user on the other end need not remember or know the difficult color codes. This tool can be understood as an image or text editor." }, { "code": null, "e": 645, "s": 603, "text": "Glimpse of ColorPicker using jQuery UI: " }, { "code": null, "e": 1322, "s": 645, "text": "If you want to attach the color-palette dropdown box on the website then you need JqueryUI Colorpicker library and include the required JavaScript(jquery.colorpicker.js) and CSS(jquery.colorpicker.css) dependencies in your PHP or HTML codes to display any jQuery UI widget. We have to use the jQuery and jQuery UI libraries and styles. You can change the files to match your style requirements. In this article, we will create the structure of the color picker in an HTML page. In the HTML web page, user input control is provided for user selection. The user input control is attached to the jQuery UI color picker widget by jQuery code. Below is the complete implementation." }, { "code": null, "e": 1458, "s": 1322, "text": "Creating Structure: In this section, we are creating the basic page structure and also attaching the required link which will be used. " }, { "code": null, "e": 1484, "s": 1458, "text": "Links for the jQuery UI: " }, { "code": null, "e": 1798, "s": 1484, "text": "<script src=”https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.js”></script> <script src=”https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.js”></script> <link href=”http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/themes/ui-lightness/jquery-ui.css” rel=”stylesheet” type=”text/css” /> " }, { "code": null, "e": 2077, "s": 1798, "text": "HTML Code: This example displays a simple color picker popup. As mentioned above, the downloaded dependent files (CSS and JS) for color picker are kept in folder colorpicker-master. Make sure the developer gives the correct path according to his own localhost path in the code. " }, { "code": null, "e": 2082, "s": 2077, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>jQueryUI | Color Picker</title></head> <body> <h1>GeeksforGeeks</h1> <b>jQueryUI | Color Picker </b> <div class=\"height\"></div> <br/> <body> Pick a color : <input type=\"text\" id=\"my_color_picker\"> </body></body> </html>", "e": 2378, "s": 2082, "text": null }, { "code": null, "e": 2884, "s": 2378, "text": "Designing Structure: In the previous section, we have created the basic code of using color picker widget. In this section, we will design the structure and attach the color picker widget to our input control where we are going to set options to override the color picker plugin’s default options. Overriding the default options with your own options settings can be done in the script part of the HTML code. It is designed in a flexible way for users to choose the options needed for their applications. " }, { "code": null, "e": 2914, "s": 2884, "text": "Links to the downloaded file:" }, { "code": null, "e": 3070, "s": 2914, "text": "<script src=”colorpicker-master/jquery.colorpicker.js”></script> <link href=”colorpicker-master/jquery.colorpicker.css” rel=”stylesheet” type=”text/css” />" }, { "code": null, "e": 3080, "s": 3070, "text": "CSS Code:" }, { "code": null, "e": 3084, "s": 3080, "text": "CSS" }, { "code": "<style> h1 { color: green; } body { text-align: center; } .height { height: 10px; }</style>", "e": 3217, "s": 3084, "text": null }, { "code": null, "e": 3226, "s": 3217, "text": "JS Code:" }, { "code": null, "e": 3237, "s": 3226, "text": "Javascript" }, { "code": "<script> $(document).ready(function() { $(function() { $(\"#my_color_picker\").colorpicker(); }); });</script>", "e": 3394, "s": 3237, "text": null }, { "code": null, "e": 3403, "s": 3394, "text": "Program:" }, { "code": null, "e": 3408, "s": 3403, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>jQueryUI | Color Picker</title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.js\"> </script> <script src=\"https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.js\"> </script> <link href=\"http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/themes/ui-lightness/jquery-ui.css\" rel=\"stylesheet\" type=\"text/css\" /> <!-- Include Pre-compiled files from link or download the files in your localhost folder --> <script src=\"colorpicker-master/jquery.colorpicker.js\"> </script> <link href=\"colorpicker-master/jquery.colorpicker.css\" rel=\"stylesheet\" type=\"text/css\" /> <style> h1 { color: green; } body { text-align: center; } .height { height: 10px; } </style></head> <body> <h1>GeeksforGeeks</h1> <b>jQueryUI | Color Picker </b> <div class=\"height\"></div> <br/> <body> Pick a color : <input type=\"text\" id=\"my_color_picker\"> <script> $(document).ready(function() { $(function() { $(\"#my_color_picker\").colorpicker(); }); }); </script> </body></body> </html>", "e": 4699, "s": 3408, "text": null }, { "code": null, "e": 4707, "s": 4699, "text": "Output:" }, { "code": null, "e": 4913, "s": 4707, "text": "Managing the initial color and color format: While displaying the colorpicker we can manage the initial color and color format. We can use the following jQuery code in the script section to get the result." }, { "code": null, "e": 4924, "s": 4913, "text": "Javascript" }, { "code": "<script> $(function() { $( '#colorpickerId').colorpicker({ color:'#00FF00', colorFormat: ['#HEX'] }); }); </script>", "e": 5056, "s": 4924, "text": null }, { "code": null, "e": 5285, "s": 5056, "text": "Managing the dialog: While displaying the color picker we can manage the dialog to be draggable if the header is visible and the dialog is not inline. We can use the following jQuery code in the script section to get the result." }, { "code": null, "e": 5296, "s": 5285, "text": "Javascript" }, { "code": "<script> $(function() { $( '#colorpickerId').colorpicker({ draggable:true, }); }); </script>", "e": 5401, "s": 5296, "text": null }, { "code": null, "e": 5597, "s": 5401, "text": "Managing the modal window: While displaying the color picker we can manage the color picker window as a modal window. We can use the following jQuery code in the script section to get the result." }, { "code": null, "e": 5608, "s": 5597, "text": "Javascript" }, { "code": "<script> $(function() { $( '#colorpickerId').colorpicker({ modal: true, }); }); </script>", "e": 5710, "s": 5608, "text": null }, { "code": null, "e": 5923, "s": 5710, "text": "Managing the none, close, and cancel buttons: While displaying the colorpicker we can manage the buttons like none, close, and cancel. We can use the following jQuery code in the script section to get the result." }, { "code": null, "e": 5934, "s": 5923, "text": "Javascript" }, { "code": "<script> $(function() { $( '#colorpickerId').colorpicker({ showNoneButton: true, showCloseButton: true, showCancelButton: true, }); }); </script>", "e": 6101, "s": 5934, "text": null }, { "code": null, "e": 6115, "s": 6101, "text": "sumitgumber28" }, { "code": null, "e": 6132, "s": 6115, "text": "surinderdawra388" }, { "code": null, "e": 6141, "s": 6132, "text": "CSS-Misc" }, { "code": null, "e": 6151, "s": 6141, "text": "HTML-Misc" }, { "code": null, "e": 6163, "s": 6151, "text": "jQuery-Misc" }, { "code": null, "e": 6173, "s": 6163, "text": "jQuery-UI" }, { "code": null, "e": 6177, "s": 6173, "text": "CSS" }, { "code": null, "e": 6182, "s": 6177, "text": "HTML" }, { "code": null, "e": 6189, "s": 6182, "text": "JQuery" }, { "code": null, "e": 6206, "s": 6189, "text": "Web Technologies" }, { "code": null, "e": 6233, "s": 6206, "text": "Web technologies Questions" }, { "code": null, "e": 6238, "s": 6233, "text": "HTML" } ]
How to Use Bootstrap with React?
19 Oct, 2021 We all know the popularity of React, and how this library has made development tasks easier for frontend developers. React is the most popular front-end library to build the user interface of the application. Industries are slowly reducing the use of jQuery and DOM libraries for building their application. When it comes to building a responsive app, CSS frameworks are useful in the market. If you work as a front-end developer, then Bootstrap, Foundation, and Bulma kind of framework are not new for you. Most industries use the Bootstrap framework. Millions of websites are running on bootstrap. Here in this blog, we are going to discuss how to use React and Bootstrap, how to add bootstrap to React app. How to install the React bootstrap package and how to use it in React application. Let’s start with it... There are mainly three ways to add Bootstrap to the React app. We will discuss them one by one. Using Bootstrap CDN.Import Bootstrap in React as a dependencyInstall React Bootstrap package (such as bootstrap-react or reactstrap). Using Bootstrap CDN. Import Bootstrap in React as a dependency Install React Bootstrap package (such as bootstrap-react or reactstrap). This is one of the easiest ways to use bootstrap in your React app. The best thing about bootstrap CDN is no requirement for installation or downloads. You just need to copy and paste a link in the head section of your app to make it work. Below is the link that you need. <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" crossorigin="anonymous"> In case your application needs JavaScript components along with the bootstrap, then at the bottom of the page place <script> tag, just before the closing </body> tag. <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js" integrity="sha384-cs/chFZiN24E4KMATLdqdvsezGxaGsi4hLGOzlXwp5UZB1LY//20VyM2taTB4QvJ" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js" integrity="sha384-uefMccjFJAIv6A+rW+L4AHf99KvxDjWSu1z9VI8SKNVmz4sk7buKt/6v9KI65qnm" crossorigin="anonymous"></script> These snippets will be added to the public/index.html page. You might have used some module bundler or webpack in your application or you might have heard these names. This one is another option to add bootstrap to your React application. You can run the command given below and install bootstrap as a dependency in your application. npm install bootstrap After installation, add this in the JavaScript file of your app’s entry. Below is the index.js file inside the src folder. import 'bootstrap/dist/css/bootstrap.min.css'; import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; import registerServiceWorker from './registerServiceWorker'; ReactDOM.render(<App />, document.getElementById('root')); registerServiceWorker(); In the above code at the top line, we have imported Bootstrap minified CSS as the first dependency. With this, we can use Bootstrap classes in our React components. You also need to install jQuery and popper.js along with this. Below is the command to install both of them. npm install jquery popper.js Make the changes following below in index.js file to add new dependencies. import 'bootstrap/dist/css/bootstrap.min.css'; import $ from 'jquery'; import Popper from 'popper.js'; import 'bootstrap/dist/js/bootstrap.bundle.min'; import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; import registerServiceWorker from './registerServiceWorker'; ReactDOM.render(<Dropdown />, document.getElementById('root')); registerServiceWorker(); The other method to add bootstrap in your React component is adding a package with the inbuilt bootstrap component. These are designed to work with your React application components. Below is the name of two popular packages. react-bootstrap reactstrap Both are good choices for using Bootstrap with React apps. Use the command given below to create a React app in your machine. create-react-app my-app Now, run the command given below to install dependencies as given below. yarn add axios bootstrap reactstrap Here we have installed Axios as a dependency which is a JavaScript library used to make the HTTP request from node.js or XMLHttpRequests from the browser. Axios allows you to fetch posts from the BaconIpsum JSON API. Now to use this Bootstrap minified CSS file. you need to make some modifications in the src/index.js file to include It will look something as given below... import 'bootstrap/dist/css/bootstrap.min.css'; import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; import registerServiceWorker from './registerServiceWorker'; ReactDOM.render(<App />, document.getElementById('root')); registerServiceWorker(); Now create a folder component in the src directory of your project. Create a new file Header.js, in it and write the code given below. import React from 'react'; import logo from '../logo.svg'; import { Container, Row, Col, Form, Input, Button, Navbar, Nav, NavbarBrand, NavLink, NavItem, UncontrolledDropdown, DropdownToggle, DropdownMenu, DropdownItem } from 'reactstrap'; const AVATAR = 'https://www.gravatar.com/avatar/429e504af19fc3e1cfa5c4326ef3394c?s=240&d=mm&r=pg'; const Header = () => ( <header> <Navbar fixed="top" color="light" light expand="xs" className="border-bottom border-gray bg-white" style={{ height: 80 }}> <Container> <Row noGutters className="position-relative w-100 align-items-center"> <Col className="d-none d-lg-flex justify-content-start"> <Nav className="mrx-auto" navbar> <NavItem className="d-flex align-items-center"> <NavLink className="font-weight-bold" href="/"> <img src={AVATAR} alt="avatar" className="img-fluid rounded-circle" style={{ width: 36 }} /> </NavLink> </NavItem> <NavItem className="d-flex align-items-center"> <NavLink className="font-weight-bold" href="/">Home</NavLink> </NavItem> <NavItem className="d-flex align-items-center"> <NavLink className="font-weight-bold" href="/">Electronics</NavLink> </NavItem> <UncontrolledDropdown className="d-flex align-items-center" nav inNavbar> <DropdownToggle className="font-weight-bold" nav caret>fashion</DropdownToggle> <DropdownMenu right> <DropdownItem className="font-weight-bold text-secondary text-uppercase" header disabled>Learn React</DropdownItem> <DropdownItem divider /> <DropdownItem>Men</DropdownItem> <DropdownItem>Women</DropdownItem> <DropdownItem>Baby and Kids</DropdownItem> </DropdownMenu> </UncontrolledDropdown> </Nav> </Col> <Col className="d-flex justify-content-xs-start justify-content-lg-center"> <NavbarBrand className="d-inline-block p-0" href="/" style={{ width: 80 }}> <img src={logo} alt="logo" className="position-relative img-fluid" /> </NavbarBrand> </Col> <Col className="d-none d-lg-flex justify-content-end"> <Form inline> <Input type="search" className="mr-3" placeholder="Search React Courses" /> <Button type="submit" color="info" outline>Search</Button> </Form> </Col> </Row> </Container> </Navbar> </header> ); export default Header; In the above code, we have included the navigation menu. Now let’s create a file LeftCard.js file in the component directory with the following content: import React, { Fragment } from 'react'; import { Button, UncontrolledAlert, Card, CardImg, CardBody, CardTitle, CardSubtitle, CardText } from 'reactstrap'; const BANNER = 'https://i.imgur.com/CaKdFMq.jpg'; const LeftCard = () => ( <Fragment> <UncontrolledAlert color="danger" className="d-none d-lg-block"> <strong>Account not activated.</strong> </UncontrolledAlert> <Card> <CardImg top width="100%" src={BANNER} alt="banner" /> <CardBody> <CardTitle className="h3 mb-2 pt-2 font-weight-bold text-secondary">Lorem Ipsum</CardTitle> <CardSubtitle className="text-secondary mb-3 font-weight-light text-uppercase" style={{ fontSize: '0.8rem' }}>Lorem Ipsum, Lagos</CardSubtitle> <CardText className="text-secondary mb-4" style={{ fontSize: '0.75rem' }}>Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a gallery of type and scrambled it to make a type specimen book</CardText> <Button color="success" className="font-weight-bold">Lorem Ipsum</Button> </CardBody> </Card> </Fragment> ); export default LeftCard; Now create a file Post.js in the components’ directory and add the snippets given below... import React, { Component, Fragment } from 'react'; import axios from 'axios'; import { Badge } from 'reactstrap'; class Post extends Component { state = { post: null } componentDidMount() { axios.get('https://baconipsum.com/api/?type=meat-and-filler&paras=4&format=text') .then(response => this.setState({ post: response.data })); } render() { return ( <Fragment> { this.state.post && <div className="position-relative"> <span className="d-block pb-2 mb-0 h6 text-uppercase text-info font-weight-bold"> Editor's Pick <Badge pill color="success" className="text-uppercase px-2 py-1 ml-3 mb-1 align-middle" style={{ fontSize: '0.75rem' }}>New</Badge> </span> <span className="d-block pb-4 h2 text-dark border-bottom border-gray">React Tutorial</span> <article className="pt-5 text-secondary text-justify" style={{ fontSize: '0.9rem', whiteSpace: 'pre-line' }}>{this.state.post}</article> </div> } </Fragment> ); } } export default Post; The above snippet renders the posts on the page. In the above code, the state of the post will be initialized to null. When the React page will render and the component mounts, we fetch the four paragraphs from BaconIpsum JSON API using Axios. After that state will be changed for post property. Make the final modification in the src/App.js file that looks like given below... import React, { Fragment } from 'react'; import axios from 'axios'; import { Container, Row, Col } from 'reactstrap'; import Post from './components/Post'; import Header from './components/Header'; import LeftCard from './components/LeftCard'; const App = () => ( <Fragment> <Header /> <main className="my-5 py-5"> <Container className="px-0"> <Row noGutters className="pt-2 pt-md-5 w-100 px-4 px-xl-0 position-relative"> <Col xs={{ order: 2 }} md={{ size: 4, order: 1 }} tag="aside" className="pb-5 mb-5 pb-md-0 mb-md-0 mx-auto mx-md-0"> <SideCard /> </Col> <Col xs={{ order: 1 }} md={{ size: 7, offset: 1 }} tag="section" className="py-5 mb-5 py-md-0 mb-md-0"> <Post /> </Col> </Row> </Container> </main> </Fragment> ); export default App; So we have discussed multiple ways to include bootstrap in React app. We have also discussed using the react-bootstrap library. Alert, badge, navbar, dropdown, button, card, nav, form, etc. are the common components of the bootstrap library in React that you will be using frequently. Other useful components are tables, modals, tooltips, carousel, jumbotron, pagination, tabs, etc. React bootstrap is very useful in giving the layout and designing the user interface of your website. Once you will start using it, you will get to know the uses of its components. varshagumber28 Bootstrap GBlog ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n19 Oct, 2021" }, { "code": null, "e": 360, "s": 52, "text": "We all know the popularity of React, and how this library has made development tasks easier for frontend developers. React is the most popular front-end library to build the user interface of the application. Industries are slowly reducing the use of jQuery and DOM libraries for building their application." }, { "code": null, "e": 652, "s": 360, "text": "When it comes to building a responsive app, CSS frameworks are useful in the market. If you work as a front-end developer, then Bootstrap, Foundation, and Bulma kind of framework are not new for you. Most industries use the Bootstrap framework. Millions of websites are running on bootstrap." }, { "code": null, "e": 868, "s": 652, "text": "Here in this blog, we are going to discuss how to use React and Bootstrap, how to add bootstrap to React app. How to install the React bootstrap package and how to use it in React application. Let’s start with it..." }, { "code": null, "e": 964, "s": 868, "text": "There are mainly three ways to add Bootstrap to the React app. We will discuss them one by one." }, { "code": null, "e": 1098, "s": 964, "text": "Using Bootstrap CDN.Import Bootstrap in React as a dependencyInstall React Bootstrap package (such as bootstrap-react or reactstrap)." }, { "code": null, "e": 1119, "s": 1098, "text": "Using Bootstrap CDN." }, { "code": null, "e": 1161, "s": 1119, "text": "Import Bootstrap in React as a dependency" }, { "code": null, "e": 1234, "s": 1161, "text": "Install React Bootstrap package (such as bootstrap-react or reactstrap)." }, { "code": null, "e": 1507, "s": 1234, "text": "This is one of the easiest ways to use bootstrap in your React app. The best thing about bootstrap CDN is no requirement for installation or downloads. You just need to copy and paste a link in the head section of your app to make it work. Below is the link that you need." }, { "code": null, "e": 1721, "s": 1507, "text": "<link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css\" \nintegrity=\"sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4\" \ncrossorigin=\"anonymous\">" }, { "code": null, "e": 1889, "s": 1721, "text": "In case your application needs JavaScript components along with the bootstrap, then at the bottom of the page place <script> tag, just before the closing </body> tag. " }, { "code": null, "e": 2487, "s": 1889, "text": "<script src=\"https://code.jquery.com/jquery-3.3.1.slim.min.js\" \nintegrity=\"sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo\" \ncrossorigin=\"anonymous\"></script>\n\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js\" \nintegrity=\"sha384-cs/chFZiN24E4KMATLdqdvsezGxaGsi4hLGOzlXwp5UZB1LY//20VyM2taTB4QvJ\" \ncrossorigin=\"anonymous\"></script>\n\n<script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js\" \nintegrity=\"sha384-uefMccjFJAIv6A+rW+L4AHf99KvxDjWSu1z9VI8SKNVmz4sk7buKt/6v9KI65qnm\" \ncrossorigin=\"anonymous\"></script>" }, { "code": null, "e": 2547, "s": 2487, "text": "These snippets will be added to the public/index.html page." }, { "code": null, "e": 2822, "s": 2547, "text": "You might have used some module bundler or webpack in your application or you might have heard these names. This one is another option to add bootstrap to your React application. You can run the command given below and install bootstrap as a dependency in your application. " }, { "code": null, "e": 2844, "s": 2822, "text": "npm install bootstrap" }, { "code": null, "e": 2967, "s": 2844, "text": "After installation, add this in the JavaScript file of your app’s entry. Below is the index.js file inside the src folder." }, { "code": null, "e": 3268, "s": 2967, "text": "import 'bootstrap/dist/css/bootstrap.min.css';\nimport React from 'react';\nimport ReactDOM from 'react-dom';\nimport './index.css';\nimport App from './App';\nimport registerServiceWorker from './registerServiceWorker';\n\nReactDOM.render(<App />, document.getElementById('root'));\nregisterServiceWorker();" }, { "code": null, "e": 3542, "s": 3268, "text": "In the above code at the top line, we have imported Bootstrap minified CSS as the first dependency. With this, we can use Bootstrap classes in our React components. You also need to install jQuery and popper.js along with this. Below is the command to install both of them." }, { "code": null, "e": 3571, "s": 3542, "text": "npm install jquery popper.js" }, { "code": null, "e": 3646, "s": 3571, "text": "Make the changes following below in index.js file to add new dependencies." }, { "code": null, "e": 4057, "s": 3646, "text": "import 'bootstrap/dist/css/bootstrap.min.css';\nimport $ from 'jquery';\nimport Popper from 'popper.js';\nimport 'bootstrap/dist/js/bootstrap.bundle.min';\nimport React from 'react';\nimport ReactDOM from 'react-dom';\nimport './index.css';\nimport App from './App';\nimport registerServiceWorker from './registerServiceWorker';\n\nReactDOM.render(<Dropdown />, document.getElementById('root'));\nregisterServiceWorker();" }, { "code": null, "e": 4285, "s": 4057, "text": "The other method to add bootstrap in your React component is adding a package with the inbuilt bootstrap component. These are designed to work with your React application components. Below is the name of two popular packages. " }, { "code": null, "e": 4301, "s": 4285, "text": "react-bootstrap" }, { "code": null, "e": 4312, "s": 4301, "text": "reactstrap" }, { "code": null, "e": 4372, "s": 4312, "text": "Both are good choices for using Bootstrap with React apps. " }, { "code": null, "e": 4439, "s": 4372, "text": "Use the command given below to create a React app in your machine." }, { "code": null, "e": 4463, "s": 4439, "text": "create-react-app my-app" }, { "code": null, "e": 4536, "s": 4463, "text": "Now, run the command given below to install dependencies as given below." }, { "code": null, "e": 4572, "s": 4536, "text": "yarn add axios bootstrap reactstrap" }, { "code": null, "e": 4790, "s": 4572, "text": "Here we have installed Axios as a dependency which is a JavaScript library used to make the HTTP request from node.js or XMLHttpRequests from the browser. Axios allows you to fetch posts from the BaconIpsum JSON API. " }, { "code": null, "e": 4949, "s": 4790, "text": "Now to use this Bootstrap minified CSS file. you need to make some modifications in the src/index.js file to include It will look something as given below..." }, { "code": null, "e": 5250, "s": 4949, "text": "import 'bootstrap/dist/css/bootstrap.min.css';\nimport React from 'react';\nimport ReactDOM from 'react-dom';\nimport './index.css';\nimport App from './App';\nimport registerServiceWorker from './registerServiceWorker';\n\nReactDOM.render(<App />, document.getElementById('root'));\nregisterServiceWorker();" }, { "code": null, "e": 5385, "s": 5250, "text": "Now create a folder component in the src directory of your project. Create a new file Header.js, in it and write the code given below." }, { "code": null, "e": 8206, "s": 5385, "text": "import React from 'react';\nimport logo from '../logo.svg';\n\nimport {\n Container, Row, Col, Form, Input, Button, Navbar, Nav,\n NavbarBrand, NavLink, NavItem, UncontrolledDropdown,\n DropdownToggle, DropdownMenu, DropdownItem\n} from 'reactstrap';\n\nconst AVATAR = 'https://www.gravatar.com/avatar/429e504af19fc3e1cfa5c4326ef3394c?s=240&d=mm&r=pg';\n\nconst Header = () => (\n <header>\n <Navbar fixed=\"top\" color=\"light\" light expand=\"xs\" className=\"border-bottom border-gray bg-white\" style={{ height: 80 }}>\n \n <Container>\n <Row noGutters className=\"position-relative w-100 align-items-center\">\n \n <Col className=\"d-none d-lg-flex justify-content-start\">\n <Nav className=\"mrx-auto\" navbar>\n \n <NavItem className=\"d-flex align-items-center\">\n <NavLink className=\"font-weight-bold\" href=\"/\">\n <img src={AVATAR} alt=\"avatar\" className=\"img-fluid rounded-circle\" style={{ width: 36 }} />\n </NavLink>\n </NavItem>\n \n <NavItem className=\"d-flex align-items-center\">\n <NavLink className=\"font-weight-bold\" href=\"/\">Home</NavLink>\n </NavItem>\n \n <NavItem className=\"d-flex align-items-center\">\n <NavLink className=\"font-weight-bold\" href=\"/\">Electronics</NavLink>\n </NavItem>\n \n <UncontrolledDropdown className=\"d-flex align-items-center\" nav inNavbar>\n <DropdownToggle className=\"font-weight-bold\" nav caret>fashion</DropdownToggle>\n <DropdownMenu right>\n <DropdownItem className=\"font-weight-bold text-secondary text-uppercase\" header disabled>Learn React</DropdownItem>\n <DropdownItem divider />\n <DropdownItem>Men</DropdownItem>\n <DropdownItem>Women</DropdownItem>\n <DropdownItem>Baby and Kids</DropdownItem>\n </DropdownMenu>\n </UncontrolledDropdown>\n \n </Nav>\n </Col>\n \n <Col className=\"d-flex justify-content-xs-start justify-content-lg-center\">\n <NavbarBrand className=\"d-inline-block p-0\" href=\"/\" style={{ width: 80 }}>\n <img src={logo} alt=\"logo\" className=\"position-relative img-fluid\" />\n </NavbarBrand>\n </Col>\n \n <Col className=\"d-none d-lg-flex justify-content-end\">\n <Form inline>\n <Input type=\"search\" className=\"mr-3\" placeholder=\"Search React Courses\" />\n <Button type=\"submit\" color=\"info\" outline>Search</Button>\n </Form>\n </Col>\n \n </Row>\n </Container>\n \n </Navbar>\n </header>\n);\n\nexport default Header;" }, { "code": null, "e": 8359, "s": 8206, "text": "In the above code, we have included the navigation menu. Now let’s create a file LeftCard.js file in the component directory with the following content:" }, { "code": null, "e": 9524, "s": 8359, "text": "import React, { Fragment } from 'react';\n\nimport {\n Button, UncontrolledAlert, Card, CardImg, CardBody,\n CardTitle, CardSubtitle, CardText\n} from 'reactstrap';\n\nconst BANNER = 'https://i.imgur.com/CaKdFMq.jpg';\n\nconst LeftCard = () => (\n <Fragment>\n \n <UncontrolledAlert color=\"danger\" className=\"d-none d-lg-block\">\n <strong>Account not activated.</strong>\n </UncontrolledAlert>\n \n <Card>\n <CardImg top width=\"100%\" src={BANNER} alt=\"banner\" />\n <CardBody>\n <CardTitle className=\"h3 mb-2 pt-2 font-weight-bold text-secondary\">Lorem Ipsum</CardTitle>\n <CardSubtitle className=\"text-secondary mb-3 font-weight-light text-uppercase\" style={{ fontSize: '0.8rem' }}>Lorem Ipsum, Lagos</CardSubtitle>\n <CardText className=\"text-secondary mb-4\" style={{ fontSize: '0.75rem' }}>Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a gallery of type and scrambled it to make a type specimen book</CardText>\n <Button color=\"success\" className=\"font-weight-bold\">Lorem Ipsum</Button>\n </CardBody>\n </Card>\n \n </Fragment>\n);\n\nexport default LeftCard;" }, { "code": null, "e": 9615, "s": 9524, "text": "Now create a file Post.js in the components’ directory and add the snippets given below..." }, { "code": null, "e": 10725, "s": 9615, "text": "import React, { Component, Fragment } from 'react';\nimport axios from 'axios';\nimport { Badge } from 'reactstrap';\n\nclass Post extends Component {\n\n state = { post: null }\n \n componentDidMount() {\n axios.get('https://baconipsum.com/api/?type=meat-and-filler&paras=4&format=text')\n .then(response => this.setState({ post: response.data }));\n }\n \n render() {\n return (\n <Fragment>\n { this.state.post && <div className=\"position-relative\">\n \n <span className=\"d-block pb-2 mb-0 h6 text-uppercase text-info font-weight-bold\">\n Editor's Pick\n <Badge pill color=\"success\" className=\"text-uppercase px-2 py-1 ml-3 mb-1 align-middle\" style={{ fontSize: '0.75rem' }}>New</Badge>\n </span>\n \n <span className=\"d-block pb-4 h2 text-dark border-bottom border-gray\">React Tutorial</span>\n \n <article className=\"pt-5 text-secondary text-justify\" style={{ fontSize: '0.9rem', whiteSpace: 'pre-line' }}>{this.state.post}</article>\n \n </div> }\n </Fragment>\n );\n }\n \n}\n\nexport default Post;" }, { "code": null, "e": 11021, "s": 10725, "text": "The above snippet renders the posts on the page. In the above code, the state of the post will be initialized to null. When the React page will render and the component mounts, we fetch the four paragraphs from BaconIpsum JSON API using Axios. After that state will be changed for post property." }, { "code": null, "e": 11103, "s": 11021, "text": "Make the final modification in the src/App.js file that looks like given below..." }, { "code": null, "e": 12000, "s": 11103, "text": "import React, { Fragment } from 'react';\nimport axios from 'axios';\nimport { Container, Row, Col } from 'reactstrap';\n\nimport Post from './components/Post';\nimport Header from './components/Header';\nimport LeftCard from './components/LeftCard';\n\nconst App = () => (\n <Fragment>\n \n <Header />\n \n <main className=\"my-5 py-5\">\n <Container className=\"px-0\">\n <Row noGutters className=\"pt-2 pt-md-5 w-100 px-4 px-xl-0 position-relative\">\n \n <Col xs={{ order: 2 }} md={{ size: 4, order: 1 }} tag=\"aside\" className=\"pb-5 mb-5 pb-md-0 mb-md-0 mx-auto mx-md-0\">\n <SideCard />\n </Col>\n \n <Col xs={{ order: 1 }} md={{ size: 7, offset: 1 }} tag=\"section\" className=\"py-5 mb-5 py-md-0 mb-md-0\">\n <Post />\n </Col>\n \n </Row>\n </Container>\n </main>\n \n </Fragment>\n);\n\nexport default App;" }, { "code": null, "e": 12565, "s": 12000, "text": "So we have discussed multiple ways to include bootstrap in React app. We have also discussed using the react-bootstrap library. Alert, badge, navbar, dropdown, button, card, nav, form, etc. are the common components of the bootstrap library in React that you will be using frequently. Other useful components are tables, modals, tooltips, carousel, jumbotron, pagination, tabs, etc. React bootstrap is very useful in giving the layout and designing the user interface of your website. Once you will start using it, you will get to know the uses of its components. " }, { "code": null, "e": 12580, "s": 12565, "text": "varshagumber28" }, { "code": null, "e": 12590, "s": 12580, "text": "Bootstrap" }, { "code": null, "e": 12596, "s": 12590, "text": "GBlog" }, { "code": null, "e": 12604, "s": 12596, "text": "ReactJS" }, { "code": null, "e": 12621, "s": 12604, "text": "Web Technologies" } ]
What are valid identifiers in Java?
A valid identifier in java – Must begin with a letter (A to Z or a to z), currency character ($) or an underscore (_). Can have any combination of characters after the first character. Cannot be a keyword. Following example shows various possible identifiers used to declare a variable in Java. Live Demo public class VariableTest { public static void main(String args[]) { // Declaring a variable named num int num = 1; int _num = 10; int $num = 100; int num123 = 1000; int NUM = 10000; //Printing the value of the variable num System.out.println("value if the variable num: "+num); System.out.println("value if the variable _num: "+_num); System.out.println("value if the variable $num: "+$num); System.out.println("value if the variable num123: "+num123); System.out.println("value if the variable NUM: "+NUM); } } value if the variable num: 1 value if the variable _num: 10 value if the variable $num: 100 value if the variable num123: 1000 value if the variable NUM: 10000
[ { "code": null, "e": 1216, "s": 1187, "text": "A valid identifier in java –" }, { "code": null, "e": 1306, "s": 1216, "text": "Must begin with a letter (A to Z or a to z), currency character ($) or an underscore (_)." }, { "code": null, "e": 1372, "s": 1306, "text": "Can have any combination of characters after the first character." }, { "code": null, "e": 1393, "s": 1372, "text": "Cannot be a keyword." }, { "code": null, "e": 1482, "s": 1393, "text": "Following example shows various possible identifiers used to declare a variable in Java." }, { "code": null, "e": 1493, "s": 1482, "text": " Live Demo" }, { "code": null, "e": 2089, "s": 1493, "text": "public class VariableTest {\n public static void main(String args[]) {\n // Declaring a variable named num\n int num = 1;\n int _num = 10;\n int $num = 100;\n int num123 = 1000;\n int NUM = 10000; \n //Printing the value of the variable num\n System.out.println(\"value if the variable num: \"+num);\n System.out.println(\"value if the variable _num: \"+_num);\n System.out.println(\"value if the variable $num: \"+$num);\n System.out.println(\"value if the variable num123: \"+num123);\n System.out.println(\"value if the variable NUM: \"+NUM);\n }\n}" }, { "code": null, "e": 2250, "s": 2089, "text": "value if the variable num: 1\nvalue if the variable _num: 10\nvalue if the variable $num: 100\nvalue if the variable num123: 1000\nvalue if the variable NUM: 10000\n" } ]
Java Program to Sort the Elements of an Array in Ascending Order
06 Jul, 2022 Problem statement: Sort the given array in ascending order such that elements will be arranged from smallest to largest. Consider an illustration below: Let the original array be as follows: Array generated after sorting the above array is as follows: Elements are sorted in such a way that the smallest element will appear on the extreme left which in this case is -9. The largest element will appear on the extreme right which in this case is 12. Approaches: Using bubble sort(naive)Using sort() method of arrays class(optimal) Using bubble sort(naive) Using sort() method of arrays class(optimal) Approach 1: Using Bubble sort Algorithm: Compare adjacent elements with each other.Use nested for loop to keep track.Swap the elements if the first element is greater than the second element. Compare adjacent elements with each other. Use nested for loop to keep track. Swap the elements if the first element is greater than the second element. Example Java // Java Program to Sort Elements of an Array// in Ascending Order // Main classclass GFG { // Declaration global variable length static int length; // Method 1 // To print the array public static void printArray(int[] array) { // Iterating using for loops for (int i = 0; i < length; i++) { System.out.print(array[i] + " "); } System.out.println(); } // Method 2 // To sort an array public static void sortArray(int[] array) { int temporary = 0; // Sort the array 'arr' elements in ascending order // using nested for loops for (int i = 0; i < length; i++) { for (int j = i + 1; j < length; j++) { if (array[i] > array[j]) { temporary = array[i]; array[i] = array[j]; array[j] = temporary; } } } // Displaying elements of array after sorting System.out.println( "Elements of array sorted in ascending order: "); printArray(array); } // Method 3 // Main driver method public static void main(String[] args) { // Initializing custom array elements // The array contains 6 elements. int[] array = new int[] { -5, -9, 8, 12, 1, 3 }; // Initialize length length = array.length; // Displaying elements of original array System.out.print("Elements of original array: "); // Call printArray method printArray(array); // Call sortArray method sortArray(array); }} Elements of original array: -5 -9 8 12 1 3 Elements of array sorted in ascending order: -9 -5 1 3 8 12 Time Complexity: O(n^2), where n is the length of an array. Approach 2: Using sort() method of Arrays class The sort() method is a java.util.Arrays class method used to sort array elements. It by default sorts of array elements in ascending order. Syntax: Arrays.sort(arrayName); Parameters: Array to be sorted Return Type: NA Example Java // Java Program to sort the elements of an array// in Ascending Order by Inbuilt Methods // Importing Arrays class from java.util packageimport java.util.Arrays; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Initialize array // The array contains 6 elements. int[] array = new int[] { -5, -9, 8, 12, 1, 3 }; // Displaying elements of original array System.out.print("Elements of original array: "); for (int i = 0; i < array.length; i++) { System.out.print(array[i] + " "); } // Using Arrays.sort() method to sort array // elements in ascending order. Arrays.sort(array); System.out.println(); // Displaying elements of array after sorting System.out.println( "Elements of array sorted in ascending order : " + Arrays.toString(array)); }} Elements of original array: -5 -9 8 12 1 3 Elements of array sorted in ascending order : [-9, -5, 1, 3, 8, 12] Time Complexity: O(n log(n)), where n is the size of an array. latifulmousom vinayedula Java-Array-Programs Picked Java Java Programs 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 Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class Factory method design pattern in Java Java Program to Remove Duplicate Elements From the Array
[ { "code": null, "e": 54, "s": 26, "text": "\n06 Jul, 2022" }, { "code": null, "e": 207, "s": 54, "text": "Problem statement: Sort the given array in ascending order such that elements will be arranged from smallest to largest. Consider an illustration below:" }, { "code": null, "e": 246, "s": 207, "text": "Let the original array be as follows: " }, { "code": null, "e": 308, "s": 246, "text": "Array generated after sorting the above array is as follows: " }, { "code": null, "e": 505, "s": 308, "text": "Elements are sorted in such a way that the smallest element will appear on the extreme left which in this case is -9. The largest element will appear on the extreme right which in this case is 12." }, { "code": null, "e": 517, "s": 505, "text": "Approaches:" }, { "code": null, "e": 586, "s": 517, "text": "Using bubble sort(naive)Using sort() method of arrays class(optimal)" }, { "code": null, "e": 611, "s": 586, "text": "Using bubble sort(naive)" }, { "code": null, "e": 656, "s": 611, "text": "Using sort() method of arrays class(optimal)" }, { "code": null, "e": 686, "s": 656, "text": "Approach 1: Using Bubble sort" }, { "code": null, "e": 697, "s": 686, "text": "Algorithm:" }, { "code": null, "e": 848, "s": 697, "text": "Compare adjacent elements with each other.Use nested for loop to keep track.Swap the elements if the first element is greater than the second element." }, { "code": null, "e": 891, "s": 848, "text": "Compare adjacent elements with each other." }, { "code": null, "e": 926, "s": 891, "text": "Use nested for loop to keep track." }, { "code": null, "e": 1001, "s": 926, "text": "Swap the elements if the first element is greater than the second element." }, { "code": null, "e": 1009, "s": 1001, "text": "Example" }, { "code": null, "e": 1014, "s": 1009, "text": "Java" }, { "code": "// Java Program to Sort Elements of an Array// in Ascending Order // Main classclass GFG { // Declaration global variable length static int length; // Method 1 // To print the array public static void printArray(int[] array) { // Iterating using for loops for (int i = 0; i < length; i++) { System.out.print(array[i] + \" \"); } System.out.println(); } // Method 2 // To sort an array public static void sortArray(int[] array) { int temporary = 0; // Sort the array 'arr' elements in ascending order // using nested for loops for (int i = 0; i < length; i++) { for (int j = i + 1; j < length; j++) { if (array[i] > array[j]) { temporary = array[i]; array[i] = array[j]; array[j] = temporary; } } } // Displaying elements of array after sorting System.out.println( \"Elements of array sorted in ascending order: \"); printArray(array); } // Method 3 // Main driver method public static void main(String[] args) { // Initializing custom array elements // The array contains 6 elements. int[] array = new int[] { -5, -9, 8, 12, 1, 3 }; // Initialize length length = array.length; // Displaying elements of original array System.out.print(\"Elements of original array: \"); // Call printArray method printArray(array); // Call sortArray method sortArray(array); }}", "e": 2622, "s": 1014, "text": null }, { "code": null, "e": 2728, "s": 2622, "text": "Elements of original array: -5 -9 8 12 1 3 \nElements of array sorted in ascending order: \n-9 -5 1 3 8 12 " }, { "code": null, "e": 2788, "s": 2728, "text": "Time Complexity: O(n^2), where n is the length of an array." }, { "code": null, "e": 2836, "s": 2788, "text": "Approach 2: Using sort() method of Arrays class" }, { "code": null, "e": 2977, "s": 2836, "text": "The sort() method is a java.util.Arrays class method used to sort array elements. It by default sorts of array elements in ascending order." }, { "code": null, "e": 2985, "s": 2977, "text": "Syntax:" }, { "code": null, "e": 3009, "s": 2985, "text": "Arrays.sort(arrayName);" }, { "code": null, "e": 3042, "s": 3009, "text": "Parameters: Array to be sorted " }, { "code": null, "e": 3058, "s": 3042, "text": "Return Type: NA" }, { "code": null, "e": 3066, "s": 3058, "text": "Example" }, { "code": null, "e": 3071, "s": 3066, "text": "Java" }, { "code": "// Java Program to sort the elements of an array// in Ascending Order by Inbuilt Methods // Importing Arrays class from java.util packageimport java.util.Arrays; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Initialize array // The array contains 6 elements. int[] array = new int[] { -5, -9, 8, 12, 1, 3 }; // Displaying elements of original array System.out.print(\"Elements of original array: \"); for (int i = 0; i < array.length; i++) { System.out.print(array[i] + \" \"); } // Using Arrays.sort() method to sort array // elements in ascending order. Arrays.sort(array); System.out.println(); // Displaying elements of array after sorting System.out.println( \"Elements of array sorted in ascending order : \" + Arrays.toString(array)); }}", "e": 4003, "s": 3071, "text": null }, { "code": null, "e": 4115, "s": 4003, "text": "Elements of original array: -5 -9 8 12 1 3 \nElements of array sorted in ascending order : [-9, -5, 1, 3, 8, 12]" }, { "code": null, "e": 4178, "s": 4115, "text": "Time Complexity: O(n log(n)), where n is the size of an array." }, { "code": null, "e": 4192, "s": 4178, "text": "latifulmousom" }, { "code": null, "e": 4203, "s": 4192, "text": "vinayedula" }, { "code": null, "e": 4223, "s": 4203, "text": "Java-Array-Programs" }, { "code": null, "e": 4230, "s": 4223, "text": "Picked" }, { "code": null, "e": 4235, "s": 4230, "text": "Java" }, { "code": null, "e": 4249, "s": 4235, "text": "Java Programs" }, { "code": null, "e": 4254, "s": 4249, "text": "Java" }, { "code": null, "e": 4352, "s": 4254, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4367, "s": 4352, "text": "Stream In Java" }, { "code": null, "e": 4388, "s": 4367, "text": "Introduction to Java" }, { "code": null, "e": 4409, "s": 4388, "text": "Constructors in Java" }, { "code": null, "e": 4428, "s": 4409, "text": "Exceptions in Java" }, { "code": null, "e": 4445, "s": 4428, "text": "Generics in Java" }, { "code": null, "e": 4471, "s": 4445, "text": "Java Programming Examples" }, { "code": null, "e": 4505, "s": 4471, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 4552, "s": 4505, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 4590, "s": 4552, "text": "Factory method design pattern in Java" } ]
ISRO CS 2018 - GeeksforGeeks
02 Jun, 2021 #include main() { int i, j , x ; scanf("%d", &x); i = 1 ; j = 1; while ( i< 10 ) { j = j * i; i = i + 1; if (i == x) break ; } } Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 29577, "s": 29549, "text": "\n02 Jun, 2021" }, { "code": null, "e": 29764, "s": 29577, "text": "#include \nmain()\n{\n int i, j , x ;\n scanf(\"%d\", &x);\n i = 1 ; j = 1;\n while ( i< 10 ) {\n j = j * i;\n i = i + 1;\n if (i == x) break ;\n }\n }" } ]
Scala - IF ELSE Statements
This chapter takes you through the conditional construction statements in Scala programming. Following is the general form of a typical decision making IF...ELSE structure found in most of the programming languages. The following is a flow chart diagram for conditional statement. ‘if’ statement consists of a Boolean expression followed by one or more statements. The syntax of an ‘if’ statement is as follows. if(Boolean_expression) { // Statements will execute if the Boolean expression is true } If the Boolean expression evaluates to true then the block of code inside the ‘if’ expression will be executed. If not, the first set of code after the end of the ‘if’ expression (after the closing curly brace) will be executed. Try the following example program to understand conditional expressions (if expression) in Scala Programming Language. object Demo { def main(args: Array[String]) { var x = 10; if( x < 20 ){ println("This is if statement"); } } } Save the above program in Demo.scala. The following commands are used to compile and execute this program. \>scalac Demo.scala \>scala Demo This is if statement An ‘if’ statement can be followed by an optional else statement, which executes when the Boolean expression is false. The syntax of a if...else is − if(Boolean_expression){ //Executes when the Boolean expression is true } else{ //Executes when the Boolean expression is false } Try the following example program to understand conditional statements (if- else statement) in Scala Programming Language. object Demo { def main(args: Array[String]) { var x = 30; if( x < 20 ){ println("This is if statement"); } else { println("This is else statement"); } } } Save the above program in Demo.scala. The following commands are used to compile and execute this program. \>scalac Demo.scala \>scala Demo This is else statement An 'if' statement can be followed by an optional 'else if...else' statement, which is very useful to test various conditions using single if...else if statement. When using if , else if , else statements there are few points to keep in mind. An 'if' can have zero or one else's and it must come after any else if's. An 'if' can have zero or one else's and it must come after any else if's. An 'if' can have zero to many else if's and they must come before the else. An 'if' can have zero to many else if's and they must come before the else. Once an else if succeeds, none of he remaining else if's or else's will be tested. Once an else if succeeds, none of he remaining else if's or else's will be tested. The following is the syntax of an ‘if...else if...else’ is as follows − if(Boolean_expression 1){ //Executes when the Boolean expression 1 is true } else if(Boolean_expression 2){ //Executes when the Boolean expression 2 is true } else if(Boolean_expression 3){ //Executes when the Boolean expression 3 is true } else { //Executes when the none of the above condition is true. } Try the following example program to understand conditional statements (if- else- if- else statement) in Scala Programming Language. object Demo { def main(args: Array[String]) { var x = 30; if( x == 10 ){ println("Value of X is 10"); } else if( x == 20 ){ println("Value of X is 20"); } else if( x == 30 ){ println("Value of X is 30"); } else{ println("This is else statement"); } } } Save the above program in Demo.scala. The following commands are used to compile and execute this program. \>scalac Demo.scala \>scala Demo Value of X is 30 It is always legal to nest if-else statements, which means you can use one if or else-if statement inside another if or else-if statement. The syntax for a nested if-else is as follows − if(Boolean_expression 1){ //Executes when the Boolean expression 1 is true if(Boolean_expression 2){ //Executes when the Boolean expression 2 is true } } Try the following example program to understand conditional statements (nested- if statement) in Scala Programming Language. object Demo { def main(args: Array[String]) { var x = 30; var y = 10; if( x == 30 ){ if( y == 10 ){ println("X = 30 and Y = 10"); } } } } Save the above program in Demo.scala. The following commands are used to compile and execute this program. \>scalac Demo.scala \>scala Demo X = 30 and Y = 10
[ { "code": null, "e": 2348, "s": 2132, "text": "This chapter takes you through the conditional construction statements in Scala programming. Following is the general form of a typical decision making IF...ELSE structure found in most of the programming languages." }, { "code": null, "e": 2413, "s": 2348, "text": "The following is a flow chart diagram for conditional statement." }, { "code": null, "e": 2497, "s": 2413, "text": "‘if’ statement consists of a Boolean expression followed by one or more statements." }, { "code": null, "e": 2544, "s": 2497, "text": "The syntax of an ‘if’ statement is as follows." }, { "code": null, "e": 2636, "s": 2544, "text": "if(Boolean_expression) {\n // Statements will execute if the Boolean expression is true\n}\n" }, { "code": null, "e": 2865, "s": 2636, "text": "If the Boolean expression evaluates to true then the block of code inside the ‘if’ expression will be executed. If not, the first set of code after the end of the ‘if’ expression (after the closing curly brace) will be executed." }, { "code": null, "e": 2984, "s": 2865, "text": "Try the following example program to understand conditional expressions (if expression) in Scala Programming Language." }, { "code": null, "e": 3129, "s": 2984, "text": "object Demo {\n def main(args: Array[String]) {\n var x = 10;\n\n if( x < 20 ){\n println(\"This is if statement\");\n }\n }\n}" }, { "code": null, "e": 3236, "s": 3129, "text": "Save the above program in Demo.scala. The following commands are used to compile and execute this program." }, { "code": null, "e": 3270, "s": 3236, "text": "\\>scalac Demo.scala\n\\>scala Demo\n" }, { "code": null, "e": 3292, "s": 3270, "text": "This is if statement\n" }, { "code": null, "e": 3410, "s": 3292, "text": "An ‘if’ statement can be followed by an optional else statement, which executes when the Boolean expression is false." }, { "code": null, "e": 3441, "s": 3410, "text": "The syntax of a if...else is −" }, { "code": null, "e": 3577, "s": 3441, "text": "if(Boolean_expression){\n //Executes when the Boolean expression is true\n} else{\n //Executes when the Boolean expression is false\n}\n" }, { "code": null, "e": 3700, "s": 3577, "text": "Try the following example program to understand conditional statements (if- else statement) in Scala Programming Language." }, { "code": null, "e": 3904, "s": 3700, "text": "object Demo {\n def main(args: Array[String]) {\n var x = 30;\n\n if( x < 20 ){\n println(\"This is if statement\");\n } else {\n println(\"This is else statement\");\n }\n }\n}" }, { "code": null, "e": 4011, "s": 3904, "text": "Save the above program in Demo.scala. The following commands are used to compile and execute this program." }, { "code": null, "e": 4045, "s": 4011, "text": "\\>scalac Demo.scala\n\\>scala Demo\n" }, { "code": null, "e": 4069, "s": 4045, "text": "This is else statement\n" }, { "code": null, "e": 4231, "s": 4069, "text": "An 'if' statement can be followed by an optional 'else if...else' statement, which is very useful to test various conditions using single if...else if statement." }, { "code": null, "e": 4311, "s": 4231, "text": "When using if , else if , else statements there are few points to keep in mind." }, { "code": null, "e": 4385, "s": 4311, "text": "An 'if' can have zero or one else's and it must come after any else if's." }, { "code": null, "e": 4459, "s": 4385, "text": "An 'if' can have zero or one else's and it must come after any else if's." }, { "code": null, "e": 4535, "s": 4459, "text": "An 'if' can have zero to many else if's and they must come before the else." }, { "code": null, "e": 4611, "s": 4535, "text": "An 'if' can have zero to many else if's and they must come before the else." }, { "code": null, "e": 4694, "s": 4611, "text": "Once an else if succeeds, none of he remaining else if's or else's will be tested." }, { "code": null, "e": 4777, "s": 4694, "text": "Once an else if succeeds, none of he remaining else if's or else's will be tested." }, { "code": null, "e": 4849, "s": 4777, "text": "The following is the syntax of an ‘if...else if...else’ is as follows −" }, { "code": null, "e": 5169, "s": 4849, "text": "if(Boolean_expression 1){\n //Executes when the Boolean expression 1 is true\n} else if(Boolean_expression 2){\n //Executes when the Boolean expression 2 is true\n} else if(Boolean_expression 3){\n //Executes when the Boolean expression 3 is true\n} else {\n //Executes when the none of the above condition is true.\n}\n" }, { "code": null, "e": 5302, "s": 5169, "text": "Try the following example program to understand conditional statements (if- else- if- else statement) in Scala Programming Language." }, { "code": null, "e": 5634, "s": 5302, "text": "object Demo {\n def main(args: Array[String]) {\n var x = 30;\n\n if( x == 10 ){\n println(\"Value of X is 10\");\n } else if( x == 20 ){\n println(\"Value of X is 20\");\n } else if( x == 30 ){\n println(\"Value of X is 30\");\n } else{\n println(\"This is else statement\");\n }\n }\n}" }, { "code": null, "e": 5741, "s": 5634, "text": "Save the above program in Demo.scala. The following commands are used to compile and execute this program." }, { "code": null, "e": 5775, "s": 5741, "text": "\\>scalac Demo.scala\n\\>scala Demo\n" }, { "code": null, "e": 5793, "s": 5775, "text": "Value of X is 30\n" }, { "code": null, "e": 5932, "s": 5793, "text": "It is always legal to nest if-else statements, which means you can use one if or else-if statement inside another if or else-if statement." }, { "code": null, "e": 5980, "s": 5932, "text": "The syntax for a nested if-else is as follows −" }, { "code": null, "e": 6154, "s": 5980, "text": "if(Boolean_expression 1){\n //Executes when the Boolean expression 1 is true\n \n if(Boolean_expression 2){\n //Executes when the Boolean expression 2 is true\n }\n}\n" }, { "code": null, "e": 6279, "s": 6154, "text": "Try the following example program to understand conditional statements (nested- if statement) in Scala Programming Language." }, { "code": null, "e": 6484, "s": 6279, "text": "object Demo {\n def main(args: Array[String]) {\n var x = 30;\n var y = 10;\n \n if( x == 30 ){\n if( y == 10 ){\n println(\"X = 30 and Y = 10\");\n }\n }\n }\n}" }, { "code": null, "e": 6591, "s": 6484, "text": "Save the above program in Demo.scala. The following commands are used to compile and execute this program." }, { "code": null, "e": 6625, "s": 6591, "text": "\\>scalac Demo.scala\n\\>scala Demo\n" } ]
Flipping Tiles (memory game) using Python3
13 Sep, 2021 Flipping tiles game can be played to test our memory. In this, we have a certain even number of tiles, in which each number/figure has a pair. The tiles are facing downwards, and we have to flip them to see them. In a turn, one flips 2 tiles, if the tiles match then they are removed. If not then they are flipped and placed back in the position. We keep on doing this until all the tiles have been matched and removed. To simulate this game in Python, we will be using the turtle and random modules. Approach: Import turtle and random module. Python offers the random module that can generate random numbers, and turtle module is being used in making different objects.Set the screen and also choose the background color of your output screen window.Define a function for making a square for the base of your game.Define a function to keep a check of the index number.Define a function to make your game user-friendly i.e user click.Write a function to draw tiles on the square base defined in step 3.Finally use the shuffle() function to shuffle the numbers placed on the square tiles in the square box. Import turtle and random module. Python offers the random module that can generate random numbers, and turtle module is being used in making different objects. Set the screen and also choose the background color of your output screen window. Define a function for making a square for the base of your game. Define a function to keep a check of the index number. Define a function to make your game user-friendly i.e user click. Write a function to draw tiles on the square base defined in step 3. Finally use the shuffle() function to shuffle the numbers placed on the square tiles in the square box. Python3 # import modulesfrom random import *from turtle import * # set the screenscreen = Screen() #choose background colorscreen.bgcolor("yellow") # define the function# for creating a square section# for the gamedef Square(x, y): up() goto(x, y) down() color('white', 'green') begin_fill() for count in range(4): forward(50) left(90) end_fill() # define function to# keep a check of index numberdef Numbering(x, y): return int((x + 200) // 50 + ((y + 200) // 50) * 8) # define functiondef Coordinates(count): return (count % 8) * 50 - 200, (count // 8) * 50 - 200 # define function# to make it interactive# user clickdef click(x, y): spot = Numbering(x, y) mark = state['mark'] if mark is None or mark == spot or tiles[mark] != tiles[spot]: state['mark'] = spot else: hide[spot] = False hide[mark] = False state['mark'] = None def draw(): clear() goto(0, 0) stamp() for count in range(64): if hide[count]: x, y = Coordinates(count) Square(x, y) mark = state['mark'] if mark is not None and hide[mark]: x, y = Coordinates(mark) up() goto(x + 2, y) color('black') write(tiles[mark], font=('Arial', 30, 'normal')) update() ontimer(draw, 10) tiles = list(range(32)) * 2state = {'mark': None}hide = [True] * 64 # for shuffling the# numbers placed inside# the square tilesshuffle(tiles)tracer(False)onscreenclick(click)draw()done() Output: surindertarika1234 Python-projects Python-turtle Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n13 Sep, 2021" }, { "code": null, "e": 474, "s": 54, "text": "Flipping tiles game can be played to test our memory. In this, we have a certain even number of tiles, in which each number/figure has a pair. The tiles are facing downwards, and we have to flip them to see them. In a turn, one flips 2 tiles, if the tiles match then they are removed. If not then they are flipped and placed back in the position. We keep on doing this until all the tiles have been matched and removed." }, { "code": null, "e": 555, "s": 474, "text": "To simulate this game in Python, we will be using the turtle and random modules." }, { "code": null, "e": 565, "s": 555, "text": "Approach:" }, { "code": null, "e": 1160, "s": 565, "text": "Import turtle and random module. Python offers the random module that can generate random numbers, and turtle module is being used in making different objects.Set the screen and also choose the background color of your output screen window.Define a function for making a square for the base of your game.Define a function to keep a check of the index number.Define a function to make your game user-friendly i.e user click.Write a function to draw tiles on the square base defined in step 3.Finally use the shuffle() function to shuffle the numbers placed on the square tiles in the square box." }, { "code": null, "e": 1320, "s": 1160, "text": "Import turtle and random module. Python offers the random module that can generate random numbers, and turtle module is being used in making different objects." }, { "code": null, "e": 1402, "s": 1320, "text": "Set the screen and also choose the background color of your output screen window." }, { "code": null, "e": 1467, "s": 1402, "text": "Define a function for making a square for the base of your game." }, { "code": null, "e": 1522, "s": 1467, "text": "Define a function to keep a check of the index number." }, { "code": null, "e": 1588, "s": 1522, "text": "Define a function to make your game user-friendly i.e user click." }, { "code": null, "e": 1657, "s": 1588, "text": "Write a function to draw tiles on the square base defined in step 3." }, { "code": null, "e": 1761, "s": 1657, "text": "Finally use the shuffle() function to shuffle the numbers placed on the square tiles in the square box." }, { "code": null, "e": 1769, "s": 1761, "text": "Python3" }, { "code": "# import modulesfrom random import *from turtle import * # set the screenscreen = Screen() #choose background colorscreen.bgcolor(\"yellow\") # define the function# for creating a square section# for the gamedef Square(x, y): up() goto(x, y) down() color('white', 'green') begin_fill() for count in range(4): forward(50) left(90) end_fill() # define function to# keep a check of index numberdef Numbering(x, y): return int((x + 200) // 50 + ((y + 200) // 50) * 8) # define functiondef Coordinates(count): return (count % 8) * 50 - 200, (count // 8) * 50 - 200 # define function# to make it interactive# user clickdef click(x, y): spot = Numbering(x, y) mark = state['mark'] if mark is None or mark == spot or tiles[mark] != tiles[spot]: state['mark'] = spot else: hide[spot] = False hide[mark] = False state['mark'] = None def draw(): clear() goto(0, 0) stamp() for count in range(64): if hide[count]: x, y = Coordinates(count) Square(x, y) mark = state['mark'] if mark is not None and hide[mark]: x, y = Coordinates(mark) up() goto(x + 2, y) color('black') write(tiles[mark], font=('Arial', 30, 'normal')) update() ontimer(draw, 10) tiles = list(range(32)) * 2state = {'mark': None}hide = [True] * 64 # for shuffling the# numbers placed inside# the square tilesshuffle(tiles)tracer(False)onscreenclick(click)draw()done()", "e": 3263, "s": 1769, "text": null }, { "code": null, "e": 3271, "s": 3263, "text": "Output:" }, { "code": null, "e": 3290, "s": 3271, "text": "surindertarika1234" }, { "code": null, "e": 3306, "s": 3290, "text": "Python-projects" }, { "code": null, "e": 3320, "s": 3306, "text": "Python-turtle" }, { "code": null, "e": 3327, "s": 3320, "text": "Python" } ]
Design a Keylogger in Python
28 Jun, 2022 Keystroke logging is the process of recording (logging) the keys pressed on a keyboard (usually when the user is unaware). It is also known as keylogging or keyboard capturing.These programs are used for troubleshooting technical problems with computers and business networks. It can also be used to monitor network usages but more often than not it is used for malicious intents like stealing passwords.This article illustrates designing a keylogger for windows and Linux. Keylogger for Windows Download some python libraries 1) pywin32 2) pyhook‘Following is the code to create a keylogger in python Python3 # Python code for keylogger# to be used in windowsimport win32apiimport win32consoleimport win32guiimport pythoncom, pyHook win = win32console.GetConsoleWindow()win32gui.ShowWindow(win, 0) def OnKeyboardEvent(event): if event.Ascii==5: _exit(1) if event.Ascii !=0 or 8: #open output.txt to read current keystrokes f = open('c:\output.txt', 'r+') buffer = f.read() f.close() # open output.txt to write current + new keystrokes f = open('c:\output.txt', 'w') keylogs = chr(event.Ascii) if event.Ascii == 13: keylogs = '/n' buffer += keylogs f.write(buffer) f.close()# create a hook manager objecthm = pyHook.HookManager()hm.KeyDown = OnKeyboardEvent# set the hookhm.HookKeyboard()# wait foreverpythoncom.PumpMessages() Save the file in C:\ as Keylogger.py and run the python file Output: The keylogger will be started in the background and save all the data on the log file “c:\output.txt”. Keylogger in Linuxpyxhook requires python-Xlib. Install it if you don’t have it already. sudo apt-get install python-xlib Download pyxhook library Python3 # Python code for keylogger# to be used in linuximport osimport pyxhook # This tells the keylogger where the log file will go.# You can set the file path as an environment variable ('pylogger_file'),# or use the default ~/Desktop/file.loglog_file = os.environ.get( 'pylogger_file', os.path.expanduser('~/Desktop/file.log'))# Allow setting the cancel key from environment args, Default: `cancel_key = ord( os.environ.get( 'pylogger_cancel', '`' )[0]) # Allow clearing the log file on start, if pylogger_clean is defined.if os.environ.get('pylogger_clean', None) is not None: try: os.remove(log_file) except EnvironmentError: # File does not exist, or no permissions. pass #creating key pressing event and saving it into log filedef OnKeyPress(event): with open(log_file, 'a') as f: f.write('{}\n'.format(event.Key)) # create a hook manager objectnew_hook = pyxhook.HookManager()new_hook.KeyDown = OnKeyPress# set the hooknew_hook.HookKeyboard()try: new_hook.start() # start the hookexcept KeyboardInterrupt: # User cancelled from command line. passexcept Exception as ex: # Write exceptions to the log file, for analysis later. msg = 'Error while catching events:\n {}'.format(ex) pyxhook.print_err(msg) with open(log_file, 'a') as f: f.write('\n{}'.format(msg)) Output: The keylogger will be started in the background and save all the data on the file.log file “/home/Akash/Desktop”. References https://en.wikipedia.org/wiki/Keystroke_loggingThis article is contributed by Akash Sharan. 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. simranarora5sos ddeevviissaavviittaa Python-projects Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Convert integer to string in Python
[ { "code": null, "e": 54, "s": 26, "text": "\n28 Jun, 2022" }, { "code": null, "e": 529, "s": 54, "text": "Keystroke logging is the process of recording (logging) the keys pressed on a keyboard (usually when the user is unaware). It is also known as keylogging or keyboard capturing.These programs are used for troubleshooting technical problems with computers and business networks. It can also be used to monitor network usages but more often than not it is used for malicious intents like stealing passwords.This article illustrates designing a keylogger for windows and Linux. " }, { "code": null, "e": 551, "s": 529, "text": "Keylogger for Windows" }, { "code": null, "e": 657, "s": 551, "text": "Download some python libraries 1) pywin32 2) pyhook‘Following is the code to create a keylogger in python" }, { "code": null, "e": 665, "s": 657, "text": "Python3" }, { "code": "# Python code for keylogger# to be used in windowsimport win32apiimport win32consoleimport win32guiimport pythoncom, pyHook win = win32console.GetConsoleWindow()win32gui.ShowWindow(win, 0) def OnKeyboardEvent(event): if event.Ascii==5: _exit(1) if event.Ascii !=0 or 8: #open output.txt to read current keystrokes f = open('c:\\output.txt', 'r+') buffer = f.read() f.close() # open output.txt to write current + new keystrokes f = open('c:\\output.txt', 'w') keylogs = chr(event.Ascii) if event.Ascii == 13: keylogs = '/n' buffer += keylogs f.write(buffer) f.close()# create a hook manager objecthm = pyHook.HookManager()hm.KeyDown = OnKeyboardEvent# set the hookhm.HookKeyboard()# wait foreverpythoncom.PumpMessages()", "e": 1473, "s": 665, "text": null }, { "code": null, "e": 1645, "s": 1473, "text": "Save the file in C:\\ as Keylogger.py and run the python file Output: The keylogger will be started in the background and save all the data on the log file “c:\\output.txt”." }, { "code": null, "e": 1735, "s": 1645, "text": "Keylogger in Linuxpyxhook requires python-Xlib. Install it if you don’t have it already. " }, { "code": null, "e": 1768, "s": 1735, "text": "sudo apt-get install python-xlib" }, { "code": null, "e": 1793, "s": 1768, "text": "Download pyxhook library" }, { "code": null, "e": 1801, "s": 1793, "text": "Python3" }, { "code": "# Python code for keylogger# to be used in linuximport osimport pyxhook # This tells the keylogger where the log file will go.# You can set the file path as an environment variable ('pylogger_file'),# or use the default ~/Desktop/file.loglog_file = os.environ.get( 'pylogger_file', os.path.expanduser('~/Desktop/file.log'))# Allow setting the cancel key from environment args, Default: `cancel_key = ord( os.environ.get( 'pylogger_cancel', '`' )[0]) # Allow clearing the log file on start, if pylogger_clean is defined.if os.environ.get('pylogger_clean', None) is not None: try: os.remove(log_file) except EnvironmentError: # File does not exist, or no permissions. pass #creating key pressing event and saving it into log filedef OnKeyPress(event): with open(log_file, 'a') as f: f.write('{}\\n'.format(event.Key)) # create a hook manager objectnew_hook = pyxhook.HookManager()new_hook.KeyDown = OnKeyPress# set the hooknew_hook.HookKeyboard()try: new_hook.start() # start the hookexcept KeyboardInterrupt: # User cancelled from command line. passexcept Exception as ex: # Write exceptions to the log file, for analysis later. msg = 'Error while catching events:\\n {}'.format(ex) pyxhook.print_err(msg) with open(log_file, 'a') as f: f.write('\\n{}'.format(msg))", "e": 3166, "s": 1801, "text": null }, { "code": null, "e": 3290, "s": 3166, "text": "Output: The keylogger will be started in the background and save all the data on the file.log file “/home/Akash/Desktop”. " }, { "code": null, "e": 3769, "s": 3290, "text": "References https://en.wikipedia.org/wiki/Keystroke_loggingThis article is contributed by Akash Sharan. 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": 3785, "s": 3769, "text": "simranarora5sos" }, { "code": null, "e": 3806, "s": 3785, "text": "ddeevviissaavviittaa" }, { "code": null, "e": 3822, "s": 3806, "text": "Python-projects" }, { "code": null, "e": 3829, "s": 3822, "text": "Python" }, { "code": null, "e": 3927, "s": 3829, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3945, "s": 3927, "text": "Python Dictionary" }, { "code": null, "e": 3987, "s": 3945, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 4009, "s": 3987, "text": "Enumerate() in Python" }, { "code": null, "e": 4044, "s": 4009, "text": "Read a file line by line in Python" }, { "code": null, "e": 4070, "s": 4044, "text": "Python String | replace()" }, { "code": null, "e": 4102, "s": 4070, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 4131, "s": 4102, "text": "*args and **kwargs in Python" }, { "code": null, "e": 4158, "s": 4131, "text": "Python Classes and Objects" }, { "code": null, "e": 4188, "s": 4158, "text": "Iterate over a list in Python" } ]
How to Plot Normal Distribution over Histogram in Python? - GeeksforGeeks
21 Apr, 2021 In this article, we will discuss how to Plot Normal Distribution over Histogram using Python. First, we will discuss Histogram and Normal Distribution graphs separately, and then we will merge both graphs together. A histogram is a graphical representation of a set of data points arranged in a user-defined range. Similar to a bar chart, a bar chart compresses a series of data into easy-to-interpret visual objects by grouping multiple data points into logical areas or containers. To draw this we will use: random.normal() method for finding the normal distribution of the data. It has three parameters: loc – (average) where the top of the bell is located.Scale – (standard deviation) how uniform you want the graph to be distributed.size – Shape of the returning Array loc – (average) where the top of the bell is located. Scale – (standard deviation) how uniform you want the graph to be distributed. size – Shape of the returning Array The function hist() in the Pyplot module of the Matplotlib library is used to draw histograms. It has parameters like: data: This parameter is a data sequence.bin: This parameter is optional and contains integers, sequences or strings.Density: This parameter is optional and contains a Boolean value.Alpha: Value is an integer between 0 and 1, which represents the transparency of each histogram. The smaller the value of n, the more transparent the histogram. data: This parameter is a data sequence. bin: This parameter is optional and contains integers, sequences or strings. Density: This parameter is optional and contains a Boolean value. Alpha: Value is an integer between 0 and 1, which represents the transparency of each histogram. The smaller the value of n, the more transparent the histogram. Python3 import numpy as npimport matplotlib.pyplot as plt # Generating some random data# for an exampledata = np.random.normal(170, 10, 250) # Plotting the histogram.plt.hist(data, bins=25, density=True, alpha=0.6, color='b') plt.show() Output: The normal distribution chart is characterized by two parameters: The average value, which represents the maximum value of the chart, and the chart is always symmetrical. And the standard deviation, which determines the amount of change beyond the mean. Smaller standard deviations (compared to the mean) appear steeper, while larger standard deviations (compared to the mean) appear flat. Plotting the Normal Distribution NumPy arange() is used to create and return a reference to a uniformly distributed ndarray instance. With the help of mean() and stdev() method, we calculated the mean and standard deviation and initialized to mean and sd variable. Inside the plot() method, we used one method pdf() for displaying the probability density function. This pdf() method present inside the scipy.stats.norm. Example: Python3 import numpy as npimport matplotlib.pyplot as pltfrom scipy.stats import normimport statistics # Plot between -30 and 30 with# 0.1 steps.x_axis = np.arange(-30, 30, 0.1) # Calculating mean and standard # deviationmean = statistics.mean(x_axis)sd = statistics.stdev(x_axis) plt.plot(x_axis, norm.pdf(x_axis, mean, sd))plt.show() Output: Now, we are done separated the histogram and the normal distribution plot discussion, but it would be great if we can visualize them in a graph with the same scale. This can be easily achieved by accessing two charts in the same cell and then using plt.show(). Now, Let’s discuss about Plotting Normal Distribution over Histogram using Python. We believe that the histogram of some data follows a normal distribution. SciPy has a variety of methods that can be used to estimate the best distribution of random variables, as well as parameters that can best simulate this adaptability. For example, for the data in this problem, the mean and standard deviation of the best-fitting normal distribution can be found as follows: # Make the normal distribution fit the data: mu, std = norm.fit (data) # mean and standard deviation The function xlim() within the Pyplot module of the Matplotlib library is used to obtain or set the x limit of this axis. Syntax: matplotlib.pyplot.xlim (*args, **kwargs) Parameters: This method uses the following parameters, as described below: left: Use this parameter to set xlim to the left. Right: Use this parameter to set xlim on the right. ** kwargs: This parameter is a text attribute that controls the appearance of the label. Return value: left, right: return a tuple of the new limit value of the x-axis. Python3 import numpy as npfrom scipy.stats import normimport matplotlib.pyplot as plt # Generate some data for this # demonstration.data = np.random.normal(170, 10, 250) # Fit a normal distribution to# the data:# mean and standard deviationmu, std = norm.fit(data) # Plot the histogram.plt.hist(data, bins=25, density=True, alpha=0.6, color='b') # Plot the PDF.xmin, xmax = plt.xlim()x = np.linspace(xmin, xmax, 100)p = norm.pdf(x, mu, std) plt.plot(x, p, 'k', linewidth=2)title = "Fit Values: {:.2f} and {:.2f}".format(mu, std)plt.title(title) plt.show() Output: Picked Python-matplotlib Python-numpy Python-scipy 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": "\n21 Apr, 2021" }, { "code": null, "e": 25753, "s": 25537, "text": "In this article, we will discuss how to Plot Normal Distribution over Histogram using Python. First, we will discuss Histogram and Normal Distribution graphs separately, and then we will merge both graphs together. " }, { "code": null, "e": 26022, "s": 25753, "text": "A histogram is a graphical representation of a set of data points arranged in a user-defined range. Similar to a bar chart, a bar chart compresses a series of data into easy-to-interpret visual objects by grouping multiple data points into logical areas or containers." }, { "code": null, "e": 26048, "s": 26022, "text": "To draw this we will use:" }, { "code": null, "e": 26313, "s": 26048, "text": "random.normal() method for finding the normal distribution of the data. It has three parameters: loc – (average) where the top of the bell is located.Scale – (standard deviation) how uniform you want the graph to be distributed.size – Shape of the returning Array" }, { "code": null, "e": 26367, "s": 26313, "text": "loc – (average) where the top of the bell is located." }, { "code": null, "e": 26446, "s": 26367, "text": "Scale – (standard deviation) how uniform you want the graph to be distributed." }, { "code": null, "e": 26482, "s": 26446, "text": "size – Shape of the returning Array" }, { "code": null, "e": 26944, "s": 26482, "text": "The function hist() in the Pyplot module of the Matplotlib library is used to draw histograms. It has parameters like: data: This parameter is a data sequence.bin: This parameter is optional and contains integers, sequences or strings.Density: This parameter is optional and contains a Boolean value.Alpha: Value is an integer between 0 and 1, which represents the transparency of each histogram. The smaller the value of n, the more transparent the histogram." }, { "code": null, "e": 26985, "s": 26944, "text": "data: This parameter is a data sequence." }, { "code": null, "e": 27062, "s": 26985, "text": "bin: This parameter is optional and contains integers, sequences or strings." }, { "code": null, "e": 27128, "s": 27062, "text": "Density: This parameter is optional and contains a Boolean value." }, { "code": null, "e": 27289, "s": 27128, "text": "Alpha: Value is an integer between 0 and 1, which represents the transparency of each histogram. The smaller the value of n, the more transparent the histogram." }, { "code": null, "e": 27297, "s": 27289, "text": "Python3" }, { "code": "import numpy as npimport matplotlib.pyplot as plt # Generating some random data# for an exampledata = np.random.normal(170, 10, 250) # Plotting the histogram.plt.hist(data, bins=25, density=True, alpha=0.6, color='b') plt.show()", "e": 27529, "s": 27297, "text": null }, { "code": null, "e": 27537, "s": 27529, "text": "Output:" }, { "code": null, "e": 27604, "s": 27537, "text": "The normal distribution chart is characterized by two parameters: " }, { "code": null, "e": 27710, "s": 27604, "text": "The average value, which represents the maximum value of the chart, and the chart is always symmetrical. " }, { "code": null, "e": 27929, "s": 27710, "text": "And the standard deviation, which determines the amount of change beyond the mean. Smaller standard deviations (compared to the mean) appear steeper, while larger standard deviations (compared to the mean) appear flat." }, { "code": null, "e": 27962, "s": 27929, "text": "Plotting the Normal Distribution" }, { "code": null, "e": 28064, "s": 27962, "text": "NumPy arange() is used to create and return a reference to a uniformly distributed ndarray instance. " }, { "code": null, "e": 28196, "s": 28064, "text": "With the help of mean() and stdev() method, we calculated the mean and standard deviation and initialized to mean and sd variable. " }, { "code": null, "e": 28352, "s": 28196, "text": "Inside the plot() method, we used one method pdf() for displaying the probability density function. This pdf() method present inside the scipy.stats.norm. " }, { "code": null, "e": 28361, "s": 28352, "text": "Example:" }, { "code": null, "e": 28369, "s": 28361, "text": "Python3" }, { "code": "import numpy as npimport matplotlib.pyplot as pltfrom scipy.stats import normimport statistics # Plot between -30 and 30 with# 0.1 steps.x_axis = np.arange(-30, 30, 0.1) # Calculating mean and standard # deviationmean = statistics.mean(x_axis)sd = statistics.stdev(x_axis) plt.plot(x_axis, norm.pdf(x_axis, mean, sd))plt.show()", "e": 28706, "s": 28369, "text": null }, { "code": null, "e": 28714, "s": 28706, "text": "Output:" }, { "code": null, "e": 29059, "s": 28714, "text": "Now, we are done separated the histogram and the normal distribution plot discussion, but it would be great if we can visualize them in a graph with the same scale. This can be easily achieved by accessing two charts in the same cell and then using plt.show(). Now, Let’s discuss about Plotting Normal Distribution over Histogram using Python. " }, { "code": null, "e": 29440, "s": 29059, "text": "We believe that the histogram of some data follows a normal distribution. SciPy has a variety of methods that can be used to estimate the best distribution of random variables, as well as parameters that can best simulate this adaptability. For example, for the data in this problem, the mean and standard deviation of the best-fitting normal distribution can be found as follows:" }, { "code": null, "e": 29542, "s": 29440, "text": "# Make the normal distribution fit the data: \nmu, std = norm.fit (data) # mean and standard deviation" }, { "code": null, "e": 29664, "s": 29542, "text": "The function xlim() within the Pyplot module of the Matplotlib library is used to obtain or set the x limit of this axis." }, { "code": null, "e": 29715, "s": 29664, "text": "Syntax: matplotlib.pyplot.xlim (*args, **kwargs) " }, { "code": null, "e": 29793, "s": 29715, "text": "Parameters: This method uses the following parameters, as described below: " }, { "code": null, "e": 29843, "s": 29793, "text": "left: Use this parameter to set xlim to the left." }, { "code": null, "e": 29895, "s": 29843, "text": "Right: Use this parameter to set xlim on the right." }, { "code": null, "e": 29984, "s": 29895, "text": "** kwargs: This parameter is a text attribute that controls the appearance of the label." }, { "code": null, "e": 30000, "s": 29984, "text": "Return value: " }, { "code": null, "e": 30066, "s": 30000, "text": "left, right: return a tuple of the new limit value of the x-axis." }, { "code": null, "e": 30074, "s": 30066, "text": "Python3" }, { "code": "import numpy as npfrom scipy.stats import normimport matplotlib.pyplot as plt # Generate some data for this # demonstration.data = np.random.normal(170, 10, 250) # Fit a normal distribution to# the data:# mean and standard deviationmu, std = norm.fit(data) # Plot the histogram.plt.hist(data, bins=25, density=True, alpha=0.6, color='b') # Plot the PDF.xmin, xmax = plt.xlim()x = np.linspace(xmin, xmax, 100)p = norm.pdf(x, mu, std) plt.plot(x, p, 'k', linewidth=2)title = \"Fit Values: {:.2f} and {:.2f}\".format(mu, std)plt.title(title) plt.show()", "e": 30629, "s": 30074, "text": null }, { "code": null, "e": 30637, "s": 30629, "text": "Output:" }, { "code": null, "e": 30644, "s": 30637, "text": "Picked" }, { "code": null, "e": 30662, "s": 30644, "text": "Python-matplotlib" }, { "code": null, "e": 30675, "s": 30662, "text": "Python-numpy" }, { "code": null, "e": 30688, "s": 30675, "text": "Python-scipy" }, { "code": null, "e": 30695, "s": 30688, "text": "Python" }, { "code": null, "e": 30793, "s": 30695, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30825, "s": 30793, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 30867, "s": 30825, "text": "Check if element exists in list in Python" }, { "code": null, "e": 30909, "s": 30867, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 30965, "s": 30909, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 30992, "s": 30965, "text": "Python Classes and Objects" }, { "code": null, "e": 31031, "s": 30992, "text": "Python | Get unique values from a list" }, { "code": null, "e": 31062, "s": 31031, "text": "Python | os.path.join() method" }, { "code": null, "e": 31091, "s": 31062, "text": "Create a directory in Python" }, { "code": null, "e": 31113, "s": 31091, "text": "Defaultdict in Python" } ]
Matplotlib.pyplot.rc_context() in Python - GeeksforGeeks
19 Apr, 2020 Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface. There are various plots which can be used in Pyplot are Line Plot, Contour, Histogram, Scatter, 3D Plot, etc. The rc_context() function in pyplot module of matplotlib library is used to return a context manager for managing rc settings. Syntax: matplotlib.pyplot.rc_context(rc=None, fname=None) Parameters: rc: This parameter is a dictionary can also be passed to the context manager. fname: This parameter contains the name of file which is to be called. Returns: This method return a context manager for managing rc settings. Below examples illustrate the matplotlib.pyplot.rcdefaults() function in matplotlib.pyplot: Example 1: # implementation of the matplotlib functionimport matplotlib.pyplot as pltimport numpy as np np.random.seed(19680801) dots = np.arange(20)x, y = np.meshgrid(dots, dots)data = [x.ravel(), y.ravel()] with plt.rc_context({'axes.xmargin': .2, 'axes.ymargin': .4}): plt.scatter(*data, c = data[1]) plt.grid(True) plt.title('matplotlib.pyplot.rc_context()\Example')plt.show() Output: Example 2: # implementation of the matplotlib functionimport matplotlib.pyplot as pltimport numpy as np np.random.seed(19680801) fig, ax = plt.subplots()dots = np.arange(100)x, y = np.meshgrid(dots, dots) data = [x.ravel(), y.ravel()]ax.scatter(*data, c = data[1]) with plt.rc_context({'axes.autolimit_mode': 'round_numbers', 'axes.xmargin': .8, 'axes.ymargin': .8}): fig, ax = plt.subplots() ax.scatter(*data, c = data[1]) plt.grid(True) plt.title('matplotlib.pyplot.rc_context() Example')plt.show() Output: Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python | Get unique values from a list Python | os.path.join() method Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n19 Apr, 2020" }, { "code": null, "e": 25842, "s": 25537, "text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface. There are various plots which can be used in Pyplot are Line Plot, Contour, Histogram, Scatter, 3D Plot, etc." }, { "code": null, "e": 25969, "s": 25842, "text": "The rc_context() function in pyplot module of matplotlib library is used to return a context manager for managing rc settings." }, { "code": null, "e": 26027, "s": 25969, "text": "Syntax: matplotlib.pyplot.rc_context(rc=None, fname=None)" }, { "code": null, "e": 26039, "s": 26027, "text": "Parameters:" }, { "code": null, "e": 26117, "s": 26039, "text": "rc: This parameter is a dictionary can also be passed to the context manager." }, { "code": null, "e": 26188, "s": 26117, "text": "fname: This parameter contains the name of file which is to be called." }, { "code": null, "e": 26260, "s": 26188, "text": "Returns: This method return a context manager for managing rc settings." }, { "code": null, "e": 26352, "s": 26260, "text": "Below examples illustrate the matplotlib.pyplot.rcdefaults() function in matplotlib.pyplot:" }, { "code": null, "e": 26363, "s": 26352, "text": "Example 1:" }, { "code": "# implementation of the matplotlib functionimport matplotlib.pyplot as pltimport numpy as np np.random.seed(19680801) dots = np.arange(20)x, y = np.meshgrid(dots, dots)data = [x.ravel(), y.ravel()] with plt.rc_context({'axes.xmargin': .2, 'axes.ymargin': .4}): plt.scatter(*data, c = data[1]) plt.grid(True) plt.title('matplotlib.pyplot.rc_context()\\Example')plt.show()", "e": 26768, "s": 26363, "text": null }, { "code": null, "e": 26776, "s": 26768, "text": "Output:" }, { "code": null, "e": 26787, "s": 26776, "text": "Example 2:" }, { "code": "# implementation of the matplotlib functionimport matplotlib.pyplot as pltimport numpy as np np.random.seed(19680801) fig, ax = plt.subplots()dots = np.arange(100)x, y = np.meshgrid(dots, dots) data = [x.ravel(), y.ravel()]ax.scatter(*data, c = data[1]) with plt.rc_context({'axes.autolimit_mode': 'round_numbers', 'axes.xmargin': .8, 'axes.ymargin': .8}): fig, ax = plt.subplots() ax.scatter(*data, c = data[1]) plt.grid(True) plt.title('matplotlib.pyplot.rc_context() Example')plt.show()", "e": 27341, "s": 26787, "text": null }, { "code": null, "e": 27349, "s": 27341, "text": "Output:" }, { "code": null, "e": 27367, "s": 27349, "text": "Python-matplotlib" }, { "code": null, "e": 27374, "s": 27367, "text": "Python" }, { "code": null, "e": 27472, "s": 27374, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27504, "s": 27472, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27546, "s": 27504, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27588, "s": 27546, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27615, "s": 27588, "text": "Python Classes and Objects" }, { "code": null, "e": 27671, "s": 27615, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27693, "s": 27671, "text": "Defaultdict in Python" }, { "code": null, "e": 27732, "s": 27693, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27763, "s": 27732, "text": "Python | os.path.join() method" }, { "code": null, "e": 27792, "s": 27763, "text": "Create a directory in Python" } ]
Lodash _.unset() Method - GeeksforGeeks
09 Sep, 2020 The Lodash _.unset() method is used to remove the property at the path of the object. If the property is removed then it returns True value otherwise, it returns False. Syntax: _.unset(object, path) Parameters: This method accepts two parameters as mentioned above and described below: object: This parameter holds the object to modify. path: This parameter holds the path of the property to unset. It can be an array or string. Return Value: This method returns true if the property is deleted, else false. Example 1: Javascript // Requiring the lodash library const _ = require("lodash"); // The source object var obj = { 'cpp': [{ 'java': { 'python': 3 } }] }; // Use of _.unset() methodconsole.log(_.unset(obj, 'cpp[0].java.python')); // Object is modifiedconsole.log(obj); Output: true { cpp: [ { java: {} } ] } Example 2: Javascript // Requiring the lodash library const _ = require("lodash"); // The source object var obj = { 'cpp': [{ 'java': { 'python': 3 } }] }; // Use of _.unset() methodconsole.log(_.unset(obj, ['html', 'css', 'javascript'])); // Objectconsole.log(obj); Output: true { cpp: [ { java: [Object] } ] } Note: This will not work in normal JavaScript because it requires the library lodash to be installed and can be installed using npm install lodash.. JavaScript-Lodash JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to append HTML code to a div using JavaScript ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 26079, "s": 26051, "text": "\n09 Sep, 2020" }, { "code": null, "e": 26248, "s": 26079, "text": "The Lodash _.unset() method is used to remove the property at the path of the object. If the property is removed then it returns True value otherwise, it returns False." }, { "code": null, "e": 26256, "s": 26248, "text": "Syntax:" }, { "code": null, "e": 26279, "s": 26256, "text": "_.unset(object, path)\n" }, { "code": null, "e": 26366, "s": 26279, "text": "Parameters: This method accepts two parameters as mentioned above and described below:" }, { "code": null, "e": 26417, "s": 26366, "text": "object: This parameter holds the object to modify." }, { "code": null, "e": 26509, "s": 26417, "text": "path: This parameter holds the path of the property to unset. It can be an array or string." }, { "code": null, "e": 26589, "s": 26509, "text": "Return Value: This method returns true if the property is deleted, else false. " }, { "code": null, "e": 26600, "s": 26589, "text": "Example 1:" }, { "code": null, "e": 26611, "s": 26600, "text": "Javascript" }, { "code": "// Requiring the lodash library const _ = require(\"lodash\"); // The source object var obj = { 'cpp': [{ 'java': { 'python': 3 } }] }; // Use of _.unset() methodconsole.log(_.unset(obj, 'cpp[0].java.python')); // Object is modifiedconsole.log(obj);", "e": 26865, "s": 26611, "text": null }, { "code": null, "e": 26873, "s": 26865, "text": "Output:" }, { "code": null, "e": 26905, "s": 26873, "text": "true\n{ cpp: [ { java: {} } ] }\n" }, { "code": null, "e": 26918, "s": 26905, "text": "Example 2: " }, { "code": null, "e": 26929, "s": 26918, "text": "Javascript" }, { "code": "// Requiring the lodash library const _ = require(\"lodash\"); // The source object var obj = { 'cpp': [{ 'java': { 'python': 3 } }] }; // Use of _.unset() methodconsole.log(_.unset(obj, ['html', 'css', 'javascript'])); // Objectconsole.log(obj);", "e": 27180, "s": 26929, "text": null }, { "code": null, "e": 27188, "s": 27180, "text": "Output:" }, { "code": null, "e": 27226, "s": 27188, "text": "true\n{ cpp: [ { java: [Object] } ] }\n" }, { "code": null, "e": 27375, "s": 27226, "text": "Note: This will not work in normal JavaScript because it requires the library lodash to be installed and can be installed using npm install lodash.." }, { "code": null, "e": 27393, "s": 27375, "text": "JavaScript-Lodash" }, { "code": null, "e": 27404, "s": 27393, "text": "JavaScript" }, { "code": null, "e": 27421, "s": 27404, "text": "Web Technologies" }, { "code": null, "e": 27519, "s": 27421, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27559, "s": 27519, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 27604, "s": 27559, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 27665, "s": 27604, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 27737, "s": 27665, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 27789, "s": 27737, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 27829, "s": 27789, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 27862, "s": 27829, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27907, "s": 27862, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 27950, "s": 27907, "text": "How to fetch data from an API in ReactJS ?" } ]
PostgreSQL - ARRAY_AGG() Function - GeeksforGeeks
01 Jun, 2020 PostgreSQL ARRAY_AGG() function is an aggregate function that accepts a set of values and returns an array where each value in the input set is assigned to an element of the array. Syntax: ARRAY_AGG(expression [ORDER BY [sort_expression {ASC | DESC}], [...]) The ORDER BY clause is an voluntary clause. It specifies the order of rows that are processed in the collection, which establishes the order of the elements in the result array. It is often used with the GROUP BY clause.Now let’s look into some examples.Example 1:We will be using the film, film_actor and actor tables in the dvdrental sample database for demonstration. In this example we will query for the list of film title and a list of actors for each film using the ARRAY_AVG() function as follows: SELECT title, ARRAY_AGG (first_name || ' ' || last_name) actors FROM film INNER JOIN film_actor USING (film_id) INNER JOIN actor USING (actor_id) GROUP BY title ORDER BY title; Output: Example 2:here we will use the ARRAY_AGG() function to return a list of films and a list of actors for each film sorted by the actor’s first name using the commands below: SELECT title, ARRAY_AGG ( first_name || ' ' || last_name ORDER BY first_name ) actors FROM film INNER JOIN film_actor USING (film_id) INNER JOIN actor USING (actor_id) GROUP BY title ORDER BY title; Output: postgreSQL-aggregate-functions PostgreSQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. PostgreSQL - CREATE PROCEDURE PostgreSQL - GROUP BY clause PostgreSQL - DROP INDEX PostgreSQL - REPLACE Function PostgreSQL - Copy Table PostgreSQL - TIME Data Type PostgreSQL - CREATE SCHEMA PostgreSQL - Rename Table PostgreSQL - ROW_NUMBER Function PostgreSQL - SELECT
[ { "code": null, "e": 25241, "s": 25213, "text": "\n01 Jun, 2020" }, { "code": null, "e": 25422, "s": 25241, "text": "PostgreSQL ARRAY_AGG() function is an aggregate function that accepts a set of values and returns an array where each value in the input set is assigned to an element of the array." }, { "code": null, "e": 25500, "s": 25422, "text": "Syntax: ARRAY_AGG(expression [ORDER BY [sort_expression {ASC | DESC}], [...])" }, { "code": null, "e": 26006, "s": 25500, "text": "The ORDER BY clause is an voluntary clause. It specifies the order of rows that are processed in the collection, which establishes the order of the elements in the result array. It is often used with the GROUP BY clause.Now let’s look into some examples.Example 1:We will be using the film, film_actor and actor tables in the dvdrental sample database for demonstration. In this example we will query for the list of film title and a list of actors for each film using the ARRAY_AVG() function as follows:" }, { "code": null, "e": 26203, "s": 26006, "text": "SELECT\n title,\n ARRAY_AGG (first_name || ' ' || last_name) actors\nFROM\n film\nINNER JOIN film_actor USING (film_id)\nINNER JOIN actor USING (actor_id)\nGROUP BY\n title\nORDER BY\n title;" }, { "code": null, "e": 26211, "s": 26203, "text": "Output:" }, { "code": null, "e": 26383, "s": 26211, "text": "Example 2:here we will use the ARRAY_AGG() function to return a list of films and a list of actors for each film sorted by the actor’s first name using the commands below:" }, { "code": null, "e": 26634, "s": 26383, "text": "SELECT\n title,\n ARRAY_AGG (\n first_name || ' ' || last_name\n ORDER BY\n first_name\n ) actors\nFROM\n film\nINNER JOIN film_actor USING (film_id)\nINNER JOIN actor USING (actor_id)\nGROUP BY\n title\nORDER BY\n title;" }, { "code": null, "e": 26642, "s": 26634, "text": "Output:" }, { "code": null, "e": 26673, "s": 26642, "text": "postgreSQL-aggregate-functions" }, { "code": null, "e": 26684, "s": 26673, "text": "PostgreSQL" }, { "code": null, "e": 26782, "s": 26684, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26812, "s": 26782, "text": "PostgreSQL - CREATE PROCEDURE" }, { "code": null, "e": 26841, "s": 26812, "text": "PostgreSQL - GROUP BY clause" }, { "code": null, "e": 26865, "s": 26841, "text": "PostgreSQL - DROP INDEX" }, { "code": null, "e": 26895, "s": 26865, "text": "PostgreSQL - REPLACE Function" }, { "code": null, "e": 26919, "s": 26895, "text": "PostgreSQL - Copy Table" }, { "code": null, "e": 26947, "s": 26919, "text": "PostgreSQL - TIME Data Type" }, { "code": null, "e": 26974, "s": 26947, "text": "PostgreSQL - CREATE SCHEMA" }, { "code": null, "e": 27000, "s": 26974, "text": "PostgreSQL - Rename Table" }, { "code": null, "e": 27033, "s": 27000, "text": "PostgreSQL - ROW_NUMBER Function" } ]
Lodash _.reverse() Function - GeeksforGeeks
29 Jul, 2020 Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, strings, objects, numbers, etc.The _.reverse() is used to reverse the array. This function changes the original array and also returns a new array. Syntax: _.reverse( array ) Parameters: This function accepts single parameter array that holds the array of elements. Return Value: It returns the reversed array. Note: Please install lodash module by using npm install lodash before using the below given code. Example 1: This examples shows that this function effect the original array. javascript // Requiring the lodash libraryconst _ = require("lodash"); // Original arraylet array1 = [1, 2, 3, 4] // Printing original Arrayconsole.log("original Array1: ", array1) // Using _.reverse() methodlet reversedArray = _.reverse(array1); // Printing the reversedArrayconsole.log("reversed Array: ", reversedArray) // Printing original Arrayconsole.log("original Array1: ", array1) Output: Example 2: In this example, we will take an array of objects and reverse them. javascript // Requiring the lodash libraryconst _ = require("lodash"); // Original arraylet array1 = [ { "a": 1 }, { "a": 2, "b": 3 }, { "c": 3 }] // Printing original Arrayconsole.log("original Array1: ", array1) // Using _.reverse() methodlet reversedArray = _.reverse(array1); // Printing the reversedArrayconsole.log("reversed Array: ", reversedArray) // Printing original Arrayconsole.log("original Array1: ", array1) Output: JavaScript-Lodash JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to append HTML code to a div using JavaScript ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 26021, "s": 25993, "text": "\n29 Jul, 2020" }, { "code": null, "e": 26277, "s": 26021, "text": "Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, strings, objects, numbers, etc.The _.reverse() is used to reverse the array. This function changes the original array and also returns a new array." }, { "code": null, "e": 26286, "s": 26277, "text": "Syntax: " }, { "code": null, "e": 26305, "s": 26286, "text": "_.reverse( array )" }, { "code": null, "e": 26396, "s": 26305, "text": "Parameters: This function accepts single parameter array that holds the array of elements." }, { "code": null, "e": 26441, "s": 26396, "text": "Return Value: It returns the reversed array." }, { "code": null, "e": 26539, "s": 26441, "text": "Note: Please install lodash module by using npm install lodash before using the below given code." }, { "code": null, "e": 26616, "s": 26539, "text": "Example 1: This examples shows that this function effect the original array." }, { "code": null, "e": 26627, "s": 26616, "text": "javascript" }, { "code": "// Requiring the lodash libraryconst _ = require(\"lodash\"); // Original arraylet array1 = [1, 2, 3, 4] // Printing original Arrayconsole.log(\"original Array1: \", array1) // Using _.reverse() methodlet reversedArray = _.reverse(array1); // Printing the reversedArrayconsole.log(\"reversed Array: \", reversedArray) // Printing original Arrayconsole.log(\"original Array1: \", array1)", "e": 27011, "s": 26627, "text": null }, { "code": null, "e": 27020, "s": 27011, "text": "Output: " }, { "code": null, "e": 27099, "s": 27020, "text": "Example 2: In this example, we will take an array of objects and reverse them." }, { "code": null, "e": 27110, "s": 27099, "text": "javascript" }, { "code": "// Requiring the lodash libraryconst _ = require(\"lodash\"); // Original arraylet array1 = [ { \"a\": 1 }, { \"a\": 2, \"b\": 3 }, { \"c\": 3 }] // Printing original Arrayconsole.log(\"original Array1: \", array1) // Using _.reverse() methodlet reversedArray = _.reverse(array1); // Printing the reversedArrayconsole.log(\"reversed Array: \", reversedArray) // Printing original Arrayconsole.log(\"original Array1: \", array1)", "e": 27538, "s": 27110, "text": null }, { "code": null, "e": 27547, "s": 27538, "text": "Output: " }, { "code": null, "e": 27565, "s": 27547, "text": "JavaScript-Lodash" }, { "code": null, "e": 27576, "s": 27565, "text": "JavaScript" }, { "code": null, "e": 27593, "s": 27576, "text": "Web Technologies" }, { "code": null, "e": 27691, "s": 27593, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27731, "s": 27691, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 27776, "s": 27731, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 27837, "s": 27776, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 27909, "s": 27837, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 27961, "s": 27909, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 28001, "s": 27961, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28034, "s": 28001, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28079, "s": 28034, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28122, "s": 28079, "text": "How to fetch data from an API in ReactJS ?" } ]
How to Run Javascript from Python ? - GeeksforGeeks
28 Jul, 2021 In this article, we’ll discuss how to run a javascript file with Python. For this, we’ll use the JS2PY(Javascript Runtime in Pure Python) Python module. JS2PY works by translating JavaScript directly into Python. It indicates that you may run JS directly from Python code without installing large external engines like V8. To use the module it first has to be installed into the system, since it is not built-in. Syntax: pip install js2py To use the module it has to be imported. Syntax: import js2py Now to covert javascript to python, the javascript command is stored as a string in some variable. We’ll now use the eval_js() function of the module js2py, and pass the javascript code to it. eval_js() function is defined under the js2py module, which is used to evaluate javascript code, Pass the Javascript code as a parameter in the eval_js module. Syntax: js2py.eval_js(javascript code) Example: Running a simple JS command in Python Python3 import js2py code_2 = "function f(x) {return x+x;}"res_2 = js2py.eval_js(code_2) print(res_2(5)) Output: 10 Now let us look at how a JS file is interpreted in Python. For this first *.js file is translated to *.py file The js2py module provides one way for converting JS code to Python code we must use the translate_file() function for this. After the translation, we will import the Python file and provide something to the function declared within the javascript file. translate_file() function accepts two arguments: a Javascript file and a Python file, finally it converts the Javascript file to a Python file. Syntax: js2py.translate_file(Javascript File, Python File) Example: Running a JS file using Python Javascript File: Javascript function wish(name) { console.log("Hello, "+name+"!")} Python File: Python3 import js2pyfrom temp import * js2py.translate_file("hey.js", "temp.py")temp.wish("GeeksforGeeks") Output: Hello GeeksforGeeks We can also run JS without explicitly translating it. for this *.js is loaded into a variable through run_file() function. run_file(): It is defined under the js2py module, which is used to run the Javascript file. It takes a Javascript file as an argument. Syntax: js2py.run_file(Javascript File) Example: Running JS in Python Python3 import js2py eval_res, tempfile = js2py.run_file("hey.js")tempfile.wish("GeeksforGeeks") Output: Hello GeeksforGeeks python-modules 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 ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python | Get unique values from a list Python | os.path.join() method Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n28 Jul, 2021" }, { "code": null, "e": 25860, "s": 25537, "text": "In this article, we’ll discuss how to run a javascript file with Python. For this, we’ll use the JS2PY(Javascript Runtime in Pure Python) Python module. JS2PY works by translating JavaScript directly into Python. It indicates that you may run JS directly from Python code without installing large external engines like V8." }, { "code": null, "e": 25950, "s": 25860, "text": "To use the module it first has to be installed into the system, since it is not built-in." }, { "code": null, "e": 25958, "s": 25950, "text": "Syntax:" }, { "code": null, "e": 25976, "s": 25958, "text": "pip install js2py" }, { "code": null, "e": 26017, "s": 25976, "text": "To use the module it has to be imported." }, { "code": null, "e": 26025, "s": 26017, "text": "Syntax:" }, { "code": null, "e": 26038, "s": 26025, "text": "import js2py" }, { "code": null, "e": 26231, "s": 26038, "text": "Now to covert javascript to python, the javascript command is stored as a string in some variable. We’ll now use the eval_js() function of the module js2py, and pass the javascript code to it." }, { "code": null, "e": 26391, "s": 26231, "text": "eval_js() function is defined under the js2py module, which is used to evaluate javascript code, Pass the Javascript code as a parameter in the eval_js module." }, { "code": null, "e": 26399, "s": 26391, "text": "Syntax:" }, { "code": null, "e": 26430, "s": 26399, "text": "js2py.eval_js(javascript code)" }, { "code": null, "e": 26478, "s": 26430, "text": "Example: Running a simple JS command in Python " }, { "code": null, "e": 26486, "s": 26478, "text": "Python3" }, { "code": "import js2py code_2 = \"function f(x) {return x+x;}\"res_2 = js2py.eval_js(code_2) print(res_2(5))", "e": 26585, "s": 26486, "text": null }, { "code": null, "e": 26594, "s": 26585, "text": "Output: " }, { "code": null, "e": 26597, "s": 26594, "text": "10" }, { "code": null, "e": 26708, "s": 26597, "text": "Now let us look at how a JS file is interpreted in Python. For this first *.js file is translated to *.py file" }, { "code": null, "e": 26961, "s": 26708, "text": "The js2py module provides one way for converting JS code to Python code we must use the translate_file() function for this. After the translation, we will import the Python file and provide something to the function declared within the javascript file." }, { "code": null, "e": 27105, "s": 26961, "text": "translate_file() function accepts two arguments: a Javascript file and a Python file, finally it converts the Javascript file to a Python file." }, { "code": null, "e": 27113, "s": 27105, "text": "Syntax:" }, { "code": null, "e": 27164, "s": 27113, "text": "js2py.translate_file(Javascript File, Python File)" }, { "code": null, "e": 27205, "s": 27164, "text": "Example: Running a JS file using Python" }, { "code": null, "e": 27222, "s": 27205, "text": "Javascript File:" }, { "code": null, "e": 27233, "s": 27222, "text": "Javascript" }, { "code": "function wish(name) { console.log(\"Hello, \"+name+\"!\")}", "e": 27291, "s": 27233, "text": null }, { "code": null, "e": 27305, "s": 27291, "text": "Python File: " }, { "code": null, "e": 27313, "s": 27305, "text": "Python3" }, { "code": "import js2pyfrom temp import * js2py.translate_file(\"hey.js\", \"temp.py\")temp.wish(\"GeeksforGeeks\")", "e": 27413, "s": 27313, "text": null }, { "code": null, "e": 27422, "s": 27413, "text": "Output: " }, { "code": null, "e": 27442, "s": 27422, "text": "Hello GeeksforGeeks" }, { "code": null, "e": 27565, "s": 27442, "text": "We can also run JS without explicitly translating it. for this *.js is loaded into a variable through run_file() function." }, { "code": null, "e": 27700, "s": 27565, "text": "run_file(): It is defined under the js2py module, which is used to run the Javascript file. It takes a Javascript file as an argument." }, { "code": null, "e": 27709, "s": 27700, "text": "Syntax: " }, { "code": null, "e": 27741, "s": 27709, "text": "js2py.run_file(Javascript File)" }, { "code": null, "e": 27771, "s": 27741, "text": "Example: Running JS in Python" }, { "code": null, "e": 27779, "s": 27771, "text": "Python3" }, { "code": "import js2py eval_res, tempfile = js2py.run_file(\"hey.js\")tempfile.wish(\"GeeksforGeeks\")", "e": 27869, "s": 27779, "text": null }, { "code": null, "e": 27877, "s": 27869, "text": "Output:" }, { "code": null, "e": 27897, "s": 27877, "text": "Hello GeeksforGeeks" }, { "code": null, "e": 27912, "s": 27897, "text": "python-modules" }, { "code": null, "e": 27927, "s": 27912, "text": "python-utility" }, { "code": null, "e": 27934, "s": 27927, "text": "Python" }, { "code": null, "e": 28032, "s": 27934, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28064, "s": 28032, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28106, "s": 28064, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28148, "s": 28106, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28175, "s": 28148, "text": "Python Classes and Objects" }, { "code": null, "e": 28231, "s": 28175, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28253, "s": 28231, "text": "Defaultdict in Python" }, { "code": null, "e": 28292, "s": 28253, "text": "Python | Get unique values from a list" }, { "code": null, "e": 28323, "s": 28292, "text": "Python | os.path.join() method" }, { "code": null, "e": 28352, "s": 28323, "text": "Create a directory in Python" } ]
Java.io.BufferedWriter class methods in Java - GeeksforGeeks
19 Apr, 2022 Bufferreader class writes text to character-output stream, buffering characters.Thus, providing efficient writing of single array, character and strings. A buffer size needs to be specified, if not it takes Default value. An output is immediately set to the underlying character or byte stream by the Writer.Class Declaration public class BufferedWriter extends Writer Constructors BufferedWriter(Writer out): Creates a buffered character-output stream that uses a default-sized output buffer. BufferedWriter(Writer out, int size): Creates a new buffered character-output stream that uses an output buffer of the given size. Methods: write() : java.io.BufferedWriter.write(int arg) writes a single character that is specified by an integer argument. Syntax : public void write(int arg) Parameters : arg : integer that specifies the character to write Return : Doesn't return any value. Implementation : JAVA //Java program illustrating use of write(int arg) method import java.io.*;public class NewClass{ public static void main(String[] args) { //initializing FileWriter FileWriter geek_file; try { geek_file = new FileWriter("ABC.txt"); // Initializing BufferedWriter BufferedWriter geekwrite = new BufferedWriter(geek_file); System.out.println("Buffered Writer start writing :)"); // Use of write() method to write the value in 'ABC' file // Printing E geekwrite.write(69); // Printing 1 geekwrite.write(49); // Closing BufferWriter to end operation geekwrite.close(); System.out.println("Written successfully"); } catch (IOException except) { except.printStackTrace(); } }} Note : In the given output, you can’t see it’s action on file. Run this code on any compiler in your device. It creates a new file ‘ABC’ and write “E 1 ” in it. Output : Buffered Writer start writing :) Written successfully write() : java.io.BufferedWriter.write(String arg, int offset, int length) writes String in the file according to its arguments as mentioned in the Java Code. Syntax : public void write(String arg, int offset, int length) Parameters : arg : String to be written offset : From where to start reading the string length : No. of characters of the string to write Return : Doesn't return any value. Implementation : JAVA //Java program illustrating use of write(String arg, int offset, int length) method import java.io.*;public class NewClass{ public static void main(String[] args) { //Initializing a FileWriter FileWriter geek_file; try { geek_file = new FileWriter("ABC.txt"); // Initializing a BufferedWriter BufferedWriter geekwrite = new BufferedWriter(geek_file); System.out.println("Buffered Writer start writing :)"); String arg = "Hello Geeks"; int offset = 6; geekwrite.write(arg,offset,arg.length()-offset); // Closing Buffer geekwrite.close(); System.out.println("Written successfully"); } catch (IOException except) { except.printStackTrace(); } }} Note : In the given output, you can’t see it’s action on file. Run this code on any compiler in your device. It creates a new file ‘ABC’ and write “Geeks” in it.Here, arg = Hello Geeks offset = 6 length = arg.length So, when we minus offset : 6, it will write 'Geeks' only in the file. Output: Buffered Writer start writing :) Written successfully newLine() : java.io.BufferedWriter.newLine() breaks/separates line. Syntax : public void newLine() Return : Doesn't return any value. Implementation : JAVA //Java program explaining use of newLine() method import java.io.*;public class NewClass{ public static void main(String[] args) { //initializing FileWriter FileWriter geek_file; try { geek_file = new FileWriter("ABC.txt"); // Initializing BufferedWriter BufferedWriter geekwrite = new BufferedWriter(geek_file); System.out.println("Buffered Writer start writing :)"); // Use of write() method to write the value in 'ABC' file // Printing "GEEKS" geekwrite.write("GEEKS"); // For next line geekwrite.newLine(); // Printing "FOR" geekwrite.write("FOR"); // For next line geekwrite.newLine(); // Printing "GEEKS" geekwrite.write("FOR"); // Closing BufferWriter to end operation geekwrite.close(); System.out.println("Written successfully"); } catch (IOException except) { except.printStackTrace(); } }} Note :In the given output, you can’t see it’s action on file. Run this code on any compiler in your device. It creates a new file ‘ABC’ and write write | GEEKS | | FOR | | GEEKS | Here, newLine() method breaks line after GEEKS and FOR is written in next line Output : Buffered Writer start writing :) Written successfully flush() : java.io.BufferedWriter.flush() flushes character from write buffer. Syntax : public void flush() Return : Doesn't return any value. close() : java.io.BufferedWriter.close() flushes character from write buffer and then close it. Syntax : public void close() Return : Doesn't return any value. Implementation of flush(), close() method : JAVA //Java program illustrating use of flush(), close() method import java.io.*; //BufferedWriter, FileWriter, IOExceptionpublic class NewClass{ public static void main(String[] args) { FileWriter geek_file; //initializing FileWriter try { geek_file = new FileWriter("ABC.txt"); // Initializing BufferedWriter BufferedWriter geekwrite = new BufferedWriter(geek_file); System.out.println("Buffered Writer start writing :)"); // Use of write() method to write the value in 'ABC' file geekwrite.write(69); // Printing E geekwrite.newLine(); // For next line geekwrite.write(49); // Printing 1 // flush() method : flushing the stream geekwrite.flush(); // close() method : closing BufferWriter to end operation geekwrite.close(); System.out.println("Written successfully"); } catch (IOException except) { except.printStackTrace(); } }} Note : You can’t see it’s action on file. Run this code on any compiler in your device.It creates a new file ‘ABC’ and write | E | | 1 | in it.Here, flush() method flushes the stream and close() method closes the writer. Output : Buffered Writer start writing :) Written successfully This article is contributed by Mohit Gupta . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. gulshankumarar231 simmytarika5 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 Interfaces in Java Stream 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": 25627, "s": 25599, "text": "\n19 Apr, 2022" }, { "code": null, "e": 25954, "s": 25627, "text": "Bufferreader class writes text to character-output stream, buffering characters.Thus, providing efficient writing of single array, character and strings. A buffer size needs to be specified, if not it takes Default value. An output is immediately set to the underlying character or byte stream by the Writer.Class Declaration " }, { "code": null, "e": 26000, "s": 25954, "text": "public class BufferedWriter\n extends Writer" }, { "code": null, "e": 26014, "s": 26000, "text": "Constructors " }, { "code": null, "e": 26126, "s": 26014, "text": "BufferedWriter(Writer out): Creates a buffered character-output stream that uses a default-sized output buffer." }, { "code": null, "e": 26257, "s": 26126, "text": "BufferedWriter(Writer out, int size): Creates a new buffered character-output stream that uses an output buffer of the given size." }, { "code": null, "e": 26267, "s": 26257, "text": "Methods: " }, { "code": null, "e": 26393, "s": 26267, "text": "write() : java.io.BufferedWriter.write(int arg) writes a single character that is specified by an integer argument. Syntax : " }, { "code": null, "e": 26531, "s": 26393, "text": "public void write(int arg)\nParameters : \narg : integer that specifies the character to write \nReturn :\nDoesn't return any value." }, { "code": null, "e": 26548, "s": 26531, "text": "Implementation :" }, { "code": null, "e": 26553, "s": 26548, "text": "JAVA" }, { "code": "//Java program illustrating use of write(int arg) method import java.io.*;public class NewClass{ public static void main(String[] args) { //initializing FileWriter FileWriter geek_file; try { geek_file = new FileWriter(\"ABC.txt\"); // Initializing BufferedWriter BufferedWriter geekwrite = new BufferedWriter(geek_file); System.out.println(\"Buffered Writer start writing :)\"); // Use of write() method to write the value in 'ABC' file // Printing E geekwrite.write(69); // Printing 1 geekwrite.write(49); // Closing BufferWriter to end operation geekwrite.close(); System.out.println(\"Written successfully\"); } catch (IOException except) { except.printStackTrace(); } }}", "e": 27472, "s": 26553, "text": null }, { "code": null, "e": 27634, "s": 27472, "text": "Note : In the given output, you can’t see it’s action on file. Run this code on any compiler in your device. It creates a new file ‘ABC’ and write “E 1 ” in it. " }, { "code": null, "e": 27698, "s": 27634, "text": "Output : \nBuffered Writer start writing :)\nWritten successfully" }, { "code": null, "e": 27867, "s": 27698, "text": "write() : java.io.BufferedWriter.write(String arg, int offset, int length) writes String in the file according to its arguments as mentioned in the Java Code. Syntax : " }, { "code": null, "e": 28105, "s": 27867, "text": "public void write(String arg, int offset, int length)\nParameters : \narg : String to be written\noffset : From where to start reading the string\nlength : No. of characters of the string to write \nReturn :\nDoesn't return any value." }, { "code": null, "e": 28122, "s": 28105, "text": "Implementation :" }, { "code": null, "e": 28127, "s": 28122, "text": "JAVA" }, { "code": "//Java program illustrating use of write(String arg, int offset, int length) method import java.io.*;public class NewClass{ public static void main(String[] args) { //Initializing a FileWriter FileWriter geek_file; try { geek_file = new FileWriter(\"ABC.txt\"); // Initializing a BufferedWriter BufferedWriter geekwrite = new BufferedWriter(geek_file); System.out.println(\"Buffered Writer start writing :)\"); String arg = \"Hello Geeks\"; int offset = 6; geekwrite.write(arg,offset,arg.length()-offset); // Closing Buffer geekwrite.close(); System.out.println(\"Written successfully\"); } catch (IOException except) { except.printStackTrace(); } }}", "e": 28968, "s": 28127, "text": null }, { "code": null, "e": 29136, "s": 28968, "text": "Note : In the given output, you can’t see it’s action on file. Run this code on any compiler in your device. It creates a new file ‘ABC’ and write “Geeks” in it.Here, " }, { "code": null, "e": 29255, "s": 29136, "text": "arg = Hello Geeks\noffset = 6\nlength = arg.length So, when we minus offset : 6, it will write 'Geeks' only in the file." }, { "code": null, "e": 29264, "s": 29255, "text": "Output: " }, { "code": null, "e": 29369, "s": 29264, "text": "Buffered Writer start writing :)\nWritten successfully " }, { "code": null, "e": 29447, "s": 29369, "text": "newLine() : java.io.BufferedWriter.newLine() breaks/separates line. Syntax : " }, { "code": null, "e": 29511, "s": 29447, "text": "public void newLine() \nReturn :\nDoesn't return any value." }, { "code": null, "e": 29528, "s": 29511, "text": "Implementation :" }, { "code": null, "e": 29533, "s": 29528, "text": "JAVA" }, { "code": "//Java program explaining use of newLine() method import java.io.*;public class NewClass{ public static void main(String[] args) { //initializing FileWriter FileWriter geek_file; try { geek_file = new FileWriter(\"ABC.txt\"); // Initializing BufferedWriter BufferedWriter geekwrite = new BufferedWriter(geek_file); System.out.println(\"Buffered Writer start writing :)\"); // Use of write() method to write the value in 'ABC' file // Printing \"GEEKS\" geekwrite.write(\"GEEKS\"); // For next line geekwrite.newLine(); // Printing \"FOR\" geekwrite.write(\"FOR\"); // For next line geekwrite.newLine(); // Printing \"GEEKS\" geekwrite.write(\"FOR\"); // Closing BufferWriter to end operation geekwrite.close(); System.out.println(\"Written successfully\"); } catch (IOException except) { except.printStackTrace(); } }}", "e": 30689, "s": 29533, "text": null }, { "code": null, "e": 30958, "s": 30689, "text": "Note :In the given output, you can’t see it’s action on file. Run this code on any compiler in your device. It creates a new file ‘ABC’ and write write | GEEKS | | FOR | | GEEKS | Here, newLine() method breaks line after GEEKS and FOR is written in next line Output : " }, { "code": null, "e": 31012, "s": 30958, "text": "Buffered Writer start writing :)\nWritten successfully" }, { "code": null, "e": 31100, "s": 31012, "text": "flush() : java.io.BufferedWriter.flush() flushes character from write buffer. Syntax : " }, { "code": null, "e": 31159, "s": 31100, "text": "public void flush() \nReturn :\nDoesn't return any value." }, { "code": null, "e": 31265, "s": 31159, "text": "close() : java.io.BufferedWriter.close() flushes character from write buffer and then close it. Syntax : " }, { "code": null, "e": 31324, "s": 31265, "text": "public void close() \nReturn :\nDoesn't return any value." }, { "code": null, "e": 31368, "s": 31324, "text": "Implementation of flush(), close() method :" }, { "code": null, "e": 31373, "s": 31368, "text": "JAVA" }, { "code": "//Java program illustrating use of flush(), close() method import java.io.*; //BufferedWriter, FileWriter, IOExceptionpublic class NewClass{ public static void main(String[] args) { FileWriter geek_file; //initializing FileWriter try { geek_file = new FileWriter(\"ABC.txt\"); // Initializing BufferedWriter BufferedWriter geekwrite = new BufferedWriter(geek_file); System.out.println(\"Buffered Writer start writing :)\"); // Use of write() method to write the value in 'ABC' file geekwrite.write(69); // Printing E geekwrite.newLine(); // For next line geekwrite.write(49); // Printing 1 // flush() method : flushing the stream geekwrite.flush(); // close() method : closing BufferWriter to end operation geekwrite.close(); System.out.println(\"Written successfully\"); } catch (IOException except) { except.printStackTrace(); } }}", "e": 32416, "s": 31373, "text": null }, { "code": null, "e": 32638, "s": 32416, "text": "Note : You can’t see it’s action on file. Run this code on any compiler in your device.It creates a new file ‘ABC’ and write | E | | 1 | in it.Here, flush() method flushes the stream and close() method closes the writer. " }, { "code": null, "e": 32702, "s": 32638, "text": "Output : \nBuffered Writer start writing :)\nWritten successfully" }, { "code": null, "e": 33122, "s": 32702, "text": "This article is contributed by Mohit Gupta . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 33140, "s": 33122, "text": "gulshankumarar231" }, { "code": null, "e": 33153, "s": 33140, "text": "simmytarika5" }, { "code": null, "e": 33158, "s": 33153, "text": "Java" }, { "code": null, "e": 33163, "s": 33158, "text": "Java" }, { "code": null, "e": 33261, "s": 33163, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33312, "s": 33261, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 33342, "s": 33312, "text": "HashMap in Java with Examples" }, { "code": null, "e": 33361, "s": 33342, "text": "Interfaces in Java" }, { "code": null, "e": 33376, "s": 33361, "text": "Stream In Java" }, { "code": null, "e": 33407, "s": 33376, "text": "How to iterate any Map in Java" }, { "code": null, "e": 33425, "s": 33407, "text": "ArrayList in Java" }, { "code": null, "e": 33457, "s": 33425, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 33477, "s": 33457, "text": "Stack Class in Java" }, { "code": null, "e": 33509, "s": 33477, "text": "Multidimensional Arrays in Java" } ]
Java Program to Convert ArrayList to LinkedList - GeeksforGeeks
28 Oct, 2021 Given an array list, your task is to write a program to convert the given array list to Linked List in Java. Examples: Input: ArrayList: [Geeks, forGeeks, A computer Portal] Output: LinkedList: [Geeks, forGeeks, A computer Portal] Input: ArrayList: [1, 2, 3, 4, 5] Output: LinkedList: [1, 2, 3, 4, 5] ArrayList – An ArrayList is a part of the collection framework and is present in java.util package. It provides us dynamic arrays in Java. Though, it may be slower than standard arrays but can be helpful in programs where lots of manipulation in the array is needed. Linked List – A linked list is a linear data structure, in which the elements are not stored at contiguous memory locations. The elements in a linked list are linked using pointers as shown in the below image: There are numerous approaches to convert the given array list to a linked list in Java. A few of them are listed below. Using Brute Force or Naive Method Using List Constructor Using Java 8 Streams API Using Google’s Guava Library Conversion between incompatible types In this method, an empty LinkedList is created and all elements present of the ArrayList are added to it one by one. Algorithm: Get the ArrayList to be converted. Create an empty LinkedList. Iterate through the items in the ArrayList. For each item, add it to LinkedList. Return the formed LinkedList. Code: Java // Java Program to convert// ArrayList to LinkedList // using Naive method import java.util.*;import java.util.stream.*; class GFG { // Generic function to convert an ArrayList to LinkedList public static <T> List<T> convertALtoLL(List<T> aL) { // Create an empty LinkedList List<T> lL = new LinkedList<>(); // Iterate through the aL for (T t : aL) { // Add each element into the lL lL.add(t); } // Return the converted LinkedList return lL; } public static void main(String args[]) { // Create an ArrayList List<String> aL = Arrays.asList("Geeks", "forGeeks", "A computer Portal"); // Print the ArrayList System.out.println("ArrayList: " + aL); // convert the ArrayList to LinkedList List<String> lL = convertALtoLL(aL); // Print the LinkedList System.out.println("LinkedList: " + lL); }} ArrayList: [Geeks, forGeeks, A computer Portal] LinkedList: [Geeks, forGeeks, A computer Portal] In this method, the ArrayList is passed as the parameter into the LinkedList constructor. Algorithm: Get the ArrayList to be converted. Create the LinkedList by passing the ArrayList as parameter in the constructor of the LinkedList. Return the formed LinkedList. Code: Java // Java Program to convert// ArrayList to LinkedList// using List Constructor import java.util.*;import java.util.stream.*; class GFG { // Generic function to convert an ArrayList to LinkedList public static <T> List<T> convertALtoLL(List<T> aL) { // Create the LinkedList by passing the ArrayList // as parameter in the constructor List<T> lL = new LinkedList<>(aL); // Return the converted LinkedList return lL; } public static void main(String args[]) { // Create an ArrayList List<String> aL = Arrays.asList("Geeks", "forGeeks", "A computer Portal"); // Print the ArrayList System.out.println("ArrayList: " + aL); // convert the ArrayList to LinkedList List<String> lL = convertALtoLL(aL); // Print the LinkedList System.out.println("LinkedList: " + lL); }} ArrayList: [Geeks, forGeeks, A computer Portal] LinkedList: [Geeks, forGeeks, A computer Portal] This method includes converting the ArrayList to a Stream and collect elements of a stream in a LinkedList using Stream.collect() method which accepts a collector. Algorithm: Get the ArrayList to be converted. Convert the ArrayList into the stream. Using Collectors, collect the ArrayList Stream and convert it into LinkedList. Now collect the LinkedList. Return the formed LinkedList. Code: Java // Java Program to convert// ArrayList to LinkedList// using Streams API import java.util.*;import java.util.stream.*; class GFG { // Generic function to convert an // ArrayList to LinkedList public static <T> List<T> convertALtoLL( List<T> aL) { // Return the converted LinkedList return aL // Convert the ArrayList into Stream .stream() // Collect the LinkedList .collect(Collectors // Convert the Stream into LinkedList // Collection type .toCollection(LinkedList::new)); } public static void main(String args[]) { // Create an ArrayList List<String> aL = Arrays.asList("Geeks", "forGeeks", "A computer Portal"); // Print the ArrayList System.out.println("ArrayList: " + aL); // convert the ArrayList to LinkedList List<String> lL = convertALtoLL(aL); // Print the LinkedList System.out.println("LinkedList: " + lL); }} ArrayList: [Geeks, forGeeks, A computer Portal] LinkedList: [Geeks, forGeeks, A computer Portal] Guava also provides a LinkedList implementation which can be used to create a LinkedList from another collection using Collection.addAll() method. Algorithm: Get the ArrayList to be converted. Create an empty LinkedList. Add the elements of the ArrayList into the LinkedList using LinkedList.addAll() method and passing the ArrayList as the parameter. Return the formed LinkedList. Code: Java // Java Program to convert// ArrayList to LinkedList// using Google's Guave library import java.util.*;import java.util.stream.*; class GFG { // Generic function to convert an ArrayList // to LinkedList public static <T> List<T> convertALtoLL(List<T> aL) { // Create an empty LinkedList List<T> lL = new LinkedList<>(); // Add ArrayList into the lL lL.addAll(aL); // Return the converted LinkedList return lL; } public static void main(String args[]) { // Create an ArrayList List<String> aL = Arrays.asList("Geeks", "forGeeks", "A computer Portal"); // Print the ArrayList System.out.println("ArrayList: " + aL); // convert the ArrayList to LinkedList List<String> lL = convertALtoLL(aL); // Print the LinkedList System.out.println("LinkedList: " + lL); }} ArrayList: [Geeks, forGeeks, A computer Portal] LinkedList: [Geeks, forGeeks, A computer Portal] This method can be used if the required TreeMap is of the different type than the HashMap. In this, the conversion needs to be done manually. Algorithm: Get the ArrayList to be converted. Convert the ArrayList into the stream. Convert the stream elements into the desired type by casting. This can be done by passing the casting function as parameter to map() function. Using Collectors, collect the ArrayList Stream and convert it into LinkedList. Now collect the LinkedList. Return the formed LinkedList. Code: Java // Java Program to convert// ArrayList to LinkedList for// Conversion between incompatible types import java.util.*;import java.util.stream.*; class GFG { // Generic function to convert an ArrayList to LinkedList public static <T> List<String> convertALtoLL(List<T> aL) { // Return the converted LinkedList return aL // Convert the ArrayList into Stream .stream() // Convert the Stream into String // Desired casting function can be passed // as parameter in next step .map(String::valueOf) // Collect the LinkedList .collect(Collectors // Convert the Stream into LinkedList // Collection type .toCollection(LinkedList::new)); } public static void main(String args[]) { // Create an ArrayList List<Integer> aL = Arrays.asList(1, 2, 3, 4, 5); // Print the ArrayList System.out.println("ArrayList: " + aL); // convert the ArrayList to LinkedList List<String> lL = convertALtoLL(aL); // Print the LinkedList System.out.println("LinkedList: " + lL); }} ArrayList: [1, 2, 3, 4, 5] LinkedList: [1, 2, 3, 4, 5] nishkarshgandhi Java-ArrayList Java-Collections java-LinkedList java-list Java-List-Programs Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples Interfaces in Java Stream In Java How to iterate any Map in Java Initialize an ArrayList in Java Stack Class in Java Multidimensional Arrays in Java Singleton Class in Java Set in Java
[ { "code": null, "e": 25775, "s": 25747, "text": "\n28 Oct, 2021" }, { "code": null, "e": 25885, "s": 25775, "text": "Given an array list, your task is to write a program to convert the given array list to Linked List in Java. " }, { "code": null, "e": 25896, "s": 25885, "text": "Examples: " }, { "code": null, "e": 26081, "s": 25896, "text": "Input: ArrayList: [Geeks, forGeeks, A computer Portal] \nOutput: LinkedList: [Geeks, forGeeks, A computer Portal]\nInput: ArrayList: [1, 2, 3, 4, 5] \nOutput: LinkedList: [1, 2, 3, 4, 5] " }, { "code": null, "e": 26348, "s": 26081, "text": "ArrayList – An ArrayList is a part of the collection framework and is present in java.util package. It provides us dynamic arrays in Java. Though, it may be slower than standard arrays but can be helpful in programs where lots of manipulation in the array is needed." }, { "code": null, "e": 26560, "s": 26348, "text": "Linked List – A linked list is a linear data structure, in which the elements are not stored at contiguous memory locations. The elements in a linked list are linked using pointers as shown in the below image: " }, { "code": null, "e": 26680, "s": 26560, "text": "There are numerous approaches to convert the given array list to a linked list in Java. A few of them are listed below." }, { "code": null, "e": 26714, "s": 26680, "text": "Using Brute Force or Naive Method" }, { "code": null, "e": 26737, "s": 26714, "text": "Using List Constructor" }, { "code": null, "e": 26762, "s": 26737, "text": "Using Java 8 Streams API" }, { "code": null, "e": 26791, "s": 26762, "text": "Using Google’s Guava Library" }, { "code": null, "e": 26829, "s": 26791, "text": "Conversion between incompatible types" }, { "code": null, "e": 26946, "s": 26829, "text": "In this method, an empty LinkedList is created and all elements present of the ArrayList are added to it one by one." }, { "code": null, "e": 26958, "s": 26946, "text": "Algorithm: " }, { "code": null, "e": 26993, "s": 26958, "text": "Get the ArrayList to be converted." }, { "code": null, "e": 27021, "s": 26993, "text": "Create an empty LinkedList." }, { "code": null, "e": 27065, "s": 27021, "text": "Iterate through the items in the ArrayList." }, { "code": null, "e": 27102, "s": 27065, "text": "For each item, add it to LinkedList." }, { "code": null, "e": 27132, "s": 27102, "text": "Return the formed LinkedList." }, { "code": null, "e": 27138, "s": 27132, "text": "Code:" }, { "code": null, "e": 27143, "s": 27138, "text": "Java" }, { "code": "// Java Program to convert// ArrayList to LinkedList // using Naive method import java.util.*;import java.util.stream.*; class GFG { // Generic function to convert an ArrayList to LinkedList public static <T> List<T> convertALtoLL(List<T> aL) { // Create an empty LinkedList List<T> lL = new LinkedList<>(); // Iterate through the aL for (T t : aL) { // Add each element into the lL lL.add(t); } // Return the converted LinkedList return lL; } public static void main(String args[]) { // Create an ArrayList List<String> aL = Arrays.asList(\"Geeks\", \"forGeeks\", \"A computer Portal\"); // Print the ArrayList System.out.println(\"ArrayList: \" + aL); // convert the ArrayList to LinkedList List<String> lL = convertALtoLL(aL); // Print the LinkedList System.out.println(\"LinkedList: \" + lL); }}", "e": 28182, "s": 27143, "text": null }, { "code": null, "e": 28279, "s": 28182, "text": "ArrayList: [Geeks, forGeeks, A computer Portal]\nLinkedList: [Geeks, forGeeks, A computer Portal]" }, { "code": null, "e": 28369, "s": 28279, "text": "In this method, the ArrayList is passed as the parameter into the LinkedList constructor." }, { "code": null, "e": 28381, "s": 28369, "text": "Algorithm: " }, { "code": null, "e": 28416, "s": 28381, "text": "Get the ArrayList to be converted." }, { "code": null, "e": 28514, "s": 28416, "text": "Create the LinkedList by passing the ArrayList as parameter in the constructor of the LinkedList." }, { "code": null, "e": 28544, "s": 28514, "text": "Return the formed LinkedList." }, { "code": null, "e": 28550, "s": 28544, "text": "Code:" }, { "code": null, "e": 28555, "s": 28550, "text": "Java" }, { "code": "// Java Program to convert// ArrayList to LinkedList// using List Constructor import java.util.*;import java.util.stream.*; class GFG { // Generic function to convert an ArrayList to LinkedList public static <T> List<T> convertALtoLL(List<T> aL) { // Create the LinkedList by passing the ArrayList // as parameter in the constructor List<T> lL = new LinkedList<>(aL); // Return the converted LinkedList return lL; } public static void main(String args[]) { // Create an ArrayList List<String> aL = Arrays.asList(\"Geeks\", \"forGeeks\", \"A computer Portal\"); // Print the ArrayList System.out.println(\"ArrayList: \" + aL); // convert the ArrayList to LinkedList List<String> lL = convertALtoLL(aL); // Print the LinkedList System.out.println(\"LinkedList: \" + lL); }}", "e": 29526, "s": 28555, "text": null }, { "code": null, "e": 29623, "s": 29526, "text": "ArrayList: [Geeks, forGeeks, A computer Portal]\nLinkedList: [Geeks, forGeeks, A computer Portal]" }, { "code": null, "e": 29787, "s": 29623, "text": "This method includes converting the ArrayList to a Stream and collect elements of a stream in a LinkedList using Stream.collect() method which accepts a collector." }, { "code": null, "e": 29799, "s": 29787, "text": "Algorithm: " }, { "code": null, "e": 29834, "s": 29799, "text": "Get the ArrayList to be converted." }, { "code": null, "e": 29873, "s": 29834, "text": "Convert the ArrayList into the stream." }, { "code": null, "e": 29952, "s": 29873, "text": "Using Collectors, collect the ArrayList Stream and convert it into LinkedList." }, { "code": null, "e": 29980, "s": 29952, "text": "Now collect the LinkedList." }, { "code": null, "e": 30010, "s": 29980, "text": "Return the formed LinkedList." }, { "code": null, "e": 30016, "s": 30010, "text": "Code:" }, { "code": null, "e": 30021, "s": 30016, "text": "Java" }, { "code": "// Java Program to convert// ArrayList to LinkedList// using Streams API import java.util.*;import java.util.stream.*; class GFG { // Generic function to convert an // ArrayList to LinkedList public static <T> List<T> convertALtoLL( List<T> aL) { // Return the converted LinkedList return aL // Convert the ArrayList into Stream .stream() // Collect the LinkedList .collect(Collectors // Convert the Stream into LinkedList // Collection type .toCollection(LinkedList::new)); } public static void main(String args[]) { // Create an ArrayList List<String> aL = Arrays.asList(\"Geeks\", \"forGeeks\", \"A computer Portal\"); // Print the ArrayList System.out.println(\"ArrayList: \" + aL); // convert the ArrayList to LinkedList List<String> lL = convertALtoLL(aL); // Print the LinkedList System.out.println(\"LinkedList: \" + lL); }}", "e": 31152, "s": 30021, "text": null }, { "code": null, "e": 31249, "s": 31152, "text": "ArrayList: [Geeks, forGeeks, A computer Portal]\nLinkedList: [Geeks, forGeeks, A computer Portal]" }, { "code": null, "e": 31396, "s": 31249, "text": "Guava also provides a LinkedList implementation which can be used to create a LinkedList from another collection using Collection.addAll() method." }, { "code": null, "e": 31408, "s": 31396, "text": "Algorithm: " }, { "code": null, "e": 31443, "s": 31408, "text": "Get the ArrayList to be converted." }, { "code": null, "e": 31471, "s": 31443, "text": "Create an empty LinkedList." }, { "code": null, "e": 31602, "s": 31471, "text": "Add the elements of the ArrayList into the LinkedList using LinkedList.addAll() method and passing the ArrayList as the parameter." }, { "code": null, "e": 31632, "s": 31602, "text": "Return the formed LinkedList." }, { "code": null, "e": 31638, "s": 31632, "text": "Code:" }, { "code": null, "e": 31643, "s": 31638, "text": "Java" }, { "code": "// Java Program to convert// ArrayList to LinkedList// using Google's Guave library import java.util.*;import java.util.stream.*; class GFG { // Generic function to convert an ArrayList // to LinkedList public static <T> List<T> convertALtoLL(List<T> aL) { // Create an empty LinkedList List<T> lL = new LinkedList<>(); // Add ArrayList into the lL lL.addAll(aL); // Return the converted LinkedList return lL; } public static void main(String args[]) { // Create an ArrayList List<String> aL = Arrays.asList(\"Geeks\", \"forGeeks\", \"A computer Portal\"); // Print the ArrayList System.out.println(\"ArrayList: \" + aL); // convert the ArrayList to LinkedList List<String> lL = convertALtoLL(aL); // Print the LinkedList System.out.println(\"LinkedList: \" + lL); }}", "e": 32622, "s": 31643, "text": null }, { "code": null, "e": 32719, "s": 32622, "text": "ArrayList: [Geeks, forGeeks, A computer Portal]\nLinkedList: [Geeks, forGeeks, A computer Portal]" }, { "code": null, "e": 32861, "s": 32719, "text": "This method can be used if the required TreeMap is of the different type than the HashMap. In this, the conversion needs to be done manually." }, { "code": null, "e": 32873, "s": 32861, "text": "Algorithm: " }, { "code": null, "e": 32908, "s": 32873, "text": "Get the ArrayList to be converted." }, { "code": null, "e": 32947, "s": 32908, "text": "Convert the ArrayList into the stream." }, { "code": null, "e": 33090, "s": 32947, "text": "Convert the stream elements into the desired type by casting. This can be done by passing the casting function as parameter to map() function." }, { "code": null, "e": 33169, "s": 33090, "text": "Using Collectors, collect the ArrayList Stream and convert it into LinkedList." }, { "code": null, "e": 33197, "s": 33169, "text": "Now collect the LinkedList." }, { "code": null, "e": 33227, "s": 33197, "text": "Return the formed LinkedList." }, { "code": null, "e": 33233, "s": 33227, "text": "Code:" }, { "code": null, "e": 33238, "s": 33233, "text": "Java" }, { "code": "// Java Program to convert// ArrayList to LinkedList for// Conversion between incompatible types import java.util.*;import java.util.stream.*; class GFG { // Generic function to convert an ArrayList to LinkedList public static <T> List<String> convertALtoLL(List<T> aL) { // Return the converted LinkedList return aL // Convert the ArrayList into Stream .stream() // Convert the Stream into String // Desired casting function can be passed // as parameter in next step .map(String::valueOf) // Collect the LinkedList .collect(Collectors // Convert the Stream into LinkedList // Collection type .toCollection(LinkedList::new)); } public static void main(String args[]) { // Create an ArrayList List<Integer> aL = Arrays.asList(1, 2, 3, 4, 5); // Print the ArrayList System.out.println(\"ArrayList: \" + aL); // convert the ArrayList to LinkedList List<String> lL = convertALtoLL(aL); // Print the LinkedList System.out.println(\"LinkedList: \" + lL); }}", "e": 34421, "s": 33238, "text": null }, { "code": null, "e": 34476, "s": 34421, "text": "ArrayList: [1, 2, 3, 4, 5]\nLinkedList: [1, 2, 3, 4, 5]" }, { "code": null, "e": 34492, "s": 34476, "text": "nishkarshgandhi" }, { "code": null, "e": 34507, "s": 34492, "text": "Java-ArrayList" }, { "code": null, "e": 34524, "s": 34507, "text": "Java-Collections" }, { "code": null, "e": 34540, "s": 34524, "text": "java-LinkedList" }, { "code": null, "e": 34550, "s": 34540, "text": "java-list" }, { "code": null, "e": 34569, "s": 34550, "text": "Java-List-Programs" }, { "code": null, "e": 34574, "s": 34569, "text": "Java" }, { "code": null, "e": 34579, "s": 34574, "text": "Java" }, { "code": null, "e": 34596, "s": 34579, "text": "Java-Collections" }, { "code": null, "e": 34694, "s": 34596, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34745, "s": 34694, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 34775, "s": 34745, "text": "HashMap in Java with Examples" }, { "code": null, "e": 34794, "s": 34775, "text": "Interfaces in Java" }, { "code": null, "e": 34809, "s": 34794, "text": "Stream In Java" }, { "code": null, "e": 34840, "s": 34809, "text": "How to iterate any Map in Java" }, { "code": null, "e": 34872, "s": 34840, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 34892, "s": 34872, "text": "Stack Class in Java" }, { "code": null, "e": 34924, "s": 34892, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 34948, "s": 34924, "text": "Singleton Class in Java" } ]
How to make a Realistic Motion Blur with CSS Transitions ? - GeeksforGeeks
08 Nov, 2021 In this article, we are going to create a realistic Motion Blur effect with CSS Transitions. Motion Blur is a special kind of effect that we can see in various online videos, movies, or animated clips. When an object moves from one place to another place with some fair speed then it gets blurred which makes the user infer that the object is moving fast. We are going to create the same effect using the CSS transition property. CSS Transitions: This property allows us to move the element smoothly on the page. We will use the CSS transition-delay property which helps us to start the transition with some delay as specified. Approach: We will create the same shape 15 times and use a slightly different transition delay for each element for moving the element from one position to another position. This simple method will help us to create a realistic motion blur of that element. Example 1: We will use a rectangular shape for our motion blur effect, when the cursor will move to the container, the shape will start to move with the motion blur effect. HTML <!DOCTYPE html><html lang="en"> <head> <style> .object_container { width: 100%; height: 100px; position: relative; margin: 100px auto; text-align: center; font-family: sans-serif; padding-top: 10px; background-color: rgb(32, 32, 32); } .shape { position: absolute; background: rgb(255, 255, 255); width: 50px; height: 50px; border-radius: 0%; transform: rotate(0deg); top: 25px; left: 25px; opacity: 0.1; transition: all 0.75s cubic-bezier(0.23, 1, 0.32, 1) 0ms; } .object_container:hover .shape { left: 525px; } .shape.two { transition-delay: 2ms; } .shape.three { transition-delay: 4ms; } .shape.four { transition-delay: 6ms; } .shape.five { transition-delay: 8ms; } .shape.six { transition-delay: 10ms; } .shape.seven { transition-delay: 12ms; } .shape.eight { transition-delay: 14ms; } .shape.nine { transition-delay: 16ms; } .shape.ten { transition-delay: 18ms; } .shape.eleven { transition-delay: 20ms; } .shape.twelve { transition-delay: 22ms; } .shape.thirteen { transition-delay: 24ms; } .shape.fourteen { transition-delay: 26ms; } .shape.fifteen { transition-delay: 28ms; } </style></head> <body> <div class="object_container"> <div class="shape one"><br /></div> <div class="shape two"><br /></div> <div class="shape three"><br /></div> <div class="shape four"><br /></div> <div class="shape five"><br /></div> <div class="shape six"><br /></div> <div class="shape seven"><br /></div> <div class="shape eight"><br /></div> <div class="shape nine"><br /></div> <div class="shape ten"><br /></div> <div class="shape eleven"><br /></div> <div class="shape twelve"><br /></div> <div class="shape thirteen"><br /></div> <div class="shape fourteen"><br /></div> <div class="shape fifteen"><br /></div> </div></body> </html> Output: Motion Blur with CSS Transition Example 2: In this example, we can clearly see the difference between with and without motion blur we will apply the same effect on the circular shape. HTML <!DOCTYPE html><html lang="en"> <head> <style> body { background-color: rgb(41, 41, 41); } /* First container is moving without motion blur */ .object_container1 { width: 615px; height: 100px; position: absolute; margin: 100px auto; text-align: center; font-family: sans-serif; padding-top: 10px; background-color: rgb(32, 32, 32); } /* Second container is moving with motion blur */ .object_container2 { width: 615px; height: 100px; position: absolute; margin: 100px auto; text-align: center; font-family: sans-serif; padding-top: 10px; background-color: rgb(32, 32, 32); } /* For this shape we have removed the transition effect */ .shape1 { position: absolute; background: rgb(255, 255, 255); width: 50px; height: 50px; border-radius: 0%; transform: rotate(0deg); top: 25px; left: 25px; opacity: 0.1; border-radius: 100%; } /* We have added the transition effect so we can see the motion blur effect */ .shape2 { position: absolute; background: rgb(255, 255, 255); width: 50px; height: 50px; border-radius: 0%; transform: rotate(0deg); top: 25px; left: 25px; opacity: 0.1; transition: all 0.75s cubic-bezier(0.23, 1, 0.32, 1) 0ms; border-radius: 100%; } .box1 .box2 { display: flex; flex-direction: column; align-items: center; justify-content: center; } .box1 { top: 100px; left: 100px; position: absolute; height: 350px; width: 32%; background-color: #fff; } .box2 { top: 100px; right: 100px; position: absolute; height: 350px; width: 32%; background-color: #fff; } #without { position: absolute; top: 370px; left: 200px; color: #fff; } #with { position: absolute; top: 370px; right: 200px; color: #fff; } .object_container1:hover .shape1 { left: 525px; } .object_container2:hover .shape2 { left: 525px; } .shape2.two { transition-delay: 2ms; } .shape2.three { transition-delay: 4ms; } .shape2.four { transition-delay: 6ms; } .shape2.five { transition-delay: 8ms; } .shape2.six { transition-delay: 10ms; } .shape2.seven { transition-delay: 12ms; } .shape2.eight { transition-delay: 14ms; } .shape2.nine { transition-delay: 16ms; } .shape2.ten { transition-delay: 18ms; } </style></head> <body> <!-- With motion blur --> <div class="box1"> <div class="object_container1"> <div class="shape1 one"><br /></div> <div class="shape1 two"><br /></div> <div class="shape1 three"><br /></div> <div class="shape1 four"><br /></div> <div class="shape1 five"><br /></div> <div class="shape1 six"><br /></div> <div class="shape1 seven"><br /></div> <div class="shape1 eight"><br /></div> <div class="shape1 nine"><br /></div> <div class="shape1 ten"><br /></div> </div> <h1 id="without">Without Motion blur</h1> </div> <!-- Without motion blur --> <div class="box2"> <div class="object_container2"> <div class="shape2 one"><br /></div> <div class="shape2 two"><br /></div> <div class="shape2 three"><br /></div> <div class="shape2 four"><br /></div> <div class="shape2 five"><br /></div> <div class="shape2 six"><br /></div> <div class="shape2 seven"><br /></div> <div class="shape2 eight"><br /></div> <div class="shape2 nine"><br /></div> <div class="shape2 ten"><br /></div> </div> <h1 id="with">With Motion blur</h1> </div></body> </html> Output: Motion blur with CSS Transition Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. CSS-Properties CSS-Questions HTML-Questions Picked CSS HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to set space between the flexbox ? Design a web page using HTML and CSS Form validation using jQuery How to style a checkbox using CSS? Search Bar using HTML, CSS and JavaScript How to set the default value for an HTML <select> element ? Hide or show elements in HTML using display property How to set input type date in dd-mm-yyyy format using HTML ? REST API (Introduction) How to Insert Form Data into Database using PHP ?
[ { "code": null, "e": 26621, "s": 26593, "text": "\n08 Nov, 2021" }, { "code": null, "e": 26978, "s": 26621, "text": "In this article, we are going to create a realistic Motion Blur effect with CSS Transitions. Motion Blur is a special kind of effect that we can see in various online videos, movies, or animated clips. When an object moves from one place to another place with some fair speed then it gets blurred which makes the user infer that the object is moving fast. " }, { "code": null, "e": 27250, "s": 26978, "text": "We are going to create the same effect using the CSS transition property. CSS Transitions: This property allows us to move the element smoothly on the page. We will use the CSS transition-delay property which helps us to start the transition with some delay as specified." }, { "code": null, "e": 27507, "s": 27250, "text": "Approach: We will create the same shape 15 times and use a slightly different transition delay for each element for moving the element from one position to another position. This simple method will help us to create a realistic motion blur of that element." }, { "code": null, "e": 27683, "s": 27509, "text": "Example 1: We will use a rectangular shape for our motion blur effect, when the cursor will move to the container, the shape will start to move with the motion blur effect. " }, { "code": null, "e": 27688, "s": 27683, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <style> .object_container { width: 100%; height: 100px; position: relative; margin: 100px auto; text-align: center; font-family: sans-serif; padding-top: 10px; background-color: rgb(32, 32, 32); } .shape { position: absolute; background: rgb(255, 255, 255); width: 50px; height: 50px; border-radius: 0%; transform: rotate(0deg); top: 25px; left: 25px; opacity: 0.1; transition: all 0.75s cubic-bezier(0.23, 1, 0.32, 1) 0ms; } .object_container:hover .shape { left: 525px; } .shape.two { transition-delay: 2ms; } .shape.three { transition-delay: 4ms; } .shape.four { transition-delay: 6ms; } .shape.five { transition-delay: 8ms; } .shape.six { transition-delay: 10ms; } .shape.seven { transition-delay: 12ms; } .shape.eight { transition-delay: 14ms; } .shape.nine { transition-delay: 16ms; } .shape.ten { transition-delay: 18ms; } .shape.eleven { transition-delay: 20ms; } .shape.twelve { transition-delay: 22ms; } .shape.thirteen { transition-delay: 24ms; } .shape.fourteen { transition-delay: 26ms; } .shape.fifteen { transition-delay: 28ms; } </style></head> <body> <div class=\"object_container\"> <div class=\"shape one\"><br /></div> <div class=\"shape two\"><br /></div> <div class=\"shape three\"><br /></div> <div class=\"shape four\"><br /></div> <div class=\"shape five\"><br /></div> <div class=\"shape six\"><br /></div> <div class=\"shape seven\"><br /></div> <div class=\"shape eight\"><br /></div> <div class=\"shape nine\"><br /></div> <div class=\"shape ten\"><br /></div> <div class=\"shape eleven\"><br /></div> <div class=\"shape twelve\"><br /></div> <div class=\"shape thirteen\"><br /></div> <div class=\"shape fourteen\"><br /></div> <div class=\"shape fifteen\"><br /></div> </div></body> </html>", "e": 30186, "s": 27688, "text": null }, { "code": null, "e": 30194, "s": 30186, "text": "Output:" }, { "code": null, "e": 30226, "s": 30194, "text": "Motion Blur with CSS Transition" }, { "code": null, "e": 30378, "s": 30226, "text": "Example 2: In this example, we can clearly see the difference between with and without motion blur we will apply the same effect on the circular shape." }, { "code": null, "e": 30383, "s": 30378, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <style> body { background-color: rgb(41, 41, 41); } /* First container is moving without motion blur */ .object_container1 { width: 615px; height: 100px; position: absolute; margin: 100px auto; text-align: center; font-family: sans-serif; padding-top: 10px; background-color: rgb(32, 32, 32); } /* Second container is moving with motion blur */ .object_container2 { width: 615px; height: 100px; position: absolute; margin: 100px auto; text-align: center; font-family: sans-serif; padding-top: 10px; background-color: rgb(32, 32, 32); } /* For this shape we have removed the transition effect */ .shape1 { position: absolute; background: rgb(255, 255, 255); width: 50px; height: 50px; border-radius: 0%; transform: rotate(0deg); top: 25px; left: 25px; opacity: 0.1; border-radius: 100%; } /* We have added the transition effect so we can see the motion blur effect */ .shape2 { position: absolute; background: rgb(255, 255, 255); width: 50px; height: 50px; border-radius: 0%; transform: rotate(0deg); top: 25px; left: 25px; opacity: 0.1; transition: all 0.75s cubic-bezier(0.23, 1, 0.32, 1) 0ms; border-radius: 100%; } .box1 .box2 { display: flex; flex-direction: column; align-items: center; justify-content: center; } .box1 { top: 100px; left: 100px; position: absolute; height: 350px; width: 32%; background-color: #fff; } .box2 { top: 100px; right: 100px; position: absolute; height: 350px; width: 32%; background-color: #fff; } #without { position: absolute; top: 370px; left: 200px; color: #fff; } #with { position: absolute; top: 370px; right: 200px; color: #fff; } .object_container1:hover .shape1 { left: 525px; } .object_container2:hover .shape2 { left: 525px; } .shape2.two { transition-delay: 2ms; } .shape2.three { transition-delay: 4ms; } .shape2.four { transition-delay: 6ms; } .shape2.five { transition-delay: 8ms; } .shape2.six { transition-delay: 10ms; } .shape2.seven { transition-delay: 12ms; } .shape2.eight { transition-delay: 14ms; } .shape2.nine { transition-delay: 16ms; } .shape2.ten { transition-delay: 18ms; } </style></head> <body> <!-- With motion blur --> <div class=\"box1\"> <div class=\"object_container1\"> <div class=\"shape1 one\"><br /></div> <div class=\"shape1 two\"><br /></div> <div class=\"shape1 three\"><br /></div> <div class=\"shape1 four\"><br /></div> <div class=\"shape1 five\"><br /></div> <div class=\"shape1 six\"><br /></div> <div class=\"shape1 seven\"><br /></div> <div class=\"shape1 eight\"><br /></div> <div class=\"shape1 nine\"><br /></div> <div class=\"shape1 ten\"><br /></div> </div> <h1 id=\"without\">Without Motion blur</h1> </div> <!-- Without motion blur --> <div class=\"box2\"> <div class=\"object_container2\"> <div class=\"shape2 one\"><br /></div> <div class=\"shape2 two\"><br /></div> <div class=\"shape2 three\"><br /></div> <div class=\"shape2 four\"><br /></div> <div class=\"shape2 five\"><br /></div> <div class=\"shape2 six\"><br /></div> <div class=\"shape2 seven\"><br /></div> <div class=\"shape2 eight\"><br /></div> <div class=\"shape2 nine\"><br /></div> <div class=\"shape2 ten\"><br /></div> </div> <h1 id=\"with\">With Motion blur</h1> </div></body> </html>", "e": 35026, "s": 30383, "text": null }, { "code": null, "e": 35034, "s": 35026, "text": "Output:" }, { "code": null, "e": 35066, "s": 35034, "text": "Motion blur with CSS Transition" }, { "code": null, "e": 35203, "s": 35066, "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": 35218, "s": 35203, "text": "CSS-Properties" }, { "code": null, "e": 35232, "s": 35218, "text": "CSS-Questions" }, { "code": null, "e": 35247, "s": 35232, "text": "HTML-Questions" }, { "code": null, "e": 35254, "s": 35247, "text": "Picked" }, { "code": null, "e": 35258, "s": 35254, "text": "CSS" }, { "code": null, "e": 35263, "s": 35258, "text": "HTML" }, { "code": null, "e": 35280, "s": 35263, "text": "Web Technologies" }, { "code": null, "e": 35285, "s": 35280, "text": "HTML" }, { "code": null, "e": 35383, "s": 35285, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35422, "s": 35383, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 35459, "s": 35422, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 35488, "s": 35459, "text": "Form validation using jQuery" }, { "code": null, "e": 35523, "s": 35488, "text": "How to style a checkbox using CSS?" }, { "code": null, "e": 35565, "s": 35523, "text": "Search Bar using HTML, CSS and JavaScript" }, { "code": null, "e": 35625, "s": 35565, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 35678, "s": 35625, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 35739, "s": 35678, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 35763, "s": 35739, "text": "REST API (Introduction)" } ]
Lazy Loading images in HTML - GeeksforGeeks
01 Dec, 2020 What is Lazy Loading? Lazy loading is a strategy to identify resources as non-critical and load these only when needed. It’s a way to optimize web pages, which translates into reduced page load times. To read more about it: https://www.geeksforgeeks.org/what-is-lazy-loading/ Generally images are larger in size, so lazy loading can be used to defer the offscreen images. Difference from JavaScript solutions ? There are many JavaScript solutions to support lazy loading but recently browsers have also started to implement lazy loading of images and iframes. Using browser method is more performance but it is not fully supported right now. Approach: To use Lazy Loading, use the loading attribute of image tag in html. Here are the supported values for the loading attribute: auto: Default lazy-loading behavior of the browser, which is the same as not including the attribute. lazy: Defer loading of the resource until it reaches a calculated distance from the viewport. eager: Load the resource immediately, regardless of where it’s located on the page. Example: HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content= "width=device-width, initial-scale=1.0"> <title>Lazy Loading Images</title></head> <body> <h1>Lazy Loading Images</h1> <!-- loading attribute of image tag is used to specify lazy loading --> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20201109171634/1.jpg" alt="numbers" loading="lazy" width="300" height="300" style="display:block; margin:10px" /> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20201109171633/2.jpg" alt="numbers" loading="lazy" width="300" height="300" style="display:block; margin:10px" /> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20201109171632/3.jpg" alt="numbers" loading="lazy" width="300" height="300" style="display:block; margin:10px" /> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20201109171631/4.jpg" alt="numbers" loading="lazy" width="300" height="300" style="display:block; margin:10px" /> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20201109171629/5.jpg" alt="numbers" loading="lazy" width="300" height="300" style="display:block; margin:10px" /> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20201109171628/6.jpg" alt="numbers" loading="lazy" width="300" height="300" style="display:block; margin:10px" /> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20201109171627/7.jpg" alt="numbers" loading="lazy" width="300" height="300" style="display:block; margin:10px" /> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20201109171626/8.jpg" alt="numbers" loading="lazy" width="300" height="300" style="display:block; margin:10px" /> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20201109171625/9.jpg" alt="numbers" loading="lazy" width="300" height="300" style="display:block; margin:10px" /> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20201109171623/10.jpg" alt="numbers" loading="lazy" width="300" height="300" style="display:block; margin:10px" /> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20201109171622/11.jpg" alt="numbers" loading="lazy" width="300" height="300" style="display:block; margin:10px" /> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20201109171621/12.jpg" alt="numbers" loading="lazy" width="300" height="300" style="display:block; margin:10px" /> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20201109171620/13.jpg" alt="numbers" loading="lazy" width="300" height="300" style="display:block; margin:10px" /> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20201109171619/14.jpg" alt="numbers" loading="lazy" width="300" height="300" style="display:block; margin:10px" /> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20201109171618/15.jpg" alt="numbers" loading="lazy" width="300" height="300" style="display:block; margin:10px" /></body> </html> Output: Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. HTML-Misc HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. REST API (Introduction) HTML Cheat Sheet - A Basic Guide to HTML Design a web page using HTML and CSS Form validation using jQuery Angular File Upload 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": 26139, "s": 26111, "text": "\n01 Dec, 2020" }, { "code": null, "e": 26161, "s": 26139, "text": "What is Lazy Loading?" }, { "code": null, "e": 26416, "s": 26161, "text": "Lazy loading is a strategy to identify resources as non-critical and load these only when needed. It’s a way to optimize web pages, which translates into reduced page load times. To read more about it: https://www.geeksforgeeks.org/what-is-lazy-loading/" }, { "code": null, "e": 26512, "s": 26416, "text": "Generally images are larger in size, so lazy loading can be used to defer the offscreen images." }, { "code": null, "e": 26551, "s": 26512, "text": "Difference from JavaScript solutions ?" }, { "code": null, "e": 26783, "s": 26551, "text": "There are many JavaScript solutions to support lazy loading but recently browsers have also started to implement lazy loading of images and iframes. Using browser method is more performance but it is not fully supported right now. " }, { "code": null, "e": 26919, "s": 26783, "text": "Approach: To use Lazy Loading, use the loading attribute of image tag in html. Here are the supported values for the loading attribute:" }, { "code": null, "e": 27021, "s": 26919, "text": "auto: Default lazy-loading behavior of the browser, which is the same as not including the attribute." }, { "code": null, "e": 27115, "s": 27021, "text": "lazy: Defer loading of the resource until it reaches a calculated distance from the viewport." }, { "code": null, "e": 27199, "s": 27115, "text": "eager: Load the resource immediately, regardless of where it’s located on the page." }, { "code": null, "e": 27208, "s": 27199, "text": "Example:" }, { "code": null, "e": 27213, "s": 27208, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\"> <title>Lazy Loading Images</title></head> <body> <h1>Lazy Loading Images</h1> <!-- loading attribute of image tag is used to specify lazy loading --> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20201109171634/1.jpg\" alt=\"numbers\" loading=\"lazy\" width=\"300\" height=\"300\" style=\"display:block; margin:10px\" /> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20201109171633/2.jpg\" alt=\"numbers\" loading=\"lazy\" width=\"300\" height=\"300\" style=\"display:block; margin:10px\" /> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20201109171632/3.jpg\" alt=\"numbers\" loading=\"lazy\" width=\"300\" height=\"300\" style=\"display:block; margin:10px\" /> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20201109171631/4.jpg\" alt=\"numbers\" loading=\"lazy\" width=\"300\" height=\"300\" style=\"display:block; margin:10px\" /> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20201109171629/5.jpg\" alt=\"numbers\" loading=\"lazy\" width=\"300\" height=\"300\" style=\"display:block; margin:10px\" /> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20201109171628/6.jpg\" alt=\"numbers\" loading=\"lazy\" width=\"300\" height=\"300\" style=\"display:block; margin:10px\" /> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20201109171627/7.jpg\" alt=\"numbers\" loading=\"lazy\" width=\"300\" height=\"300\" style=\"display:block; margin:10px\" /> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20201109171626/8.jpg\" alt=\"numbers\" loading=\"lazy\" width=\"300\" height=\"300\" style=\"display:block; margin:10px\" /> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20201109171625/9.jpg\" alt=\"numbers\" loading=\"lazy\" width=\"300\" height=\"300\" style=\"display:block; margin:10px\" /> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20201109171623/10.jpg\" alt=\"numbers\" loading=\"lazy\" width=\"300\" height=\"300\" style=\"display:block; margin:10px\" /> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20201109171622/11.jpg\" alt=\"numbers\" loading=\"lazy\" width=\"300\" height=\"300\" style=\"display:block; margin:10px\" /> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20201109171621/12.jpg\" alt=\"numbers\" loading=\"lazy\" width=\"300\" height=\"300\" style=\"display:block; margin:10px\" /> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20201109171620/13.jpg\" alt=\"numbers\" loading=\"lazy\" width=\"300\" height=\"300\" style=\"display:block; margin:10px\" /> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20201109171619/14.jpg\" alt=\"numbers\" loading=\"lazy\" width=\"300\" height=\"300\" style=\"display:block; margin:10px\" /> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20201109171618/15.jpg\" alt=\"numbers\" loading=\"lazy\" width=\"300\" height=\"300\" style=\"display:block; margin:10px\" /></body> </html>", "e": 30604, "s": 27213, "text": null }, { "code": null, "e": 30612, "s": 30604, "text": "Output:" }, { "code": null, "e": 30749, "s": 30612, "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": 30759, "s": 30749, "text": "HTML-Misc" }, { "code": null, "e": 30764, "s": 30759, "text": "HTML" }, { "code": null, "e": 30781, "s": 30764, "text": "Web Technologies" }, { "code": null, "e": 30786, "s": 30781, "text": "HTML" }, { "code": null, "e": 30884, "s": 30786, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30908, "s": 30884, "text": "REST API (Introduction)" }, { "code": null, "e": 30949, "s": 30908, "text": "HTML Cheat Sheet - A Basic Guide to HTML" }, { "code": null, "e": 30986, "s": 30949, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 31015, "s": 30986, "text": "Form validation using jQuery" }, { "code": null, "e": 31035, "s": 31015, "text": "Angular File Upload" }, { "code": null, "e": 31075, "s": 31035, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 31108, "s": 31075, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 31153, "s": 31108, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 31196, "s": 31153, "text": "How to fetch data from an API in ReactJS ?" } ]
A Multitask Music Model with BERT, Transformer-XL and Seq2Seq | by Andrew Shaw | Towards Data Science
Buzzwordy clickbait title intended, but still a simple concept. This is Part III of the “Building An A.I. Music Generator” series. I’ll be covering the basics of Multitask training with Music Models — which we’ll use to do really cool things like harmonization, melody generation, and song remixing. We’ll be building off of Part I and Part II. As you know, Transformers have recently revolutionized the NLP space. As you also probably know, there are several different transformer variations. They all have the same basic attentional layers, but some are specialized for different tasks. Here are 3 of the coolest: Seq2Seq (Sequence to Sequence Translation)— uses an encoder-decoder architecture to translate between languages. This is the OG transformer that started the revolution. TransformerXL —this forward-directional decoder is an amazing text generator. Memory and relative positional encoding enable super fast and accurate predictions. We used this model in Part II. BERT —this bi-directional encoder produced SOTA results in answering questions and filling in the blanks. Token masking and bi-directionality allows for exceptional context. Dang, all of these variations are just so cool! Instead of having to pick one, why not just combine them? Wait.. What?!? Bear with me for a second. If you are training a language model, combining all 3 models doesn’t make sense. TransformerXL is great for generating text. Seq2Seq is great for languange translations. BERT excels at filling in the blanks. No reason you’d ever want to do all three at once. Let’s look at a few scenarios when you are thinking about composing a song: Task 1. I have a couple of notes I want to make into a song TransformerXL is great at sequence generation. Let’s use it to autocomplete your song idea. Task 2a. My melody needs some harmony.Task 2b. I have a chord progression. Now I need a hook. Seq2Seq is great for translation tasks. We can use this to translate melody to chords. Or vice versa. Task 3a. I’ve got a song now, but something doesn’t sound right.Task 3b. This song needs a better rhythm. BERT is great for filling in the blanks. We can erase certain parts of the song and use BERT to generate a new variation. As you can see, each of these transformer variations can be helpful in generating song ideas. We’re going to train a model that can solve all these tasks. To understand what we’re trying to do here, it might be helpful to play around with the multitask model we’re trying to create. Each demo has been generated to solve a specific task. Toggle between the prediction (red notes) and the original (green notes) to hear the difference. Task 1. Song Generation“Canon in D” by Pachelbel Task 2a. Harmonizing the Melody“Where Is The Love” by Black Eyed Peas Task 2b. New melody with existing chord progression“Scary Monsters and Nice Sprites” by Skrillex Task 3a. Same Beat, Different Song“Levels” by Avicii Task 3b. Same Song, Remixed Beat“Fur Elise” by Beethoven You’re back. Now let’s build this thing. It might sound a little daunting at first, but it’s honestly not complicated. Our multitask model is essentially the Seq2Seq architecture. All we are doing is modifying it to train on different tasks. I’m going to assume you already know how Seq2Seq translation works. If you don’t, please visit this incredible transformer illustration. Alright, now let’s picture how a Seq2Seq Transformer might work for music. Very similar to how you would translate a language. Chords (the input language) are translated into melodies (the target language). “Previous output” is fed back into the decoder so it knows what has already been translated. The model is split into blue encoder blocks and red encoder blocks. It’s important to know the difference between the two, because we’ll be re-purposing them for our other tasks. Blue Encoder Blocks are single bi-directional attention layers. They are able to see both previous and future tokens. Red Decoder Blocks are double-stacked forward attention layers. The double-stacked blocks use both the encoder output and the “previous output” as context to predict the melody. Forward layers are unable to see the future tokens — only the previous tokens. As you might have guessed, the blue bi-directional encoders are a perfect match for training BERT models. Likewise, the forward decoder layers can be reused for training TransformerXL tasks. Let’s take a look. Erase some notes and BERT will fill in the blanks: We train the encoder to predict the correct notes (in red), whenever it sees a masked token (in blue). You’ll recognize this diagram from the previous posts. We train the decoder to predict the next token by shifting the target over by one. As you can see, the Seq2Seq model is a combination of the BERT encoder and TransformerXL decoder. This means we can reuse the encoder and decoder from the Seq2Seq model to train on the BERT and TransformerXL tasks. The only thing that changes, is the input and target. Here’s a reminder of our 3 tasks from before: Task 1. Music generation with TransformerXL Task 2a/2b. Melody-to-Chords/Chords-to-Melody translation with Seq2Seq Task 3a/3b. Song remixing with BERT Earlier you saw how to do Melody-to-Chords translation (2a.). The Chords-to-Melody task (2b.) is the exact same, but with the input and target flipped. Since BERT only uses the encoder layers and TransformerXL only uses the decoder layers, Task #1 and Task #3 can be trained at the same time. On the BERT side, we mask the input and send it through the encoder. In parallel, we’ll feed a shifted input to the decoder to train TransformerXL. Here’s what that looks like: Encoder is trained on the masked task. Separately and in parallel, the decoder is trained on the next token task. Note that the decoder only has a single arrow as input. It doesn’t use the encoder output for this task. Hopefully this model is pretty clear to those of you who’ve used PyTorch. Model architecture:Encoder - Bi-directional attention layersDecoder - Uni-directional double-stacked attention layersHead - Dense layer for token decodingForward Prop:1. If the input is masked ('msk'), train the encoder.2. If the input is shifted ('lm'), train the decoder.3. If the input contains both translation input ('enc') and previous tokens ('dec'), use both encoder and decoder. Run this notebook for actual training. It really is just an encoder/decoder model trained on various types of inputs and outputs. Masked tokens train the encoder (BERT). Shifted tokens train the decoder (TransformerXL). Paired sequences train both (Seq2Seq). If you played with the examples at the beginning of this post, then you’ve already seen the results. The musicautobot web app is powered by the multitask transformer. Rather than listening to me drone on about the results, you’ll have more fun if you head back over and generate the results for yourself! To enable Task 1, 2a, 2b, 3a, 3b, just toggle this switch: If you’re feeling more hands on, this python notebook generates all the same examples in code. You’ll get a better sense of how predictions work by running through that notebook. Woohoo! We can generate some cool results, but... it seems to be missing some of that pop music magic. In our next post, we’ll uncover some of that magic sauce. Part IV. Using a Music Bot to Remix The Chainsmokers — We’re down to my final and favorite post of the series! Special Thanks to Kenneth, Jeremy Howard, SPC and PalapaVC for support.
[ { "code": null, "e": 111, "s": 47, "text": "Buzzwordy clickbait title intended, but still a simple concept." }, { "code": null, "e": 392, "s": 111, "text": "This is Part III of the “Building An A.I. Music Generator” series. I’ll be covering the basics of Multitask training with Music Models — which we’ll use to do really cool things like harmonization, melody generation, and song remixing. We’ll be building off of Part I and Part II." }, { "code": null, "e": 663, "s": 392, "text": "As you know, Transformers have recently revolutionized the NLP space. As you also probably know, there are several different transformer variations. They all have the same basic attentional layers, but some are specialized for different tasks. Here are 3 of the coolest:" }, { "code": null, "e": 832, "s": 663, "text": "Seq2Seq (Sequence to Sequence Translation)— uses an encoder-decoder architecture to translate between languages. This is the OG transformer that started the revolution." }, { "code": null, "e": 1025, "s": 832, "text": "TransformerXL —this forward-directional decoder is an amazing text generator. Memory and relative positional encoding enable super fast and accurate predictions. We used this model in Part II." }, { "code": null, "e": 1199, "s": 1025, "text": "BERT —this bi-directional encoder produced SOTA results in answering questions and filling in the blanks. Token masking and bi-directionality allows for exceptional context." }, { "code": null, "e": 1305, "s": 1199, "text": "Dang, all of these variations are just so cool! Instead of having to pick one, why not just combine them?" }, { "code": null, "e": 1320, "s": 1305, "text": "Wait.. What?!?" }, { "code": null, "e": 1347, "s": 1320, "text": "Bear with me for a second." }, { "code": null, "e": 1428, "s": 1347, "text": "If you are training a language model, combining all 3 models doesn’t make sense." }, { "code": null, "e": 1606, "s": 1428, "text": "TransformerXL is great for generating text. Seq2Seq is great for languange translations. BERT excels at filling in the blanks. No reason you’d ever want to do all three at once." }, { "code": null, "e": 1682, "s": 1606, "text": "Let’s look at a few scenarios when you are thinking about composing a song:" }, { "code": null, "e": 1742, "s": 1682, "text": "Task 1. I have a couple of notes I want to make into a song" }, { "code": null, "e": 1834, "s": 1742, "text": "TransformerXL is great at sequence generation. Let’s use it to autocomplete your song idea." }, { "code": null, "e": 1928, "s": 1834, "text": "Task 2a. My melody needs some harmony.Task 2b. I have a chord progression. Now I need a hook." }, { "code": null, "e": 2030, "s": 1928, "text": "Seq2Seq is great for translation tasks. We can use this to translate melody to chords. Or vice versa." }, { "code": null, "e": 2136, "s": 2030, "text": "Task 3a. I’ve got a song now, but something doesn’t sound right.Task 3b. This song needs a better rhythm." }, { "code": null, "e": 2258, "s": 2136, "text": "BERT is great for filling in the blanks. We can erase certain parts of the song and use BERT to generate a new variation." }, { "code": null, "e": 2413, "s": 2258, "text": "As you can see, each of these transformer variations can be helpful in generating song ideas. We’re going to train a model that can solve all these tasks." }, { "code": null, "e": 2541, "s": 2413, "text": "To understand what we’re trying to do here, it might be helpful to play around with the multitask model we’re trying to create." }, { "code": null, "e": 2693, "s": 2541, "text": "Each demo has been generated to solve a specific task. Toggle between the prediction (red notes) and the original (green notes) to hear the difference." }, { "code": null, "e": 2742, "s": 2693, "text": "Task 1. Song Generation“Canon in D” by Pachelbel" }, { "code": null, "e": 2812, "s": 2742, "text": "Task 2a. Harmonizing the Melody“Where Is The Love” by Black Eyed Peas" }, { "code": null, "e": 2909, "s": 2812, "text": "Task 2b. New melody with existing chord progression“Scary Monsters and Nice Sprites” by Skrillex" }, { "code": null, "e": 2962, "s": 2909, "text": "Task 3a. Same Beat, Different Song“Levels” by Avicii" }, { "code": null, "e": 3019, "s": 2962, "text": "Task 3b. Same Song, Remixed Beat“Fur Elise” by Beethoven" }, { "code": null, "e": 3060, "s": 3019, "text": "You’re back. Now let’s build this thing." }, { "code": null, "e": 3261, "s": 3060, "text": "It might sound a little daunting at first, but it’s honestly not complicated. Our multitask model is essentially the Seq2Seq architecture. All we are doing is modifying it to train on different tasks." }, { "code": null, "e": 3398, "s": 3261, "text": "I’m going to assume you already know how Seq2Seq translation works. If you don’t, please visit this incredible transformer illustration." }, { "code": null, "e": 3473, "s": 3398, "text": "Alright, now let’s picture how a Seq2Seq Transformer might work for music." }, { "code": null, "e": 3605, "s": 3473, "text": "Very similar to how you would translate a language. Chords (the input language) are translated into melodies (the target language)." }, { "code": null, "e": 3698, "s": 3605, "text": "“Previous output” is fed back into the decoder so it knows what has already been translated." }, { "code": null, "e": 3877, "s": 3698, "text": "The model is split into blue encoder blocks and red encoder blocks. It’s important to know the difference between the two, because we’ll be re-purposing them for our other tasks." }, { "code": null, "e": 3995, "s": 3877, "text": "Blue Encoder Blocks are single bi-directional attention layers. They are able to see both previous and future tokens." }, { "code": null, "e": 4252, "s": 3995, "text": "Red Decoder Blocks are double-stacked forward attention layers. The double-stacked blocks use both the encoder output and the “previous output” as context to predict the melody. Forward layers are unable to see the future tokens — only the previous tokens." }, { "code": null, "e": 4443, "s": 4252, "text": "As you might have guessed, the blue bi-directional encoders are a perfect match for training BERT models. Likewise, the forward decoder layers can be reused for training TransformerXL tasks." }, { "code": null, "e": 4462, "s": 4443, "text": "Let’s take a look." }, { "code": null, "e": 4513, "s": 4462, "text": "Erase some notes and BERT will fill in the blanks:" }, { "code": null, "e": 4616, "s": 4513, "text": "We train the encoder to predict the correct notes (in red), whenever it sees a masked token (in blue)." }, { "code": null, "e": 4671, "s": 4616, "text": "You’ll recognize this diagram from the previous posts." }, { "code": null, "e": 4754, "s": 4671, "text": "We train the decoder to predict the next token by shifting the target over by one." }, { "code": null, "e": 5023, "s": 4754, "text": "As you can see, the Seq2Seq model is a combination of the BERT encoder and TransformerXL decoder. This means we can reuse the encoder and decoder from the Seq2Seq model to train on the BERT and TransformerXL tasks. The only thing that changes, is the input and target." }, { "code": null, "e": 5069, "s": 5023, "text": "Here’s a reminder of our 3 tasks from before:" }, { "code": null, "e": 5113, "s": 5069, "text": "Task 1. Music generation with TransformerXL" }, { "code": null, "e": 5184, "s": 5113, "text": "Task 2a/2b. Melody-to-Chords/Chords-to-Melody translation with Seq2Seq" }, { "code": null, "e": 5220, "s": 5184, "text": "Task 3a/3b. Song remixing with BERT" }, { "code": null, "e": 5372, "s": 5220, "text": "Earlier you saw how to do Melody-to-Chords translation (2a.). The Chords-to-Melody task (2b.) is the exact same, but with the input and target flipped." }, { "code": null, "e": 5661, "s": 5372, "text": "Since BERT only uses the encoder layers and TransformerXL only uses the decoder layers, Task #1 and Task #3 can be trained at the same time. On the BERT side, we mask the input and send it through the encoder. In parallel, we’ll feed a shifted input to the decoder to train TransformerXL." }, { "code": null, "e": 5690, "s": 5661, "text": "Here’s what that looks like:" }, { "code": null, "e": 5729, "s": 5690, "text": "Encoder is trained on the masked task." }, { "code": null, "e": 5804, "s": 5729, "text": "Separately and in parallel, the decoder is trained on the next token task." }, { "code": null, "e": 5909, "s": 5804, "text": "Note that the decoder only has a single arrow as input. It doesn’t use the encoder output for this task." }, { "code": null, "e": 5983, "s": 5909, "text": "Hopefully this model is pretty clear to those of you who’ve used PyTorch." }, { "code": null, "e": 6371, "s": 5983, "text": "Model architecture:Encoder - Bi-directional attention layersDecoder - Uni-directional double-stacked attention layersHead - Dense layer for token decodingForward Prop:1. If the input is masked ('msk'), train the encoder.2. If the input is shifted ('lm'), train the decoder.3. If the input contains both translation input ('enc') and previous tokens ('dec'), use both encoder and decoder." }, { "code": null, "e": 6410, "s": 6371, "text": "Run this notebook for actual training." }, { "code": null, "e": 6501, "s": 6410, "text": "It really is just an encoder/decoder model trained on various types of inputs and outputs." }, { "code": null, "e": 6630, "s": 6501, "text": "Masked tokens train the encoder (BERT). Shifted tokens train the decoder (TransformerXL). Paired sequences train both (Seq2Seq)." }, { "code": null, "e": 6935, "s": 6630, "text": "If you played with the examples at the beginning of this post, then you’ve already seen the results. The musicautobot web app is powered by the multitask transformer. Rather than listening to me drone on about the results, you’ll have more fun if you head back over and generate the results for yourself!" }, { "code": null, "e": 6994, "s": 6935, "text": "To enable Task 1, 2a, 2b, 3a, 3b, just toggle this switch:" }, { "code": null, "e": 7173, "s": 6994, "text": "If you’re feeling more hands on, this python notebook generates all the same examples in code. You’ll get a better sense of how predictions work by running through that notebook." }, { "code": null, "e": 7334, "s": 7173, "text": "Woohoo! We can generate some cool results, but... it seems to be missing some of that pop music magic. In our next post, we’ll uncover some of that magic sauce." }, { "code": null, "e": 7445, "s": 7334, "text": "Part IV. Using a Music Bot to Remix The Chainsmokers — We’re down to my final and favorite post of the series!" } ]
Reading Color Blindness Charts: Deep Learning and Computer Vision | by Mykyta Solonko | Towards Data Science
There are plenty of online tutorials where you can learn to train a neural network to classify handwritten digits using the MNIST dataset, or to tell the difference between cats and dogs. Us, humans, are always very good at these tasks and can easily match or beat the performance of a computer. However, there are some cases where computers can actually help humans do something that we have difficulty with. For instance, I have mild red-green color blindness. Thus, charts such as these have usually been difficult if not impossible to see: What if I could make the computer do this test for me, without me having to squint and inevitably get the question wrong either way? Well, this task seems simple. Let’s take some images, split them into training and test sets, train a convolutional neural network, and bam, we are finished. Except... there is no dataset. Online, I was able to find only 54 different images, which is not enough for a training set, given that there are 9 classes (digits 1–9). So what now? Well, we still have our good old MNIST dataset. We can use it to train a neural network that is amazing at classifying individual digits. With some OpenCV transformations, we can get our charts to look similar to MNIST, which looks like this: Let’s do it! There are many tutorials on this, but I will nonetheless give a high-level overview on how this is done. First, we will need Tensorflow installed, which is available using pip. pip install tensorflow Or if you have a GPU: pip install tensorflow-gpu Now we will create a mnist.py file and get our data: Next, we will set up our Convolutional Neural Network using one Conv2D layer, followed by MaxPooling, and Dropout. Then, our 2D output is flattened and put through a Dense layer with 128 units, followed by our classification layer with 10 classes (number 1–10). The output will be a vector of a length of 10 to indicate the prediction. For instance, a 2 will be predicted like this: [0, 0, 1, 0, 0, 0, 0, 0, 0, 0] since the 1 is in the 2nd index. Here is the code: Now, we compile the model, run it on our training data, evaluate on our test data, and save as an .h5 file in our directory: When we run this code, we get a training accuracy of about 99% and test set accuracy of: Not bad! Now, you should see a mnist.h5 file in your directory. Now, let’s move to the next step. For this part, we will need a few more libraries: pip install opencv-pythonpip install imutilspip install numpypip install sklearnpip install scikit-image We need to convert our charts to look somewhat like the MNIST dataset. At first, I thought, let’s just convert the image to grayscale. Well, then this happens: What number is that? I have no idea. As you see, color matters. We cannot just ignore it. Our goal is this: So, after hours of experimentation, here is what processing we will need to do: Increase the contrastApply median and Gaussian blurringApply K-means color clusteringConvert to grayscaleApply thresholding (this one will be tricky)More blurring and thresholdingMorphology open, close, erosionSkeletonizingDilation Increase the contrast Apply median and Gaussian blurring Apply K-means color clustering Convert to grayscale Apply thresholding (this one will be tricky) More blurring and thresholding Morphology open, close, erosion Skeletonizing Dilation Wow, that is a lot. Let’s get started. First, contrast. To be honest, I copied a function online that takes in an image and applies customized brightness and constrast transformations. I put this in a file ContrastBrightness.py and made it a class: I did not look too deeply into how this works, but on a higher level, increasing brightness adds values to the RGB channels of an image while increasing contrast multiplies the values by some constant. We will only use the contrast feature. Another complex part of our algorithm is clustering. Again, I made a file Clusterer.py and put the necessary code into it that I got online: This code will take an image and a number as an input. That number K will determine how many color clusters we will use. Now, let’s make our last file main.py. We will start with imports: Notice that we are importing the two classes that we just created. Now, please download the images in the charts directory from my Github. These have all been sorted (with the help of people without color blindness) into appropriate folders. Now, we will loop through all the images in our path and apply transformations 1–4. I commented my code pretty extensively. Here is what some of those images look like: That is an obvious improvement. The digits are all clear. Two problems remain: They do not look very hand-written and are too thickThey are not fully white on a black background They do not look very hand-written and are too thick They are not fully white on a black background So, we will threshold. However, due to the various coloring of the images, each needs a different threshold to work. We will automate the search for the perfect threshold. I noticed that a digit typically takes up 10–28% of the total image based on the number of pixels. Thus, we will try different threshold values until we reach that percent white range that we want. First, we will define a function that tells us what percent of an input image is white: Now, we will start at a threshold of 0 and works up to 255 in increments of 10 until we are in the 0.1–0.28 zone (this code goes in our for loop): Awesome! The finish is in sight. Now we get images like this (if we use the threshold we found): Most images look pretty good! However, some are problematic. It turns out that some digits are darker than the background, as you see with the 9 on the top right. Thus, thresholding makes them black, not white! The 0.1–0.28 zone is never reached. We can check if our threshold was successful by the value of the variable. If the value of the threshold variable is 260, it means that the while loop ended without finding a perfect threshold. For those images, we will have a separate procedure. Essentially, we will Invert the images to make the inside bright compared to the backgroundConvert to black and whiteCreate a circular mask to mask out the background (that went from black to white when we inverted). Invert the images to make the inside bright compared to the background Convert to black and white Create a circular mask to mask out the background (that went from black to white when we inverted). Here is the visual process: The last step is the most difficult, so I commented it in my code. Here is our whole function for this: We will adjust our code to use the new function and also do steps 6–7. These are all built-in OpenCV transformations, so nothing surprising here: Let’s see what the images look like! Awesome! Clearly recognizable. Originally, our neural network accuracy was 11% because it was choosing among the 10 possible classes randomly (remember, MNIST has 10 classes even though our chart dataset only has 9). If we stopped here, our accuracy would be about 63%, almost 6X better than random! However, we can do a little bit more. We will skeletonize and dilate our images. This will give us a consistent width and look more uniform overall. Let’s do it: As a reminder, this code is the last code we put inside the big for loop. Here is what everything looks like: Yeah, maybe a little uneven, but so is handwriting. Should be no problem for the neural network. Now, we just reshape our list, load the model, and evaluate: Put this code below your for loop. As a recap, we load our model, reshape the data, and print the accuracy after evaluating. The code may take a while to run because it takes some time for all 54 images to be transformed. After running the code, here is what gets printed for me: Let’s take a look! We got an overall accuracy of.... 78%! That is 7–8 times better than random and probably a lot better than a person with medium to severe color blindness can do. This is outstanding! If we look at our recall (ratio of correctly predicted positive observations to all observations in the actual class) for our digits, we see that we had great performance for 1–5 and 9. We had an okay performance for 8, and our neural network really struggled with 6s and 7s. This approach clearly has limitations and the transformations I listed do not work for all possible color blindness images (there is actually one image in the dataset that it does not work with after the thresholding step). Try printing all the processed 9s and you will see that the thresholding step results in a ratio between 0.1 and .28 but that is because the background becomes partly white. I did not try to find a solution for this because this only affected one image. I hope this tutorial has been informative on how a similar dataset can be used to make predictions on a different one. Also, I hope that this tutorial helps beginners become more comfortable with OpenCV, Tensorflow, and Python in general. To view the complete code and download the images and model, check out my Github. [1] Data Science Stack Exchange (2020), Link
[ { "code": null, "e": 468, "s": 172, "text": "There are plenty of online tutorials where you can learn to train a neural network to classify handwritten digits using the MNIST dataset, or to tell the difference between cats and dogs. Us, humans, are always very good at these tasks and can easily match or beat the performance of a computer." }, { "code": null, "e": 716, "s": 468, "text": "However, there are some cases where computers can actually help humans do something that we have difficulty with. For instance, I have mild red-green color blindness. Thus, charts such as these have usually been difficult if not impossible to see:" }, { "code": null, "e": 849, "s": 716, "text": "What if I could make the computer do this test for me, without me having to squint and inevitably get the question wrong either way?" }, { "code": null, "e": 1176, "s": 849, "text": "Well, this task seems simple. Let’s take some images, split them into training and test sets, train a convolutional neural network, and bam, we are finished. Except... there is no dataset. Online, I was able to find only 54 different images, which is not enough for a training set, given that there are 9 classes (digits 1–9)." }, { "code": null, "e": 1432, "s": 1176, "text": "So what now? Well, we still have our good old MNIST dataset. We can use it to train a neural network that is amazing at classifying individual digits. With some OpenCV transformations, we can get our charts to look similar to MNIST, which looks like this:" }, { "code": null, "e": 1445, "s": 1432, "text": "Let’s do it!" }, { "code": null, "e": 1550, "s": 1445, "text": "There are many tutorials on this, but I will nonetheless give a high-level overview on how this is done." }, { "code": null, "e": 1622, "s": 1550, "text": "First, we will need Tensorflow installed, which is available using pip." }, { "code": null, "e": 1645, "s": 1622, "text": "pip install tensorflow" }, { "code": null, "e": 1667, "s": 1645, "text": "Or if you have a GPU:" }, { "code": null, "e": 1694, "s": 1667, "text": "pip install tensorflow-gpu" }, { "code": null, "e": 1747, "s": 1694, "text": "Now we will create a mnist.py file and get our data:" }, { "code": null, "e": 2130, "s": 1747, "text": "Next, we will set up our Convolutional Neural Network using one Conv2D layer, followed by MaxPooling, and Dropout. Then, our 2D output is flattened and put through a Dense layer with 128 units, followed by our classification layer with 10 classes (number 1–10). The output will be a vector of a length of 10 to indicate the prediction. For instance, a 2 will be predicted like this:" }, { "code": null, "e": 2161, "s": 2130, "text": "[0, 0, 1, 0, 0, 0, 0, 0, 0, 0]" }, { "code": null, "e": 2212, "s": 2161, "text": "since the 1 is in the 2nd index. Here is the code:" }, { "code": null, "e": 2337, "s": 2212, "text": "Now, we compile the model, run it on our training data, evaluate on our test data, and save as an .h5 file in our directory:" }, { "code": null, "e": 2426, "s": 2337, "text": "When we run this code, we get a training accuracy of about 99% and test set accuracy of:" }, { "code": null, "e": 2524, "s": 2426, "text": "Not bad! Now, you should see a mnist.h5 file in your directory. Now, let’s move to the next step." }, { "code": null, "e": 2574, "s": 2524, "text": "For this part, we will need a few more libraries:" }, { "code": null, "e": 2679, "s": 2574, "text": "pip install opencv-pythonpip install imutilspip install numpypip install sklearnpip install scikit-image" }, { "code": null, "e": 2839, "s": 2679, "text": "We need to convert our charts to look somewhat like the MNIST dataset. At first, I thought, let’s just convert the image to grayscale. Well, then this happens:" }, { "code": null, "e": 2947, "s": 2839, "text": "What number is that? I have no idea. As you see, color matters. We cannot just ignore it. Our goal is this:" }, { "code": null, "e": 3027, "s": 2947, "text": "So, after hours of experimentation, here is what processing we will need to do:" }, { "code": null, "e": 3259, "s": 3027, "text": "Increase the contrastApply median and Gaussian blurringApply K-means color clusteringConvert to grayscaleApply thresholding (this one will be tricky)More blurring and thresholdingMorphology open, close, erosionSkeletonizingDilation" }, { "code": null, "e": 3281, "s": 3259, "text": "Increase the contrast" }, { "code": null, "e": 3316, "s": 3281, "text": "Apply median and Gaussian blurring" }, { "code": null, "e": 3347, "s": 3316, "text": "Apply K-means color clustering" }, { "code": null, "e": 3368, "s": 3347, "text": "Convert to grayscale" }, { "code": null, "e": 3413, "s": 3368, "text": "Apply thresholding (this one will be tricky)" }, { "code": null, "e": 3444, "s": 3413, "text": "More blurring and thresholding" }, { "code": null, "e": 3476, "s": 3444, "text": "Morphology open, close, erosion" }, { "code": null, "e": 3490, "s": 3476, "text": "Skeletonizing" }, { "code": null, "e": 3499, "s": 3490, "text": "Dilation" }, { "code": null, "e": 3748, "s": 3499, "text": "Wow, that is a lot. Let’s get started. First, contrast. To be honest, I copied a function online that takes in an image and applies customized brightness and constrast transformations. I put this in a file ContrastBrightness.py and made it a class:" }, { "code": null, "e": 3989, "s": 3748, "text": "I did not look too deeply into how this works, but on a higher level, increasing brightness adds values to the RGB channels of an image while increasing contrast multiplies the values by some constant. We will only use the contrast feature." }, { "code": null, "e": 4130, "s": 3989, "text": "Another complex part of our algorithm is clustering. Again, I made a file Clusterer.py and put the necessary code into it that I got online:" }, { "code": null, "e": 4318, "s": 4130, "text": "This code will take an image and a number as an input. That number K will determine how many color clusters we will use. Now, let’s make our last file main.py. We will start with imports:" }, { "code": null, "e": 4457, "s": 4318, "text": "Notice that we are importing the two classes that we just created. Now, please download the images in the charts directory from my Github." }, { "code": null, "e": 4560, "s": 4457, "text": "These have all been sorted (with the help of people without color blindness) into appropriate folders." }, { "code": null, "e": 4684, "s": 4560, "text": "Now, we will loop through all the images in our path and apply transformations 1–4. I commented my code pretty extensively." }, { "code": null, "e": 4729, "s": 4684, "text": "Here is what some of those images look like:" }, { "code": null, "e": 4808, "s": 4729, "text": "That is an obvious improvement. The digits are all clear. Two problems remain:" }, { "code": null, "e": 4907, "s": 4808, "text": "They do not look very hand-written and are too thickThey are not fully white on a black background" }, { "code": null, "e": 4960, "s": 4907, "text": "They do not look very hand-written and are too thick" }, { "code": null, "e": 5007, "s": 4960, "text": "They are not fully white on a black background" }, { "code": null, "e": 5278, "s": 5007, "text": "So, we will threshold. However, due to the various coloring of the images, each needs a different threshold to work. We will automate the search for the perfect threshold. I noticed that a digit typically takes up 10–28% of the total image based on the number of pixels." }, { "code": null, "e": 5465, "s": 5278, "text": "Thus, we will try different threshold values until we reach that percent white range that we want. First, we will define a function that tells us what percent of an input image is white:" }, { "code": null, "e": 5612, "s": 5465, "text": "Now, we will start at a threshold of 0 and works up to 255 in increments of 10 until we are in the 0.1–0.28 zone (this code goes in our for loop):" }, { "code": null, "e": 5709, "s": 5612, "text": "Awesome! The finish is in sight. Now we get images like this (if we use the threshold we found):" }, { "code": null, "e": 5956, "s": 5709, "text": "Most images look pretty good! However, some are problematic. It turns out that some digits are darker than the background, as you see with the 9 on the top right. Thus, thresholding makes them black, not white! The 0.1–0.28 zone is never reached." }, { "code": null, "e": 6203, "s": 5956, "text": "We can check if our threshold was successful by the value of the variable. If the value of the threshold variable is 260, it means that the while loop ended without finding a perfect threshold. For those images, we will have a separate procedure." }, { "code": null, "e": 6224, "s": 6203, "text": "Essentially, we will" }, { "code": null, "e": 6420, "s": 6224, "text": "Invert the images to make the inside bright compared to the backgroundConvert to black and whiteCreate a circular mask to mask out the background (that went from black to white when we inverted)." }, { "code": null, "e": 6491, "s": 6420, "text": "Invert the images to make the inside bright compared to the background" }, { "code": null, "e": 6518, "s": 6491, "text": "Convert to black and white" }, { "code": null, "e": 6618, "s": 6518, "text": "Create a circular mask to mask out the background (that went from black to white when we inverted)." }, { "code": null, "e": 6646, "s": 6618, "text": "Here is the visual process:" }, { "code": null, "e": 6750, "s": 6646, "text": "The last step is the most difficult, so I commented it in my code. Here is our whole function for this:" }, { "code": null, "e": 6896, "s": 6750, "text": "We will adjust our code to use the new function and also do steps 6–7. These are all built-in OpenCV transformations, so nothing surprising here:" }, { "code": null, "e": 6933, "s": 6896, "text": "Let’s see what the images look like!" }, { "code": null, "e": 7271, "s": 6933, "text": "Awesome! Clearly recognizable. Originally, our neural network accuracy was 11% because it was choosing among the 10 possible classes randomly (remember, MNIST has 10 classes even though our chart dataset only has 9). If we stopped here, our accuracy would be about 63%, almost 6X better than random! However, we can do a little bit more." }, { "code": null, "e": 7395, "s": 7271, "text": "We will skeletonize and dilate our images. This will give us a consistent width and look more uniform overall. Let’s do it:" }, { "code": null, "e": 7505, "s": 7395, "text": "As a reminder, this code is the last code we put inside the big for loop. Here is what everything looks like:" }, { "code": null, "e": 7663, "s": 7505, "text": "Yeah, maybe a little uneven, but so is handwriting. Should be no problem for the neural network. Now, we just reshape our list, load the model, and evaluate:" }, { "code": null, "e": 7885, "s": 7663, "text": "Put this code below your for loop. As a recap, we load our model, reshape the data, and print the accuracy after evaluating. The code may take a while to run because it takes some time for all 54 images to be transformed." }, { "code": null, "e": 7943, "s": 7885, "text": "After running the code, here is what gets printed for me:" }, { "code": null, "e": 8145, "s": 7943, "text": "Let’s take a look! We got an overall accuracy of.... 78%! That is 7–8 times better than random and probably a lot better than a person with medium to severe color blindness can do. This is outstanding!" }, { "code": null, "e": 8421, "s": 8145, "text": "If we look at our recall (ratio of correctly predicted positive observations to all observations in the actual class) for our digits, we see that we had great performance for 1–5 and 9. We had an okay performance for 8, and our neural network really struggled with 6s and 7s." }, { "code": null, "e": 8899, "s": 8421, "text": "This approach clearly has limitations and the transformations I listed do not work for all possible color blindness images (there is actually one image in the dataset that it does not work with after the thresholding step). Try printing all the processed 9s and you will see that the thresholding step results in a ratio between 0.1 and .28 but that is because the background becomes partly white. I did not try to find a solution for this because this only affected one image." }, { "code": null, "e": 9138, "s": 8899, "text": "I hope this tutorial has been informative on how a similar dataset can be used to make predictions on a different one. Also, I hope that this tutorial helps beginners become more comfortable with OpenCV, Tensorflow, and Python in general." }, { "code": null, "e": 9220, "s": 9138, "text": "To view the complete code and download the images and model, check out my Github." } ]
Node.js HTTP Module
08 Oct, 2021 To make HTTP requests in Node.js, there is a built-in module HTTP in Node.js to transfer data over the HTTP. To use the HTTP server in node, we need to require the HTTP module. The HTTP module creates an HTTP server that listens to server ports and gives a response back to the client. Syntax: var http = require('http'); We can create a HTTP server with the help of http.createServer() method. Example 1:Filename: max.js var http = require('http'); // Create a serverhttp.createServer((request, response)=>{ // Sends a chunk of the response body response.write('Hello World!'); // Signals the server that all of // the response headers and body // have been sent response.end();}).listen(3000); // Server listening on port 3000 Step to run this program: Run this max.js file using the below command: node max.js Output: To make requests via the HTTP module http.request() method is used. Syntax: http.request(options[, callback]) Example 2:Filename: max.js var http = require('http'); var options = { host: 'www.geeksforgeeks.org', path: '/courses', method: 'GET'}; // Making a get request to // 'www.geeksforgeeks.org'http.request(options, (response) => { // Printing the statusCode console.log(`STATUS: ${response.statusCode}`);}).end(); Step to run this program: Run this max.js file using the below command: node max.js Output: Node.js-Basics Picked Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to update Node.js and NPM to next version ? Node.js fs.readFileSync() Method Node.js fs.writeFile() Method How to update NPM ? Difference between promise and async await in Node.js 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 ? Differences between Functional Components and Class Components in React
[ { "code": null, "e": 52, "s": 24, "text": "\n08 Oct, 2021" }, { "code": null, "e": 338, "s": 52, "text": "To make HTTP requests in Node.js, there is a built-in module HTTP in Node.js to transfer data over the HTTP. To use the HTTP server in node, we need to require the HTTP module. The HTTP module creates an HTTP server that listens to server ports and gives a response back to the client." }, { "code": null, "e": 346, "s": 338, "text": "Syntax:" }, { "code": null, "e": 374, "s": 346, "text": "var http = require('http');" }, { "code": null, "e": 447, "s": 374, "text": "We can create a HTTP server with the help of http.createServer() method." }, { "code": null, "e": 474, "s": 447, "text": "Example 1:Filename: max.js" }, { "code": "var http = require('http'); // Create a serverhttp.createServer((request, response)=>{ // Sends a chunk of the response body response.write('Hello World!'); // Signals the server that all of // the response headers and body // have been sent response.end();}).listen(3000); // Server listening on port 3000", "e": 806, "s": 474, "text": null }, { "code": null, "e": 878, "s": 806, "text": "Step to run this program: Run this max.js file using the below command:" }, { "code": null, "e": 890, "s": 878, "text": "node max.js" }, { "code": null, "e": 898, "s": 890, "text": "Output:" }, { "code": null, "e": 966, "s": 898, "text": "To make requests via the HTTP module http.request() method is used." }, { "code": null, "e": 974, "s": 966, "text": "Syntax:" }, { "code": null, "e": 1008, "s": 974, "text": "http.request(options[, callback])" }, { "code": null, "e": 1035, "s": 1008, "text": "Example 2:Filename: max.js" }, { "code": "var http = require('http'); var options = { host: 'www.geeksforgeeks.org', path: '/courses', method: 'GET'}; // Making a get request to // 'www.geeksforgeeks.org'http.request(options, (response) => { // Printing the statusCode console.log(`STATUS: ${response.statusCode}`);}).end();", "e": 1337, "s": 1035, "text": null }, { "code": null, "e": 1409, "s": 1337, "text": "Step to run this program: Run this max.js file using the below command:" }, { "code": null, "e": 1421, "s": 1409, "text": "node max.js" }, { "code": null, "e": 1429, "s": 1421, "text": "Output:" }, { "code": null, "e": 1444, "s": 1429, "text": "Node.js-Basics" }, { "code": null, "e": 1451, "s": 1444, "text": "Picked" }, { "code": null, "e": 1459, "s": 1451, "text": "Node.js" }, { "code": null, "e": 1476, "s": 1459, "text": "Web Technologies" }, { "code": null, "e": 1574, "s": 1476, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1622, "s": 1574, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 1655, "s": 1622, "text": "Node.js fs.readFileSync() Method" }, { "code": null, "e": 1685, "s": 1655, "text": "Node.js fs.writeFile() Method" }, { "code": null, "e": 1705, "s": 1685, "text": "How to update NPM ?" }, { "code": null, "e": 1759, "s": 1705, "text": "Difference between promise and async await in Node.js" }, { "code": null, "e": 1821, "s": 1759, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 1882, "s": 1821, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 1932, "s": 1882, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 1975, "s": 1932, "text": "How to fetch data from an API in ReactJS ?" } ]
Output of the Program | Pointer to a Constant or Constant Pointer?
21 Jun, 2022 Predict the output of the below program. C++ C #include <iostream>using namespace std; int main(){ int x = 5; int * const ptr = &x; ++(*ptr); cout << x; return 0;} // This code is contributed by sarajadhav12052009 #include <stdio.h> int main(){ int x = 5; int * const ptr = &x; ++(*ptr); printf("%d", x); getchar(); return 0; } 6 Explanation: See following declarations to know the difference between constant pointer and a pointer to a constant. int * const ptr —> ptr is constant pointer. You can change the value at the location pointed by pointer p, but you can not change p to point to other location.int const * ptr —> ptr is a pointer to a constant. You can change ptr to point other variable. But you cannot change the value pointed by ptr.Therefore above program works well because we have a constant pointer and we are not changing ptr to point to any other location. We are only incrementing value pointed by ptr.Try below program, you will get compiler error. C++ C #include <iostream>using namespace std; int main(){ int x = 5; int const * ptr = &x; ++(*ptr); cout << x; return 0;} // This code is contributed by sarajadhav12052009 int main(){ int x = 5; int const * ptr = &x; ++(*ptr); printf("%d", x); getchar(); return 0; } varshagumber28 nikhatkhan11 sarajadhav12052009 C-Output Program Output Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Runtime Errors Output of C Programs | Set 2 Different ways to copy a string in C/C++ Output of C Programs | Set 3 Output of C++ Program | Set 1 Output of Python Program | Set 1 Output of Java Program | Set 2 Output of Java Program | Set 3 Output of C++ programs | Set 47 (Pointers) Output of Java Programs | Set 12
[ { "code": null, "e": 52, "s": 24, "text": "\n21 Jun, 2022" }, { "code": null, "e": 94, "s": 52, "text": "Predict the output of the below program. " }, { "code": null, "e": 98, "s": 94, "text": "C++" }, { "code": null, "e": 100, "s": 98, "text": "C" }, { "code": "#include <iostream>using namespace std; int main(){ int x = 5; int * const ptr = &x; ++(*ptr); cout << x; return 0;} // This code is contributed by sarajadhav12052009", "e": 285, "s": 100, "text": null }, { "code": "#include <stdio.h> int main(){ int x = 5; int * const ptr = &x; ++(*ptr); printf(\"%d\", x); getchar(); return 0; }", "e": 426, "s": 285, "text": null }, { "code": null, "e": 428, "s": 426, "text": "6" }, { "code": null, "e": 1072, "s": 428, "text": "Explanation: See following declarations to know the difference between constant pointer and a pointer to a constant. int * const ptr —> ptr is constant pointer. You can change the value at the location pointed by pointer p, but you can not change p to point to other location.int const * ptr —> ptr is a pointer to a constant. You can change ptr to point other variable. But you cannot change the value pointed by ptr.Therefore above program works well because we have a constant pointer and we are not changing ptr to point to any other location. We are only incrementing value pointed by ptr.Try below program, you will get compiler error. " }, { "code": null, "e": 1076, "s": 1072, "text": "C++" }, { "code": null, "e": 1078, "s": 1076, "text": "C" }, { "code": "#include <iostream>using namespace std; int main(){ int x = 5; int const * ptr = &x; ++(*ptr); cout << x; return 0;} // This code is contributed by sarajadhav12052009", "e": 1267, "s": 1078, "text": null }, { "code": "int main(){ int x = 5; int const * ptr = &x; ++(*ptr); printf(\"%d\", x); getchar(); return 0; }", "e": 1387, "s": 1267, "text": null }, { "code": null, "e": 1402, "s": 1387, "text": "varshagumber28" }, { "code": null, "e": 1415, "s": 1402, "text": "nikhatkhan11" }, { "code": null, "e": 1434, "s": 1415, "text": "sarajadhav12052009" }, { "code": null, "e": 1443, "s": 1434, "text": "C-Output" }, { "code": null, "e": 1458, "s": 1443, "text": "Program Output" }, { "code": null, "e": 1556, "s": 1458, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1571, "s": 1556, "text": "Runtime Errors" }, { "code": null, "e": 1600, "s": 1571, "text": "Output of C Programs | Set 2" }, { "code": null, "e": 1641, "s": 1600, "text": "Different ways to copy a string in C/C++" }, { "code": null, "e": 1670, "s": 1641, "text": "Output of C Programs | Set 3" }, { "code": null, "e": 1700, "s": 1670, "text": "Output of C++ Program | Set 1" }, { "code": null, "e": 1733, "s": 1700, "text": "Output of Python Program | Set 1" }, { "code": null, "e": 1764, "s": 1733, "text": "Output of Java Program | Set 2" }, { "code": null, "e": 1795, "s": 1764, "text": "Output of Java Program | Set 3" }, { "code": null, "e": 1838, "s": 1795, "text": "Output of C++ programs | Set 47 (Pointers)" } ]
How to generate random colors by using React hooks ?
29 Oct, 2021 We are going to make a react custom hook for generating random colors. Pre-requisite: React.js React Hooks Approach: Basically, if we are familiar with React , then we all have already used react custom hooks(like useState, useEffect , useContext etc.). We can also make our custom react hooks and can use it wherever we want. So there’s a small code for generating random colors. Here we will be making a random color generator custom hook (in our custom hook file), here we will make a function for changing color called (generateColor) , and we will be passing color and generate color as return. Then we will use this in our App.js by destructuring and will use that generate color as an onClick event function for a button through which we will change the color of our window. Creating react application: Step 1: Go to your command prompt and write the below command to create a react app. npx create-react-app <YOUR_APP_NAME> Step 2: Then go to your app folder by typing the below command cd <YOUR_APP_NAME> Project Structure: Our folder structure should be like this. Folder structure Step 3: Make a separate file useGenerateRandomColor.js in your src folder and use the below code : useGenerateRandomColor.js import {useState} from 'react'; const useGenerateRandomColor = () => { const [color,setColor] = useState("") const generateColor = () =>{ setColor(Math.random().toString(16).substr(-6)); }; return {color,generateColor}; };export default useGenerateRandomColor; Step 4: Now go to src/App.js and paste the below code to use our random color generator custom hook. App.js import "./App.css";import useGenerateRandomColor from "./useGenerateRandomColor"; function App() { const { color, generateColor } = useGenerateRandomColor(); return ( <div style={{ height: "100vh", width: "100vw", backgroundColor: "#" + color, display: "flex", justifyContent: "center", alignItems: "center", }} > <button style={{ padding: "40px", borderRadius: "10px", backgroundImage: "linear-gradient(to top, #a8edea 0%, #fed6e3 100%)", fontSize: "larger", }} onClick={generateColor} > Generate random color </button> </div> );} export default App; Now we are good to go with our react app . Step to run the application: Run the following command to start your app in your localhost:3000. npm start Output: React-Hooks React-Questions ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Oct, 2021" }, { "code": null, "e": 99, "s": 28, "text": "We are going to make a react custom hook for generating random colors." }, { "code": null, "e": 114, "s": 99, "text": "Pre-requisite:" }, { "code": null, "e": 123, "s": 114, "text": "React.js" }, { "code": null, "e": 135, "s": 123, "text": "React Hooks" }, { "code": null, "e": 810, "s": 135, "text": "Approach: Basically, if we are familiar with React , then we all have already used react custom hooks(like useState, useEffect , useContext etc.). We can also make our custom react hooks and can use it wherever we want. So there’s a small code for generating random colors. Here we will be making a random color generator custom hook (in our custom hook file), here we will make a function for changing color called (generateColor) , and we will be passing color and generate color as return. Then we will use this in our App.js by destructuring and will use that generate color as an onClick event function for a button through which we will change the color of our window." }, { "code": null, "e": 838, "s": 810, "text": "Creating react application:" }, { "code": null, "e": 923, "s": 838, "text": "Step 1: Go to your command prompt and write the below command to create a react app." }, { "code": null, "e": 960, "s": 923, "text": "npx create-react-app <YOUR_APP_NAME>" }, { "code": null, "e": 1023, "s": 960, "text": "Step 2: Then go to your app folder by typing the below command" }, { "code": null, "e": 1042, "s": 1023, "text": "cd <YOUR_APP_NAME>" }, { "code": null, "e": 1103, "s": 1042, "text": "Project Structure: Our folder structure should be like this." }, { "code": null, "e": 1120, "s": 1103, "text": "Folder structure" }, { "code": null, "e": 1219, "s": 1120, "text": "Step 3: Make a separate file useGenerateRandomColor.js in your src folder and use the below code :" }, { "code": null, "e": 1245, "s": 1219, "text": "useGenerateRandomColor.js" }, { "code": "import {useState} from 'react'; const useGenerateRandomColor = () => { const [color,setColor] = useState(\"\") const generateColor = () =>{ setColor(Math.random().toString(16).substr(-6)); }; return {color,generateColor}; };export default useGenerateRandomColor;", "e": 1531, "s": 1245, "text": null }, { "code": null, "e": 1632, "s": 1531, "text": "Step 4: Now go to src/App.js and paste the below code to use our random color generator custom hook." }, { "code": null, "e": 1639, "s": 1632, "text": "App.js" }, { "code": "import \"./App.css\";import useGenerateRandomColor from \"./useGenerateRandomColor\"; function App() { const { color, generateColor } = useGenerateRandomColor(); return ( <div style={{ height: \"100vh\", width: \"100vw\", backgroundColor: \"#\" + color, display: \"flex\", justifyContent: \"center\", alignItems: \"center\", }} > <button style={{ padding: \"40px\", borderRadius: \"10px\", backgroundImage: \"linear-gradient(to top, #a8edea 0%, #fed6e3 100%)\", fontSize: \"larger\", }} onClick={generateColor} > Generate random color </button> </div> );} export default App;", "e": 2352, "s": 1639, "text": null }, { "code": null, "e": 2395, "s": 2352, "text": "Now we are good to go with our react app ." }, { "code": null, "e": 2492, "s": 2395, "text": "Step to run the application: Run the following command to start your app in your localhost:3000." }, { "code": null, "e": 2502, "s": 2492, "text": "npm start" }, { "code": null, "e": 2510, "s": 2502, "text": "Output:" }, { "code": null, "e": 2522, "s": 2510, "text": "React-Hooks" }, { "code": null, "e": 2538, "s": 2522, "text": "React-Questions" }, { "code": null, "e": 2546, "s": 2538, "text": "ReactJS" }, { "code": null, "e": 2563, "s": 2546, "text": "Web Technologies" } ]
Design DFA in LEX Code that accepts the string having even binary number over input alphabet {0,1}
31 Jul, 2021 Problem Overview – Design a DFA in LEX Code that accepts the string having even binary number over input alphabet {0,1}. Example – Input : 1010 Output: Accepted Input : 1001 Output: Not Accepted Input: 23ab Output:Invalid Input:ab345 Output:Invalid Input:010101 Output:Not Accepted Approach :LEX provides us with an INITIAL state by default. So to make a DFA, use this as the initial state of the DFA. We define two more states: A, and DEAD, where the DEAD state would be used if encountering a wrong or invalid input. When the user inputs an invalid character, move to DEAD state, and then print “Invalid”. If the input string ends at A then display the message “Accepted”. Else if the input string ends at state INITIAL then displays the message “Not Accepted”. Note –To compile the lex program we need to have a Unix system that has flex installed into it. Then we need to save the file with the .l extension.For example- filename.lThen after saving the program closes the lex file and then open the terminal and write the following commands as follows. lex filename.l cc lex.yy.c ./a.out LEX CODE : %{ %} %s A DEAD %% <INITIAL>0 BEGIN A; <INITIAL>1 BEGIN INITIAL; <INITIAL>[^01\n] BEGIN DEAD; <INITIAL>\n BEGIN INITIAL; {printf("Not Accepted\n");} <A>0 BEGIN A; <A>1 BEGIN INITIAL; <A>[^01\n] BEGIN DEAD; <A>\n BEGIN INITIAL; {printf("Accepted\n");} <DEAD>[^\n] BEGIN DEAD; <DEAD>\n BEGIN INITIAL; {printf("Invalid\n");} %% int yywrap() { return 1; } int main() { printf("Enter String\n"); yylex(); return 0; } Output : Enter String 1100 Accepted 1010 Accepted 0001 Not Accepted abc Invalid 0101 Not Accepted DFA Theory of Computation & Automata Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Boyer-Moore Majority Voting Algorithm Variation of Turing Machine Decidable and Undecidable problems in Theory of Computation Halting Problem in Theory of Computation Post Correspondence Problem NPDA for accepting the language L = {wwR | w ∈ (a,b)*} Pushdown Automata Acceptance by Final State Undecidability and Reducibility in TOC Program to construct a DFA which accept the language L = {anbm | n mod 2=0, m≥1} Arden's Theorem in Theory of Computation
[ { "code": null, "e": 52, "s": 24, "text": "\n31 Jul, 2021" }, { "code": null, "e": 174, "s": 52, "text": "Problem Overview – Design a DFA in LEX Code that accepts the string having even binary number over input alphabet {0,1}." }, { "code": null, "e": 185, "s": 174, "text": "Example – " }, { "code": null, "e": 340, "s": 185, "text": "Input : 1010\nOutput: Accepted\n\nInput : 1001\nOutput: Not Accepted\n\nInput: 23ab\nOutput:Invalid\n\nInput:ab345\nOutput:Invalid\n\nInput:010101\nOutput:Not Accepted" }, { "code": null, "e": 822, "s": 340, "text": "Approach :LEX provides us with an INITIAL state by default. So to make a DFA, use this as the initial state of the DFA. We define two more states: A, and DEAD, where the DEAD state would be used if encountering a wrong or invalid input. When the user inputs an invalid character, move to DEAD state, and then print “Invalid”. If the input string ends at A then display the message “Accepted”. Else if the input string ends at state INITIAL then displays the message “Not Accepted”." }, { "code": null, "e": 1115, "s": 822, "text": "Note –To compile the lex program we need to have a Unix system that has flex installed into it. Then we need to save the file with the .l extension.For example- filename.lThen after saving the program closes the lex file and then open the terminal and write the following commands as follows." }, { "code": null, "e": 1150, "s": 1115, "text": "lex filename.l\ncc lex.yy.c\n./a.out" }, { "code": null, "e": 1161, "s": 1150, "text": "LEX CODE :" }, { "code": null, "e": 1604, "s": 1161, "text": "%{\n%}\n \n%s A DEAD\n \n%%\n<INITIAL>0 BEGIN A;\n<INITIAL>1 BEGIN INITIAL;\n<INITIAL>[^01\\n] BEGIN DEAD;\n<INITIAL>\\n BEGIN INITIAL; {printf(\"Not Accepted\\n\");}\n \n<A>0 BEGIN A;\n<A>1 BEGIN INITIAL;\n<A>[^01\\n] BEGIN DEAD;\n<A>\\n BEGIN INITIAL; {printf(\"Accepted\\n\");}\n \n<DEAD>[^\\n] BEGIN DEAD;\n<DEAD>\\n BEGIN INITIAL; {printf(\"Invalid\\n\");} \n \n%%\n\nint yywrap()\n{\n return 1;\n} \nint main()\n{\n printf(\"Enter String\\n\");\n yylex();\nreturn 0;\n}" }, { "code": null, "e": 1613, "s": 1604, "text": "Output :" }, { "code": null, "e": 1702, "s": 1613, "text": "Enter String\n1100\nAccepted\n1010\nAccepted\n0001\nNot Accepted\nabc\nInvalid\n0101\nNot Accepted" }, { "code": null, "e": 1706, "s": 1702, "text": "DFA" }, { "code": null, "e": 1739, "s": 1706, "text": "Theory of Computation & Automata" }, { "code": null, "e": 1837, "s": 1739, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1875, "s": 1837, "text": "Boyer-Moore Majority Voting Algorithm" }, { "code": null, "e": 1903, "s": 1875, "text": "Variation of Turing Machine" }, { "code": null, "e": 1963, "s": 1903, "text": "Decidable and Undecidable problems in Theory of Computation" }, { "code": null, "e": 2004, "s": 1963, "text": "Halting Problem in Theory of Computation" }, { "code": null, "e": 2032, "s": 2004, "text": "Post Correspondence Problem" }, { "code": null, "e": 2087, "s": 2032, "text": "NPDA for accepting the language L = {wwR | w ∈ (a,b)*}" }, { "code": null, "e": 2131, "s": 2087, "text": "Pushdown Automata Acceptance by Final State" }, { "code": null, "e": 2170, "s": 2131, "text": "Undecidability and Reducibility in TOC" }, { "code": null, "e": 2251, "s": 2170, "text": "Program to construct a DFA which accept the language L = {anbm | n mod 2=0, m≥1}" } ]
Widgets in ipython – Numeric Widgets
06 Jul, 2021 Widgets in ipython are GUI based interaction tools provided within the ipython interpreter console. It helps to interact with different components by real-time changing the value of integers based on the widget used. To install it, use the following command in jupyter notebook. !pip install ipywidgets The ipywidgets are modules in python to use widget within the jupyter cells. There are many types of widgets provided under this liberality. In ML most of the time it is used to understand the importance of the features within the model and thus choose only the best ones. There are many widgets distributed with ipywidgets that are designed to display numeric values. Widgets exist for displaying integers and floats, both bounded and unbounded. The integer widgets share a similar scheme to their other numeric counterparts. By replacing float with int in the widget name, the Integer equivalent is achieved. To understand the effect of change in the result due to variation in some input values, Numeric widget is the best solution for that. To use the slider for specific to integers only, IntSlider is provided. Some important options in IntSlider value : It is displays value with an initial value.min: The lower bound is defined by min within the IntSlider.max: The upper bound is defined by max within the IntSlider.step: The values are incremented according to the step parameter.description: This parameter defines the label of the slider.orientation: The slider’s can be ‘horizontal’ or ‘vertical’.It is horizontal by default.readout: This displays the current value of the slider next to it. value : It is displays value with an initial value. min: The lower bound is defined by min within the IntSlider. max: The upper bound is defined by max within the IntSlider. step: The values are incremented according to the step parameter. description: This parameter defines the label of the slider. orientation: The slider’s can be ‘horizontal’ or ‘vertical’.It is horizontal by default. readout: This displays the current value of the slider next to it. Example: Python3 import ipywidgets as wdg # Real time interactive square calculationwdg.interact(lambda x:x**2, x = wdg.IntSlider(min = 0, max = 10, value = 1)) Output: Output The interact() method is used to return the value of the callable in coupling with the sliders. It is real time in nature. The slide in slider will change the value. Like IntSlider, there is a class for float slider which is used to handle the float changes in real time. It is same as IntSlider but it has feature to take steps in float values. Example: Python3 import ipywidgets as widgetswidgets.interact(lambda x:x**2, x = widgets.FloatSlider(min = 0, step =.25, max = 10, value = 1)) Output: Output The FloatLogSlider has a log scale, which makes it easy to have a slider that covers a wide range of positive magnitudes. It is generally show to demonstrate the cost values in the machine learning algorithms. In this the min and max refer to the minimum and maximum exponents of the base, and the value refers to the actual value of the slider. The base parameter allows to alter the log base in the slider. Example: Python3 import ipywidgets as widgetswidgets.interact(lambda x:x, x = widgets.FloatLogSlider(description ="$e ^ x$", min = 0, step = 1, base = 5, max = 10, value = 1)) Output: Output It is the widget used to set a range as an interactive component. It sets a tuple with 2 values the start and the stop values. The Syntax difference with respect to IntSlide is only for the value option. Example: Python3 import ipywidgets as widgetswidgets.interact(lambda x :x, x = widgets.IntRangeSlider(min = 0, step = 1, max = 10, value =[1, 2])) Output: Output It is the widget used to set a range as an interactive component. It sets a tuple with 2 values the start and the stop values. The Syntax difference with respect to FloatSlide is only for the value option. Example: Python3 import ipywidgets as widgetswidgets.interact(lambda x :x, x = widgets.FloatRangeSlider(min = 0, step =.25, max = 10, value =[1, 2])) Output: Output varshagumber28 Python-gui Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Different ways to create Pandas Dataframe Enumerate() in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python Program for Fibonacci numbers Python | Split string into list of characters
[ { "code": null, "e": 28, "s": 0, "text": "\n06 Jul, 2021" }, { "code": null, "e": 307, "s": 28, "text": "Widgets in ipython are GUI based interaction tools provided within the ipython interpreter console. It helps to interact with different components by real-time changing the value of integers based on the widget used. To install it, use the following command in jupyter notebook." }, { "code": null, "e": 331, "s": 307, "text": "!pip install ipywidgets" }, { "code": null, "e": 605, "s": 331, "text": "The ipywidgets are modules in python to use widget within the jupyter cells. There are many types of widgets provided under this liberality. In ML most of the time it is used to understand the importance of the features within the model and thus choose only the best ones. " }, { "code": null, "e": 1077, "s": 605, "text": "There are many widgets distributed with ipywidgets that are designed to display numeric values. Widgets exist for displaying integers and floats, both bounded and unbounded. The integer widgets share a similar scheme to their other numeric counterparts. By replacing float with int in the widget name, the Integer equivalent is achieved. To understand the effect of change in the result due to variation in some input values, Numeric widget is the best solution for that." }, { "code": null, "e": 1149, "s": 1077, "text": "To use the slider for specific to integers only, IntSlider is provided." }, { "code": null, "e": 1187, "s": 1149, "text": "Some important options in IntSlider " }, { "code": null, "e": 1640, "s": 1187, "text": "value : It is displays value with an initial value.min: The lower bound is defined by min within the IntSlider.max: The upper bound is defined by max within the IntSlider.step: The values are incremented according to the step parameter.description: This parameter defines the label of the slider.orientation: The slider’s can be ‘horizontal’ or ‘vertical’.It is horizontal by default.readout: This displays the current value of the slider next to it." }, { "code": null, "e": 1692, "s": 1640, "text": "value : It is displays value with an initial value." }, { "code": null, "e": 1753, "s": 1692, "text": "min: The lower bound is defined by min within the IntSlider." }, { "code": null, "e": 1814, "s": 1753, "text": "max: The upper bound is defined by max within the IntSlider." }, { "code": null, "e": 1880, "s": 1814, "text": "step: The values are incremented according to the step parameter." }, { "code": null, "e": 1942, "s": 1880, "text": "description: This parameter defines the label of the slider." }, { "code": null, "e": 2032, "s": 1942, "text": "orientation: The slider’s can be ‘horizontal’ or ‘vertical’.It is horizontal by default." }, { "code": null, "e": 2099, "s": 2032, "text": "readout: This displays the current value of the slider next to it." }, { "code": null, "e": 2108, "s": 2099, "text": "Example:" }, { "code": null, "e": 2116, "s": 2108, "text": "Python3" }, { "code": "import ipywidgets as wdg # Real time interactive square calculationwdg.interact(lambda x:x**2, x = wdg.IntSlider(min = 0, max = 10, value = 1))", "e": 2260, "s": 2116, "text": null }, { "code": null, "e": 2268, "s": 2260, "text": "Output:" }, { "code": null, "e": 2275, "s": 2268, "text": "Output" }, { "code": null, "e": 2441, "s": 2275, "text": "The interact() method is used to return the value of the callable in coupling with the sliders. It is real time in nature. The slide in slider will change the value." }, { "code": null, "e": 2621, "s": 2441, "text": "Like IntSlider, there is a class for float slider which is used to handle the float changes in real time. It is same as IntSlider but it has feature to take steps in float values." }, { "code": null, "e": 2630, "s": 2621, "text": "Example:" }, { "code": null, "e": 2638, "s": 2630, "text": "Python3" }, { "code": "import ipywidgets as widgetswidgets.interact(lambda x:x**2, x = widgets.FloatSlider(min = 0, step =.25, max = 10, value = 1))", "e": 2764, "s": 2638, "text": null }, { "code": null, "e": 2772, "s": 2764, "text": "Output:" }, { "code": null, "e": 2779, "s": 2772, "text": "Output" }, { "code": null, "e": 3125, "s": 2779, "text": "The FloatLogSlider has a log scale, which makes it easy to have a slider that covers a wide range of positive magnitudes. It is generally show to demonstrate the cost values in the machine learning algorithms. In this the min and max refer to the minimum and maximum exponents of the base, and the value refers to the actual value of the slider." }, { "code": null, "e": 3188, "s": 3125, "text": "The base parameter allows to alter the log base in the slider." }, { "code": null, "e": 3197, "s": 3188, "text": "Example:" }, { "code": null, "e": 3205, "s": 3197, "text": "Python3" }, { "code": "import ipywidgets as widgetswidgets.interact(lambda x:x, x = widgets.FloatLogSlider(description =\"$e ^ x$\", min = 0, step = 1, base = 5, max = 10, value = 1))", "e": 3364, "s": 3205, "text": null }, { "code": null, "e": 3372, "s": 3364, "text": "Output:" }, { "code": null, "e": 3379, "s": 3372, "text": "Output" }, { "code": null, "e": 3583, "s": 3379, "text": "It is the widget used to set a range as an interactive component. It sets a tuple with 2 values the start and the stop values. The Syntax difference with respect to IntSlide is only for the value option." }, { "code": null, "e": 3592, "s": 3583, "text": "Example:" }, { "code": null, "e": 3600, "s": 3592, "text": "Python3" }, { "code": "import ipywidgets as widgetswidgets.interact(lambda x :x, x = widgets.IntRangeSlider(min = 0, step = 1, max = 10, value =[1, 2]))", "e": 3730, "s": 3600, "text": null }, { "code": null, "e": 3738, "s": 3730, "text": "Output:" }, { "code": null, "e": 3745, "s": 3738, "text": "Output" }, { "code": null, "e": 3951, "s": 3745, "text": "It is the widget used to set a range as an interactive component. It sets a tuple with 2 values the start and the stop values. The Syntax difference with respect to FloatSlide is only for the value option." }, { "code": null, "e": 3960, "s": 3951, "text": "Example:" }, { "code": null, "e": 3968, "s": 3960, "text": "Python3" }, { "code": "import ipywidgets as widgetswidgets.interact(lambda x :x, x = widgets.FloatRangeSlider(min = 0, step =.25, max = 10, value =[1, 2]))", "e": 4101, "s": 3968, "text": null }, { "code": null, "e": 4109, "s": 4101, "text": "Output:" }, { "code": null, "e": 4116, "s": 4109, "text": "Output" }, { "code": null, "e": 4131, "s": 4116, "text": "varshagumber28" }, { "code": null, "e": 4142, "s": 4131, "text": "Python-gui" }, { "code": null, "e": 4149, "s": 4142, "text": "Python" }, { "code": null, "e": 4165, "s": 4149, "text": "Python Programs" }, { "code": null, "e": 4263, "s": 4165, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4305, "s": 4263, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 4327, "s": 4305, "text": "Enumerate() in Python" }, { "code": null, "e": 4353, "s": 4327, "text": "Python String | replace()" }, { "code": null, "e": 4385, "s": 4353, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 4414, "s": 4385, "text": "*args and **kwargs in Python" }, { "code": null, "e": 4436, "s": 4414, "text": "Defaultdict in Python" }, { "code": null, "e": 4475, "s": 4436, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 4513, "s": 4475, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 4550, "s": 4513, "text": "Python Program for Fibonacci numbers" } ]
How can I apply an offset on the current time in Python?
Whenever you want to add or subtract(apply an offset) to a date/time, use a datetime.datetime(), then add or subtract datetime.timedelta() instances. A timedelta object represents a duration, the difference between two dates or times. The timedelta constructor has the following function signature − datetime.timedelta([days[, seconds[, microseconds[, milliseconds[, minutes[, hours[, weeks]]]]]]]) Note − All arguments are optional and default to 0. Arguments may be ints, longs, or floats, and may be positive or negative. You can read more about it here − https://docs.python.org/2/library/datetime.html#timedelta-objects An example of using the timedelta objects and dates − import datetime old_time = datetime.datetime.now() print(old_time) new_time = old_time - datetime.timedelta(hours=2, minutes=10) print(new_time) This will give the output − 2018-01-04 11:09:00.694602 2018-01-04 08:59:00.694602 timedelta() arithmetic is not supported for datetime.time() objects; if you need to use offsets from an existing datetime.time() object, just use datetime.datetime.combine() to form a datetime.datetime() instance, do your calculations, and 'extract' the time again with the .time() method.
[ { "code": null, "e": 1487, "s": 1187, "text": "Whenever you want to add or subtract(apply an offset) to a date/time, use a datetime.datetime(), then add or subtract datetime.timedelta() instances. A timedelta object represents a duration, the difference between two dates or times. The timedelta constructor has the following function signature −" }, { "code": null, "e": 1586, "s": 1487, "text": "datetime.timedelta([days[, seconds[, microseconds[, milliseconds[, minutes[, hours[, weeks]]]]]]])" }, { "code": null, "e": 1812, "s": 1586, "text": "Note − All arguments are optional and default to 0. Arguments may be ints, longs, or floats, and may be positive or negative. You can read more about it here − https://docs.python.org/2/library/datetime.html#timedelta-objects" }, { "code": null, "e": 1866, "s": 1812, "text": "An example of using the timedelta objects and dates −" }, { "code": null, "e": 2011, "s": 1866, "text": "import datetime\nold_time = datetime.datetime.now()\nprint(old_time)\nnew_time = old_time - datetime.timedelta(hours=2, minutes=10)\nprint(new_time)" }, { "code": null, "e": 2039, "s": 2011, "text": "This will give the output −" }, { "code": null, "e": 2093, "s": 2039, "text": "2018-01-04 11:09:00.694602\n2018-01-04 08:59:00.694602" }, { "code": null, "e": 2383, "s": 2093, "text": "timedelta() arithmetic is not supported for datetime.time() objects; if you need to use offsets from an existing datetime.time() object, just use datetime.datetime.combine() to form a datetime.datetime() instance, do your calculations, and 'extract' the time again with the .time() method." } ]
Python statistics | variance()
13 Oct, 2021 Statistics module provides very powerful tools, which can be used to compute anything related to Statistics. variance() is one such function. This function helps to calculate the variance from a sample of data (sample is a subset of populated data). variance() function should only be used when variance of a sample needs to be calculated. There’s another function known as pvariance(), which is used to calculate the variance of an entire population.In pure statistics, variance is the squared deviation of a variable from its mean. Basically, it measures the spread of random data in a set from its mean or median value. A low value for variance indicates that the data are clustered together and are not spread apart widely, whereas a high value would indicate that the data in the given set are much more spread apart from the average value. Variance is an important tool in the sciences, where statistical analysis of data is common. It is the square of standard deviation of the given data-set and is also known as second central moment of a distribution. It is usually represented by in pure Statistics.Variance is calculated by the following formula : It’s calculated by mean of square minus square of mean Syntax : variance( [data], xbar )Parameters : [data] : An iterable with real valued numbers. xbar (Optional) : Takes actual mean of data-set as value.Returnype : Returns the actual variance of the values passed as parameter.Exceptions : StatisticsError is raised for data-set less than 2-values passed as parameter. Throws impossible values when the value provided as xbar doesn’t match actual mean of the data-set. Code #1 : Python3 # Python code to demonstrate the working of# variance() function of Statistics Module # Importing Statistics moduleimport statistics # Creating a sample of datasample = [2.74, 1.23, 2.63, 2.22, 3, 1.98] # Prints variance of the sample set # Function will automatically calculate# it's mean and set it as xbarprint("Variance of sample set is % s" %(statistics.variance(sample))) Output : Variance of sample set is 0.40924 Code #2 : Demonstrates variance() on a range of data-types Python3 # Python code to demonstrate variance()# function on varying range of data-types # importing statistics modulefrom statistics import variance # importing fractions as parameter valuesfrom fractions import Fraction as fr # tuple of a set of positive integers# numbers are spread apart but not very muchsample1 = (1, 2, 5, 4, 8, 9, 12) # tuple of a set of negative integerssample2 = (-2, -4, -3, -1, -5, -6) # tuple of a set of positive and negative numbers# data-points are spread apart considerablysample3 = (-9, -1, -0, 2, 1, 3, 4, 19) # tuple of a set of fractional numberssample4 = (fr(1, 2), fr(2, 3), fr(3, 4), fr(5, 6), fr(7, 8)) # tuple of a set of floating point valuessample5 = (1.23, 1.45, 2.1, 2.2, 1.9) # Print the variance of each samplesprint("Variance of Sample1 is % s " %(variance(sample1)))print("Variance of Sample2 is % s " %(variance(sample2)))print("Variance of Sample3 is % s " %(variance(sample3)))print("Variance of Sample4 is % s " %(variance(sample4)))print("Variance of Sample5 is % s " %(variance(sample5))) Output : Variance of Sample 1 is 15.80952380952381 Variance of Sample 2 is 3.5 Variance of Sample 3 is 61.125 Variance of Sample 4 is 1/45 Variance of Sample 5 is 0.17613000000000006 Code #3 : Demonstrates the use of xbar parameter Python3 # Python code to demonstrate# the use of xbar parameter # Importing statistics moduleimport statistics # creating a sample listsample = (1, 1.3, 1.2, 1.9, 2.5, 2.2) # calculating the mean of sample setm = statistics.mean(sample) # calculating the variance of sample setprint("Variance of Sample set is % s" %(statistics.variance(sample, xbar = m))) Output : Variance of Sample set is 0.3656666666666667 Code #4 : Demonstrates the Error when value of xbar is not same as the mean/average value Python3 # Python code to demonstrate the error caused# when garbage value of xbar is entered # Importing statistics moduleimport statistics # creating a sample listsample = (1, 1.3, 1.2, 1.9, 2.5, 2.2) # calculating the mean of sample setm = statistics.mean(sample) # Actual value of mean after calculation# comes out to 1.6833333333333333# But to demonstrate xbar error let's enter# -100 as the value for xbar parameterprint(statistics.variance(sample, xbar = -100)) Output : 0.3656666666663053 Note : It is different in precision from the output in Code #3 Code #4 : Demonstrates StatisticsError Python3 # Python code to demonstrate StatisticsError # importing Statistics moduleimport statistics # creating an empty data-srtsample = [] # will raise Statistics Errorprint(statistics.variance(sample)) Output : Traceback (most recent call last): File "/home/64bf6d80f158b65d2b75c894d03a7779.py", line 10, in print(statistics.variance(sample)) File "/usr/lib/python3.5/statistics.py", line 555, in variance raise StatisticsError('variance requires at least two data points') statistics.StatisticsError: variance requires at least two data points Applications : Variance is a very important tool in Statistics and handling huge amounts of data. Like, when the omniscient mean is unknown (sample mean) then variance is used as biased estimator. Real world observations like the value of increase and decrease of all shares of a company throughout the day cannot be all sets of possible observations. As such, variance is calculated from a finite set of data, although it won’t match when calculated taking the whole population into consideration, but still it will give the user an estimate which is enough to chalk out other calculations. Akanksha_Rai kashishsoda Python-Built-in-functions Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n13 Oct, 2021" }, { "code": null, "e": 1190, "s": 28, "text": "Statistics module provides very powerful tools, which can be used to compute anything related to Statistics. variance() is one such function. This function helps to calculate the variance from a sample of data (sample is a subset of populated data). variance() function should only be used when variance of a sample needs to be calculated. There’s another function known as pvariance(), which is used to calculate the variance of an entire population.In pure statistics, variance is the squared deviation of a variable from its mean. Basically, it measures the spread of random data in a set from its mean or median value. A low value for variance indicates that the data are clustered together and are not spread apart widely, whereas a high value would indicate that the data in the given set are much more spread apart from the average value. Variance is an important tool in the sciences, where statistical analysis of data is common. It is the square of standard deviation of the given data-set and is also known as second central moment of a distribution. It is usually represented by in pure Statistics.Variance is calculated by the following formula : " }, { "code": null, "e": 1246, "s": 1190, "text": "It’s calculated by mean of square minus square of mean " }, { "code": null, "e": 1666, "s": 1248, "text": "Syntax : variance( [data], xbar )Parameters : [data] : An iterable with real valued numbers. xbar (Optional) : Takes actual mean of data-set as value.Returnype : Returns the actual variance of the values passed as parameter.Exceptions : StatisticsError is raised for data-set less than 2-values passed as parameter. Throws impossible values when the value provided as xbar doesn’t match actual mean of the data-set. " }, { "code": null, "e": 1677, "s": 1666, "text": "Code #1 : " }, { "code": null, "e": 1685, "s": 1677, "text": "Python3" }, { "code": "# Python code to demonstrate the working of# variance() function of Statistics Module # Importing Statistics moduleimport statistics # Creating a sample of datasample = [2.74, 1.23, 2.63, 2.22, 3, 1.98] # Prints variance of the sample set # Function will automatically calculate# it's mean and set it as xbarprint(\"Variance of sample set is % s\" %(statistics.variance(sample)))", "e": 2068, "s": 1685, "text": null }, { "code": null, "e": 2079, "s": 2068, "text": "Output : " }, { "code": null, "e": 2113, "s": 2079, "text": "Variance of sample set is 0.40924" }, { "code": null, "e": 2176, "s": 2113, "text": " Code #2 : Demonstrates variance() on a range of data-types " }, { "code": null, "e": 2184, "s": 2176, "text": "Python3" }, { "code": "# Python code to demonstrate variance()# function on varying range of data-types # importing statistics modulefrom statistics import variance # importing fractions as parameter valuesfrom fractions import Fraction as fr # tuple of a set of positive integers# numbers are spread apart but not very muchsample1 = (1, 2, 5, 4, 8, 9, 12) # tuple of a set of negative integerssample2 = (-2, -4, -3, -1, -5, -6) # tuple of a set of positive and negative numbers# data-points are spread apart considerablysample3 = (-9, -1, -0, 2, 1, 3, 4, 19) # tuple of a set of fractional numberssample4 = (fr(1, 2), fr(2, 3), fr(3, 4), fr(5, 6), fr(7, 8)) # tuple of a set of floating point valuessample5 = (1.23, 1.45, 2.1, 2.2, 1.9) # Print the variance of each samplesprint(\"Variance of Sample1 is % s \" %(variance(sample1)))print(\"Variance of Sample2 is % s \" %(variance(sample2)))print(\"Variance of Sample3 is % s \" %(variance(sample3)))print(\"Variance of Sample4 is % s \" %(variance(sample4)))print(\"Variance of Sample5 is % s \" %(variance(sample5)))", "e": 3241, "s": 2184, "text": null }, { "code": null, "e": 3252, "s": 3241, "text": "Output : " }, { "code": null, "e": 3431, "s": 3252, "text": "Variance of Sample 1 is 15.80952380952381 \nVariance of Sample 2 is 3.5 \nVariance of Sample 3 is 61.125 \nVariance of Sample 4 is 1/45 \nVariance of Sample 5 is 0.17613000000000006 " }, { "code": null, "e": 3484, "s": 3431, "text": " Code #3 : Demonstrates the use of xbar parameter " }, { "code": null, "e": 3492, "s": 3484, "text": "Python3" }, { "code": "# Python code to demonstrate# the use of xbar parameter # Importing statistics moduleimport statistics # creating a sample listsample = (1, 1.3, 1.2, 1.9, 2.5, 2.2) # calculating the mean of sample setm = statistics.mean(sample) # calculating the variance of sample setprint(\"Variance of Sample set is % s\" %(statistics.variance(sample, xbar = m)))", "e": 3845, "s": 3492, "text": null }, { "code": null, "e": 3856, "s": 3845, "text": "Output : " }, { "code": null, "e": 3901, "s": 3856, "text": "Variance of Sample set is 0.3656666666666667" }, { "code": null, "e": 3995, "s": 3901, "text": " Code #4 : Demonstrates the Error when value of xbar is not same as the mean/average value " }, { "code": null, "e": 4003, "s": 3995, "text": "Python3" }, { "code": "# Python code to demonstrate the error caused# when garbage value of xbar is entered # Importing statistics moduleimport statistics # creating a sample listsample = (1, 1.3, 1.2, 1.9, 2.5, 2.2) # calculating the mean of sample setm = statistics.mean(sample) # Actual value of mean after calculation# comes out to 1.6833333333333333# But to demonstrate xbar error let's enter# -100 as the value for xbar parameterprint(statistics.variance(sample, xbar = -100))", "e": 4463, "s": 4003, "text": null }, { "code": null, "e": 4474, "s": 4463, "text": "Output : " }, { "code": null, "e": 4493, "s": 4474, "text": "0.3656666666663053" }, { "code": null, "e": 4599, "s": 4493, "text": "Note : It is different in precision from the output in Code #3 Code #4 : Demonstrates StatisticsError " }, { "code": null, "e": 4607, "s": 4599, "text": "Python3" }, { "code": "# Python code to demonstrate StatisticsError # importing Statistics moduleimport statistics # creating an empty data-srtsample = [] # will raise Statistics Errorprint(statistics.variance(sample))", "e": 4803, "s": 4607, "text": null }, { "code": null, "e": 4814, "s": 4803, "text": "Output : " }, { "code": null, "e": 5161, "s": 4814, "text": "Traceback (most recent call last):\n File \"/home/64bf6d80f158b65d2b75c894d03a7779.py\", line 10, in \n print(statistics.variance(sample))\n File \"/usr/lib/python3.5/statistics.py\", line 555, in variance\n raise StatisticsError('variance requires at least two data points')\nstatistics.StatisticsError: variance requires at least two data points" }, { "code": null, "e": 5756, "s": 5161, "text": " Applications : Variance is a very important tool in Statistics and handling huge amounts of data. Like, when the omniscient mean is unknown (sample mean) then variance is used as biased estimator. Real world observations like the value of increase and decrease of all shares of a company throughout the day cannot be all sets of possible observations. As such, variance is calculated from a finite set of data, although it won’t match when calculated taking the whole population into consideration, but still it will give the user an estimate which is enough to chalk out other calculations. " }, { "code": null, "e": 5769, "s": 5756, "text": "Akanksha_Rai" }, { "code": null, "e": 5781, "s": 5769, "text": "kashishsoda" }, { "code": null, "e": 5807, "s": 5781, "text": "Python-Built-in-functions" }, { "code": null, "e": 5814, "s": 5807, "text": "Python" } ]
Python | Program to convert a tuple to a string
30 Jun, 2021 Given a tuple of characters, Write a python program to convert the tuple into a string. Examples: Input : ('a', 'b', 'c', 'd', 'e') Output : abcde Input : ('g', 'e', 'e', 'k', 's') Output : geeks There are various approaches to convert a tuple to a string. Create an empty string and using a for loop iterate through the elements of the tuple and keep on adding each element to the empty string. In this way, the tuple is converted to a string. It is one of the simplest and the easiest approaches to convert a tuple to a string in Python. Python3 # Python3 code to convert a tuple# into a string using a for loop def convertTuple(tup): # initialize an empty string str = '' for item in tup: str = str + item return str # Driver codetuple = ('g', 'e', 'e', 'k', 's')str = convertTuple(tuple)print(str) Output: geeks The join() method is a string method and returns a string in which the elements of the sequence have been joined by a str separator. Using join() we add the characters of the tuple and convert it into a string. Python3 # Python3 code to convert a tuple# into a string using str.join() method def convertTuple(tup): str = ''.join(tup) return str # Driver codetuple = ('g', 'e', 'e', 'k', 's')str = convertTuple(tuple)print(str) Output: geeks The str.join() function works well when we have only string objects as the tuple elements but if the tuple contains at least one non-string object then the str.join() function will fail and show a TypeError as a string object cannot be added to a non-string object. Hence to avoid this TypeError we will make use of map() function inside the join(). This map() function will take the iterator of the tuple and str() function as its parameters and convert each element of the tuple into a string. Python3 # Python3 code to convert a tuple# into a string using str.join() & map() functions def convertTuple(tup): st = ''.join(map(str, tup)) return st # Driver codetuple = ('g', 'e', 'e', 'k', 's', 101)str = convertTuple(tuple)print(str) Output: geeks101 The reduce(fun, seq) function is used to apply a particular function passed in its argument to all of the list elements mentioned in the sequence passed along. We pass the add operator in the function to concatenate the characters of a tuple. Python3 # Python3 code to convert a tuple# into a string using reduce() functionimport functoolsimport operator def convertTuple(tup): str = functools.reduce(operator.add, (tup)) return str # Driver codetuple = ('g', 'e', 'e', 'k', 's')str = convertTuple(tuple)print(str) Output: geeks sanju6890 Python string-programs Python tuple-programs python-string python-tuple Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Different ways to create Pandas Dataframe Enumerate() in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python | Convert string dictionary to dictionary Python Program for Fibonacci numbers
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Jun, 2021" }, { "code": null, "e": 117, "s": 28, "text": "Given a tuple of characters, Write a python program to convert the tuple into a string. " }, { "code": null, "e": 128, "s": 117, "text": "Examples: " }, { "code": null, "e": 227, "s": 128, "text": "Input : ('a', 'b', 'c', 'd', 'e')\nOutput : abcde\n\nInput : ('g', 'e', 'e', 'k', 's')\nOutput : geeks" }, { "code": null, "e": 290, "s": 227, "text": " There are various approaches to convert a tuple to a string. " }, { "code": null, "e": 573, "s": 290, "text": "Create an empty string and using a for loop iterate through the elements of the tuple and keep on adding each element to the empty string. In this way, the tuple is converted to a string. It is one of the simplest and the easiest approaches to convert a tuple to a string in Python." }, { "code": null, "e": 581, "s": 573, "text": "Python3" }, { "code": "# Python3 code to convert a tuple# into a string using a for loop def convertTuple(tup): # initialize an empty string str = '' for item in tup: str = str + item return str # Driver codetuple = ('g', 'e', 'e', 'k', 's')str = convertTuple(tuple)print(str)", "e": 860, "s": 581, "text": null }, { "code": null, "e": 868, "s": 860, "text": "Output:" }, { "code": null, "e": 874, "s": 868, "text": "geeks" }, { "code": null, "e": 1087, "s": 874, "text": "The join() method is a string method and returns a string in which the elements of the sequence have been joined by a str separator. Using join() we add the characters of the tuple and convert it into a string. " }, { "code": null, "e": 1095, "s": 1087, "text": "Python3" }, { "code": "# Python3 code to convert a tuple# into a string using str.join() method def convertTuple(tup): str = ''.join(tup) return str # Driver codetuple = ('g', 'e', 'e', 'k', 's')str = convertTuple(tuple)print(str)", "e": 1311, "s": 1095, "text": null }, { "code": null, "e": 1319, "s": 1311, "text": "Output:" }, { "code": null, "e": 1325, "s": 1319, "text": "geeks" }, { "code": null, "e": 1821, "s": 1325, "text": "The str.join() function works well when we have only string objects as the tuple elements but if the tuple contains at least one non-string object then the str.join() function will fail and show a TypeError as a string object cannot be added to a non-string object. Hence to avoid this TypeError we will make use of map() function inside the join(). This map() function will take the iterator of the tuple and str() function as its parameters and convert each element of the tuple into a string." }, { "code": null, "e": 1829, "s": 1821, "text": "Python3" }, { "code": "# Python3 code to convert a tuple# into a string using str.join() & map() functions def convertTuple(tup): st = ''.join(map(str, tup)) return st # Driver codetuple = ('g', 'e', 'e', 'k', 's', 101)str = convertTuple(tuple)print(str)", "e": 2069, "s": 1829, "text": null }, { "code": null, "e": 2077, "s": 2069, "text": "Output:" }, { "code": null, "e": 2086, "s": 2077, "text": "geeks101" }, { "code": null, "e": 2331, "s": 2086, "text": "The reduce(fun, seq) function is used to apply a particular function passed in its argument to all of the list elements mentioned in the sequence passed along. We pass the add operator in the function to concatenate the characters of a tuple. " }, { "code": null, "e": 2339, "s": 2331, "text": "Python3" }, { "code": "# Python3 code to convert a tuple# into a string using reduce() functionimport functoolsimport operator def convertTuple(tup): str = functools.reduce(operator.add, (tup)) return str # Driver codetuple = ('g', 'e', 'e', 'k', 's')str = convertTuple(tuple)print(str)", "e": 2611, "s": 2339, "text": null }, { "code": null, "e": 2619, "s": 2611, "text": "Output:" }, { "code": null, "e": 2625, "s": 2619, "text": "geeks" }, { "code": null, "e": 2635, "s": 2625, "text": "sanju6890" }, { "code": null, "e": 2658, "s": 2635, "text": "Python string-programs" }, { "code": null, "e": 2680, "s": 2658, "text": "Python tuple-programs" }, { "code": null, "e": 2694, "s": 2680, "text": "python-string" }, { "code": null, "e": 2707, "s": 2694, "text": "python-tuple" }, { "code": null, "e": 2714, "s": 2707, "text": "Python" }, { "code": null, "e": 2730, "s": 2714, "text": "Python Programs" }, { "code": null, "e": 2828, "s": 2730, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2870, "s": 2828, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2892, "s": 2870, "text": "Enumerate() in Python" }, { "code": null, "e": 2918, "s": 2892, "text": "Python String | replace()" }, { "code": null, "e": 2950, "s": 2918, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2979, "s": 2950, "text": "*args and **kwargs in Python" }, { "code": null, "e": 3001, "s": 2979, "text": "Defaultdict in Python" }, { "code": null, "e": 3040, "s": 3001, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 3078, "s": 3040, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 3127, "s": 3078, "text": "Python | Convert string dictionary to dictionary" } ]
Difference between Relative Addressing Mode and Direct Addressing Mode
04 Jul, 2022 Prerequisite – Addressing Modes In an Instruction Fetch operation of the Instruction Cycle Process, addressing mode plays a crucial part. Addressing Mode is how the operand is addressed in an instruction word before being executed. 1. Relative Address Mode: In this mode, the Effective Address (EA) of the operand is calculated by adding the content of the CPU register and the address part of the instruction word. The effective address is calculated by adding displacement (immediate value given in the instruction) and the register value. The address part of the instruction is usually a signed number, either positive or negative. The effective address thus calculated is relative to the address of the next instruction. EA = CPU Register + Displacement Figure – PC Relative Addressing Mode Relative Addressing Mode can be further classified into three types – PC (Program Counter) Relative Addressing Mode. Index Register Relative Addressing Mode or Indexed Addressing Mode. Base Register Addressing Mode. 2. Direct Address Mode: In Direct Address Mode, the effective address of the operand is equal to the address part of the instruction, i.e. the address part of the instruction indicates the memory location containing the operand. Example – ADD R1, 4000 where 4000 is the effective address of the location. Figure – Direct Address ModeIn this example, the memory location 4000 contains the operand 100 which gets added to the contents of R1 and gets stored in R1. Difference between Relative Addressing Mode and Direct Addressing Mode : The PC Relative or Base Relative Addressing mode is favored over the direct addressing mode because-i) Reduce the size of program storage.ii) Reduce the instruction fetch queue’s size. iii) It will be simpler to relocate. annieahujaweb2020 microprocessor Computer Organization & Architecture Difference Between GATE CS microprocessor Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n04 Jul, 2022" }, { "code": null, "e": 287, "s": 54, "text": "Prerequisite – Addressing Modes In an Instruction Fetch operation of the Instruction Cycle Process, addressing mode plays a crucial part. Addressing Mode is how the operand is addressed in an instruction word before being executed. " }, { "code": null, "e": 780, "s": 287, "text": "1. Relative Address Mode: In this mode, the Effective Address (EA) of the operand is calculated by adding the content of the CPU register and the address part of the instruction word. The effective address is calculated by adding displacement (immediate value given in the instruction) and the register value. The address part of the instruction is usually a signed number, either positive or negative. The effective address thus calculated is relative to the address of the next instruction." }, { "code": null, "e": 813, "s": 780, "text": "EA = CPU Register + Displacement" }, { "code": null, "e": 850, "s": 813, "text": "Figure – PC Relative Addressing Mode" }, { "code": null, "e": 920, "s": 850, "text": "Relative Addressing Mode can be further classified into three types –" }, { "code": null, "e": 967, "s": 920, "text": "PC (Program Counter) Relative Addressing Mode." }, { "code": null, "e": 1035, "s": 967, "text": "Index Register Relative Addressing Mode or Indexed Addressing Mode." }, { "code": null, "e": 1066, "s": 1035, "text": "Base Register Addressing Mode." }, { "code": null, "e": 1372, "s": 1066, "text": "2. Direct Address Mode: In Direct Address Mode, the effective address of the operand is equal to the address part of the instruction, i.e. the address part of the instruction indicates the memory location containing the operand. Example – ADD R1, 4000 where 4000 is the effective address of the location. " }, { "code": null, "e": 1603, "s": 1372, "text": "Figure – Direct Address ModeIn this example, the memory location 4000 contains the operand 100 which gets added to the contents of R1 and gets stored in R1. Difference between Relative Addressing Mode and Direct Addressing Mode : " }, { "code": null, "e": 1788, "s": 1603, "text": "The PC Relative or Base Relative Addressing mode is favored over the direct addressing mode because-i) Reduce the size of program storage.ii) Reduce the instruction fetch queue’s size." }, { "code": null, "e": 1825, "s": 1788, "text": "iii) It will be simpler to relocate." }, { "code": null, "e": 1843, "s": 1825, "text": "annieahujaweb2020" }, { "code": null, "e": 1858, "s": 1843, "text": "microprocessor" }, { "code": null, "e": 1895, "s": 1858, "text": "Computer Organization & Architecture" }, { "code": null, "e": 1914, "s": 1895, "text": "Difference Between" }, { "code": null, "e": 1922, "s": 1914, "text": "GATE CS" }, { "code": null, "e": 1937, "s": 1922, "text": "microprocessor" } ]
Live Webcam Drawing using OpenCV
22 Feb, 2022 Let us see how to draw the movement of objects captured by the webcam using OpenCV. Our program takes the video input from the webcam and tracks the objects we are moving. After identifying the objects, it will make contours precisely. After that, it will print all your drawing on the output screen. python3 # importing the modulesimport cv2import numpy as np # set Width and Height of output ScreenframeWidth = 640frameHeight = 480 # capturing Video from Webcamcap = cv2.VideoCapture(0)cap.set(3, frameWidth)cap.set(4, frameHeight) # set brightness, id is 10 and# value can be changed accordinglycap.set(10,150) # object color valuesmyColors = [[5, 107, 0, 19, 255, 255], [133, 56, 0, 159, 156, 255], [57, 76, 0, 100, 255, 255], [90, 48, 0, 118, 255, 255]] # color values which will be used to paint# values needs to be in BGRmyColorValues = [[51, 153, 255], [255, 0, 255], [0, 255, 0], [255, 0, 0]] # [x , y , colorId ]myPoints = [] # function to pick color of objectdef findColor(img, myColors, myColorValues): # converting the image to HSV format imgHSV = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) count = 0 newPoints = [] # running for loop to work with all colors for color in myColors: lower = np.array(color[0:3]) upper = np.array(color[3:6]) mask = cv2.inRange(imgHSV,lower,upper) x, y = getContours(mask) # making the circles cv2.circle(imgResult, (x,y), 15, myColorValues[count], cv2.FILLED) if x != 0 and y != 0: newPoints.append([x,y,count]) count += 1 return newPoints # contours function used to improve accuracy of paintdef getContours(img): _, contours, hierarchy = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) x, y, w, h = 0, 0, 0, 0 # working with contours for cnt in contours: area = cv2.contourArea(cnt) if area > 500: peri = cv2.arcLength(cnt, True) approx = cv2.approxPolyDP(cnt, 0.02 * peri, True) x, y, w, h = cv2.boundingRect(approx) return x + w // 2, y # draws your action on virtual canvasdef drawOnCanvas(myPoints, myColorValues): for point in myPoints: cv2.circle(imgResult, (point[0], point[1]), 10, myColorValues[point[2]], cv2.FILLED) # running infinite while loop so that# program keep running until we close itwhile True: success, img = cap.read() imgResult = img.copy() # finding the colors for the points newPoints = findColor(img, myColors, myColorValues) if len(newPoints)!= 0: for newP in newPoints: myPoints.append(newP) if len(myPoints)!= 0: # drawing the points drawOnCanvas(myPoints, myColorValues) # displaying output on Screen cv2.imshow("Result", imgResult) # condition to break programs execution # press q to stop the execution of program if cv2.waitKey(1) and 0xFF == ord('q'): break Output : germanshephered48 kk773572498 Python-OpenCV Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 54, "s": 26, "text": "\n22 Feb, 2022" }, { "code": null, "e": 356, "s": 54, "text": "Let us see how to draw the movement of objects captured by the webcam using OpenCV. Our program takes the video input from the webcam and tracks the objects we are moving. After identifying the objects, it will make contours precisely. After that, it will print all your drawing on the output screen. " }, { "code": null, "e": 364, "s": 356, "text": "python3" }, { "code": "# importing the modulesimport cv2import numpy as np # set Width and Height of output ScreenframeWidth = 640frameHeight = 480 # capturing Video from Webcamcap = cv2.VideoCapture(0)cap.set(3, frameWidth)cap.set(4, frameHeight) # set brightness, id is 10 and# value can be changed accordinglycap.set(10,150) # object color valuesmyColors = [[5, 107, 0, 19, 255, 255], [133, 56, 0, 159, 156, 255], [57, 76, 0, 100, 255, 255], [90, 48, 0, 118, 255, 255]] # color values which will be used to paint# values needs to be in BGRmyColorValues = [[51, 153, 255], [255, 0, 255], [0, 255, 0], [255, 0, 0]] # [x , y , colorId ]myPoints = [] # function to pick color of objectdef findColor(img, myColors, myColorValues): # converting the image to HSV format imgHSV = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) count = 0 newPoints = [] # running for loop to work with all colors for color in myColors: lower = np.array(color[0:3]) upper = np.array(color[3:6]) mask = cv2.inRange(imgHSV,lower,upper) x, y = getContours(mask) # making the circles cv2.circle(imgResult, (x,y), 15, myColorValues[count], cv2.FILLED) if x != 0 and y != 0: newPoints.append([x,y,count]) count += 1 return newPoints # contours function used to improve accuracy of paintdef getContours(img): _, contours, hierarchy = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) x, y, w, h = 0, 0, 0, 0 # working with contours for cnt in contours: area = cv2.contourArea(cnt) if area > 500: peri = cv2.arcLength(cnt, True) approx = cv2.approxPolyDP(cnt, 0.02 * peri, True) x, y, w, h = cv2.boundingRect(approx) return x + w // 2, y # draws your action on virtual canvasdef drawOnCanvas(myPoints, myColorValues): for point in myPoints: cv2.circle(imgResult, (point[0], point[1]), 10, myColorValues[point[2]], cv2.FILLED) # running infinite while loop so that# program keep running until we close itwhile True: success, img = cap.read() imgResult = img.copy() # finding the colors for the points newPoints = findColor(img, myColors, myColorValues) if len(newPoints)!= 0: for newP in newPoints: myPoints.append(newP) if len(myPoints)!= 0: # drawing the points drawOnCanvas(myPoints, myColorValues) # displaying output on Screen cv2.imshow(\"Result\", imgResult) # condition to break programs execution # press q to stop the execution of program if cv2.waitKey(1) and 0xFF == ord('q'): break", "e": 3163, "s": 364, "text": null }, { "code": null, "e": 3174, "s": 3163, "text": "Output : " }, { "code": null, "e": 3194, "s": 3176, "text": "germanshephered48" }, { "code": null, "e": 3206, "s": 3194, "text": "kk773572498" }, { "code": null, "e": 3220, "s": 3206, "text": "Python-OpenCV" }, { "code": null, "e": 3227, "s": 3220, "text": "Python" }, { "code": null, "e": 3325, "s": 3227, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3357, "s": 3325, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3384, "s": 3357, "text": "Python Classes and Objects" }, { "code": null, "e": 3405, "s": 3384, "text": "Python OOPs Concepts" }, { "code": null, "e": 3428, "s": 3405, "text": "Introduction To PYTHON" }, { "code": null, "e": 3484, "s": 3428, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 3515, "s": 3484, "text": "Python | os.path.join() method" }, { "code": null, "e": 3557, "s": 3515, "text": "Check if element exists in list in Python" }, { "code": null, "e": 3599, "s": 3557, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 3638, "s": 3599, "text": "Python | Get unique values from a list" } ]
Java Program to Extract Content from a PDF
16 Jul, 2021 Java class< file using the Apache Tika< library is used. For document type detection and content extraction from various file formats, it uses various document parsers and document type detection techniques to detect and extract data. It provides a single generic API for parsing different file formats. All these parser libraries are encapsulated in a single interface called the Parser interface. Java supports multiple in-built classes and packages to extract and access the content from a PDF document. The following classes are used in the extraction of the content : BodyContentHandler is an in-built class that creates a handler for the text, which writes these XHTML body character events and stores them in an internal string buffer. It is inherited from the parent class ContentHandlerDecorator in Java. The specified text can be retrieved using the method ContentHandlerDecorator.toString() provided by the parent class. PDFParser Java provides an in-built package that provides a class PDFParser, which parses the contents of PDF documents. It extracts the contents of a PDF Document stored within paragraphs, strings, and tables (without invoking tabular boundaries). It can be used to parse encrypted documents too if the password is specified as an argument. ParseContext: This class is a component of the Java package org.apache.tika.parser, which is used to parse context and pass it on to the Tika parsers. Procedure: Create a content handler.Create a PDF file at the local directory in the system.Now, create a FileInputStream having the same path as that of the above PDF file created.Create a content parser using a metadata type object for the PDF document.PDF document is now parsed using the PDF parser class.Print the content of the PDF document as created above to illustrate the extraction of content in the above PDF. Create a content handler. Create a PDF file at the local directory in the system. Now, create a FileInputStream having the same path as that of the above PDF file created. Create a content parser using a metadata type object for the PDF document. PDF document is now parsed using the PDF parser class. Print the content of the PDF document as created above to illustrate the extraction of content in the above PDF. Implementation: The following Java program is used to illustrate the extraction of content from the PDF document. Java // Java Program to Extract Content from a PDF // Importing java input/output classesimport java.io.File;import java.io.FileInputStream;// Importing Apache POI classesimport org.apache.tika.metadata.Metadata;import org.apache.tika.parser.ParseContext;import org.apache.tika.parser.pdf.PDFParser;import org.apache.tika.sax.BodyContentHandler; // Classpublic class GFG { // Main driver method public static void main(String[] args) throws Exception { // Create a content handler BodyContentHandler contenthandler = new BodyContentHandler(); // Create a file in local directory File f = new File("C:/extractcontent.pdf"); // Create a file input stream // on specified path with the created file FileInputStream fstream = new FileInputStream(f); // Create an object of type Metadata to use Metadata data = new Metadata(); // Create a context parser for the pdf document ParseContext context = new ParseContext(); // PDF document can be parsed using the PDFparser // class PDFParser pdfparser = new PDFParser(); // Method parse invoked on PDFParser class pdfparser.parse(fstream, contenthandler, data, context); // Printing the contents of the pdf document // using toString() method in java System.out.println("Extracting contents :" + contenthandler.toString()); }} Output: The following are the contents of the file at the local directory made is as follows: surindertarika1234 Picked Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java How to iterate any Map in Java Interfaces in Java HashMap in Java with Examples ArrayList in Java Initializing a List in Java Java Programming Examples Convert a String to Character Array in Java Convert Double to Integer in Java Implementing a Linked List in Java using Class
[ { "code": null, "e": 28, "s": 0, "text": "\n16 Jul, 2021" }, { "code": null, "e": 428, "s": 28, "text": "Java class< file using the Apache Tika< library is used. For document type detection and content extraction from various file formats, it uses various document parsers and document type detection techniques to detect and extract data. It provides a single generic API for parsing different file formats. All these parser libraries are encapsulated in a single interface called the Parser interface." }, { "code": null, "e": 603, "s": 428, "text": "Java supports multiple in-built classes and packages to extract and access the content from a PDF document. The following classes are used in the extraction of the content : " }, { "code": null, "e": 963, "s": 603, "text": "BodyContentHandler is an in-built class that creates a handler for the text, which writes these XHTML body character events and stores them in an internal string buffer. It is inherited from the parent class ContentHandlerDecorator in Java. The specified text can be retrieved using the method ContentHandlerDecorator.toString() provided by the parent class. " }, { "code": null, "e": 1306, "s": 963, "text": "PDFParser Java provides an in-built package that provides a class PDFParser, which parses the contents of PDF documents. It extracts the contents of a PDF Document stored within paragraphs, strings, and tables (without invoking tabular boundaries). It can be used to parse encrypted documents too if the password is specified as an argument. " }, { "code": null, "e": 1457, "s": 1306, "text": "ParseContext: This class is a component of the Java package org.apache.tika.parser, which is used to parse context and pass it on to the Tika parsers." }, { "code": null, "e": 1468, "s": 1457, "text": "Procedure:" }, { "code": null, "e": 1878, "s": 1468, "text": "Create a content handler.Create a PDF file at the local directory in the system.Now, create a FileInputStream having the same path as that of the above PDF file created.Create a content parser using a metadata type object for the PDF document.PDF document is now parsed using the PDF parser class.Print the content of the PDF document as created above to illustrate the extraction of content in the above PDF." }, { "code": null, "e": 1904, "s": 1878, "text": "Create a content handler." }, { "code": null, "e": 1960, "s": 1904, "text": "Create a PDF file at the local directory in the system." }, { "code": null, "e": 2050, "s": 1960, "text": "Now, create a FileInputStream having the same path as that of the above PDF file created." }, { "code": null, "e": 2125, "s": 2050, "text": "Create a content parser using a metadata type object for the PDF document." }, { "code": null, "e": 2180, "s": 2125, "text": "PDF document is now parsed using the PDF parser class." }, { "code": null, "e": 2293, "s": 2180, "text": "Print the content of the PDF document as created above to illustrate the extraction of content in the above PDF." }, { "code": null, "e": 2407, "s": 2293, "text": "Implementation: The following Java program is used to illustrate the extraction of content from the PDF document." }, { "code": null, "e": 2412, "s": 2407, "text": "Java" }, { "code": "// Java Program to Extract Content from a PDF // Importing java input/output classesimport java.io.File;import java.io.FileInputStream;// Importing Apache POI classesimport org.apache.tika.metadata.Metadata;import org.apache.tika.parser.ParseContext;import org.apache.tika.parser.pdf.PDFParser;import org.apache.tika.sax.BodyContentHandler; // Classpublic class GFG { // Main driver method public static void main(String[] args) throws Exception { // Create a content handler BodyContentHandler contenthandler = new BodyContentHandler(); // Create a file in local directory File f = new File(\"C:/extractcontent.pdf\"); // Create a file input stream // on specified path with the created file FileInputStream fstream = new FileInputStream(f); // Create an object of type Metadata to use Metadata data = new Metadata(); // Create a context parser for the pdf document ParseContext context = new ParseContext(); // PDF document can be parsed using the PDFparser // class PDFParser pdfparser = new PDFParser(); // Method parse invoked on PDFParser class pdfparser.parse(fstream, contenthandler, data, context); // Printing the contents of the pdf document // using toString() method in java System.out.println(\"Extracting contents :\" + contenthandler.toString()); }}", "e": 3888, "s": 2412, "text": null }, { "code": null, "e": 3985, "s": 3891, "text": "Output: The following are the contents of the file at the local directory made is as follows:" }, { "code": null, "e": 4008, "s": 3989, "text": "surindertarika1234" }, { "code": null, "e": 4015, "s": 4008, "text": "Picked" }, { "code": null, "e": 4020, "s": 4015, "text": "Java" }, { "code": null, "e": 4034, "s": 4020, "text": "Java Programs" }, { "code": null, "e": 4039, "s": 4034, "text": "Java" }, { "code": null, "e": 4137, "s": 4039, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4188, "s": 4137, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 4219, "s": 4188, "text": "How to iterate any Map in Java" }, { "code": null, "e": 4238, "s": 4219, "text": "Interfaces in Java" }, { "code": null, "e": 4268, "s": 4238, "text": "HashMap in Java with Examples" }, { "code": null, "e": 4286, "s": 4268, "text": "ArrayList in Java" }, { "code": null, "e": 4314, "s": 4286, "text": "Initializing a List in Java" }, { "code": null, "e": 4340, "s": 4314, "text": "Java Programming Examples" }, { "code": null, "e": 4384, "s": 4340, "text": "Convert a String to Character Array in Java" }, { "code": null, "e": 4418, "s": 4384, "text": "Convert Double to Integer in Java" } ]
How to display the items in a JComboBox in Java
The following is an example to display the first element in a JComboBox in Java: import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JTextArea; public class SwingDemo { public static void main(String[] args) { JPanel panel = new JPanel(new BorderLayout()); String[] strArr = new String[] { "Laptop", "Mobile", "Desktop", "Tablet" }; JComboBox<String> comboBox = new JComboBox<>(strArr); panel.add(comboBox, BorderLayout.NORTH); JTextArea text = new JTextArea(5, 5); panel.add(text, BorderLayout.CENTER); JButton btn = new JButton("Click"); btn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { text.setText((String) comboBox.getSelectedItem()); comboBox.setSelectedIndex(0); } }); panel.add(btn, BorderLayout.SOUTH); JFrame frame = new JFrame(); frame.add(panel); frame.pack(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } } The output is as follows displaying the first item: Now, select the second item (Mobile) and press the “Click” button. The following will get displayed:
[ { "code": null, "e": 1268, "s": 1187, "text": "The following is an example to display the first element in a JComboBox in Java:" }, { "code": null, "e": 2422, "s": 1268, "text": "import java.awt.BorderLayout;\nimport java.awt.event.ActionEvent;\nimport java.awt.event.ActionListener;\nimport javax.swing.JButton;\nimport javax.swing.JComboBox;\nimport javax.swing.JFrame;\nimport javax.swing.JPanel;\nimport javax.swing.JTextArea;\npublic class SwingDemo {\n public static void main(String[] args) {\n JPanel panel = new JPanel(new BorderLayout());\n String[] strArr = new String[] { \"Laptop\", \"Mobile\", \"Desktop\", \"Tablet\" };\n JComboBox<String> comboBox = new JComboBox<>(strArr);\n panel.add(comboBox, BorderLayout.NORTH);\n JTextArea text = new JTextArea(5, 5);\n panel.add(text, BorderLayout.CENTER);\n JButton btn = new JButton(\"Click\");\n btn.addActionListener(new ActionListener() {\n @Override\n public void actionPerformed(ActionEvent e) {\n text.setText((String) comboBox.getSelectedItem());\n comboBox.setSelectedIndex(0);\n }\n });\n panel.add(btn, BorderLayout.SOUTH);\n JFrame frame = new JFrame();\n frame.add(panel);\n frame.pack();\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n frame.setVisible(true);\n }\n}" }, { "code": null, "e": 2474, "s": 2422, "text": "The output is as follows displaying the first item:" }, { "code": null, "e": 2575, "s": 2474, "text": "Now, select the second item (Mobile) and press the “Click” button. The following will get displayed:" } ]
How to select between/before/after dates in MySQL conditionally?
Following is the syntax − select *from yourTableName where yourColumnName1 < yourValue1 AND (yourColumnName2 > yourValue2 OR yourColumnName2 is null); Let us create a table − mysql> create table demo35 −> ( −> id int NOT NULL AUTO_INCREMENT PRIMARY KEY, −> joining_date date, −> relieving_date date −> ); Query OK, 0 rows affected (3.88 sec) Insert some records into the table with the help of insert command − mysql> insert into demo35(joining_date,relieving_date) values('2020−01−10','2020−07−11'); Query OK, 1 row affected (0.15 sec) mysql> insert into demo35(joining_date,relieving_date) values('2020−05−07','2020−12−08'); Query OK, 1 row affected (0.17 sec) mysql> insert into demo35(joining_date,relieving_date) values('2020−04−11','2020−09−18'); Query OK, 1 row affected (0.14 sec) mysql> insert into demo35(joining_date,relieving_date) values('2020−03−12','2020−10−01'); Query OK, 1 row affected (0.13 sec) Display records from the table using select statement − mysql> select *from demo35; This will produce the following output − +----+--------------+----------------+ | id | joining_date | relieving_date | +----+--------------+----------------+ | 1 | 2020−01−10 | 2020−07−11 | | 2 | 2020−05−07 | 2020−12−08 | | 3 | 2020−04−11 | 2020−09−18 | | 4 | 2020−03−12 | 2020−10−01 | +----+--------------+----------------+ 4 rows in set (0.00 sec) Following is the query to select date conditionally in MySQL − mysql> select *from demo35 −> where −> joining_date < '2020−05−11' AND −> (relieving_date > '2020−08−10' OR relieving_date is null); This will produce the following output − +----+--------------+----------------+ | id | joining_date | relieving_date | +----+--------------+----------------+ | 2 | 2020−05−07 | 2020−12−08 | | 3 | 2020−04−11 | 2020−09−18 | | 4 | 2020−03−12 | 2020−10−01 | +----+--------------+----------------+ 3 rows in set (0.00 sec)
[ { "code": null, "e": 1213, "s": 1187, "text": "Following is the syntax −" }, { "code": null, "e": 1338, "s": 1213, "text": "select *from yourTableName\nwhere\nyourColumnName1 < yourValue1 AND\n(yourColumnName2 > yourValue2 OR yourColumnName2 is null);" }, { "code": null, "e": 1362, "s": 1338, "text": "Let us create a table −" }, { "code": null, "e": 1529, "s": 1362, "text": "mysql> create table demo35\n−> (\n−> id int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n−> joining_date date,\n−> relieving_date date\n−> );\nQuery OK, 0 rows affected (3.88 sec)" }, { "code": null, "e": 1598, "s": 1529, "text": "Insert some records into the table with the help of insert command −" }, { "code": null, "e": 2102, "s": 1598, "text": "mysql> insert into demo35(joining_date,relieving_date) values('2020−01−10','2020−07−11');\nQuery OK, 1 row affected (0.15 sec)\nmysql> insert into demo35(joining_date,relieving_date) values('2020−05−07','2020−12−08');\nQuery OK, 1 row affected (0.17 sec)\nmysql> insert into demo35(joining_date,relieving_date) values('2020−04−11','2020−09−18');\nQuery OK, 1 row affected (0.14 sec)\nmysql> insert into demo35(joining_date,relieving_date) values('2020−03−12','2020−10−01');\nQuery OK, 1 row affected (0.13 sec)" }, { "code": null, "e": 2158, "s": 2102, "text": "Display records from the table using select statement −" }, { "code": null, "e": 2186, "s": 2158, "text": "mysql> select *from demo35;" }, { "code": null, "e": 2227, "s": 2186, "text": "This will produce the following output −" }, { "code": null, "e": 2564, "s": 2227, "text": "+----+--------------+----------------+\n| id | joining_date | relieving_date |\n+----+--------------+----------------+\n| 1 | 2020−01−10 | 2020−07−11 |\n| 2 | 2020−05−07 | 2020−12−08 |\n| 3 | 2020−04−11 | 2020−09−18 |\n| 4 | 2020−03−12 | 2020−10−01 |\n+----+--------------+----------------+\n4 rows in set (0.00 sec)" }, { "code": null, "e": 2627, "s": 2564, "text": "Following is the query to select date conditionally in MySQL −" }, { "code": null, "e": 2760, "s": 2627, "text": "mysql> select *from demo35\n−> where\n−> joining_date < '2020−05−11' AND\n−> (relieving_date > '2020−08−10' OR relieving_date is null);" }, { "code": null, "e": 2801, "s": 2760, "text": "This will produce the following output −" }, { "code": null, "e": 3099, "s": 2801, "text": "+----+--------------+----------------+\n| id | joining_date | relieving_date |\n+----+--------------+----------------+\n| 2 | 2020−05−07 | 2020−12−08 |\n| 3 | 2020−04−11 | 2020−09−18 |\n| 4 | 2020−03−12 | 2020−10−01 |\n+----+--------------+----------------+\n3 rows in set (0.00 sec)" } ]
How to fetch data from Database in PHP PDO using loop ?
30 May, 2022 The PDO (PHP Data Objects) defines the lightweight, consistent interface for accessing databases in PHP. Approach: Make sure you have XAMPP or WAMP installed on your windows machine. In case you’re using Linux then install the LAMP server. In this article, we will be using the XAMPP server. Follow the steps to fetch data from the Database in PHP PDO: 1. Create Database: Create a database using XAMPP, the database is named “geeksforgeeks” here. You can give any name to your database. create database “geeksforgeeks” 2. Create Table: Create a table named “fetch_record” with 2 columns to store the data. create table “fetch_record” 3. Create Table Structure: The table “fetch_record” contains 2 fields. id – primary key – auto increment studentname – varchar(100) The datatype for studentname is varchar. The size can be altered as per the requirement. However, 100 is sufficient, and the datatype for “id” is int and it is a primary key. Set the primary key to auto-increment, so that the value of id increase automatically. A primary key also called a primary keyword, is a key in a relational database that is unique for each record. It is a unique identifier, such as a driver’s license number, telephone number (including area code), or vehicle identification number (VIN). To create a table copy and paste the following code into the SQL panel of your PHPMyAdmin. DROP TABLE IF EXISTS `fetch_record`; CREATE TABLE IF NOT EXISTS `fetch_record` ( `id` int(11) NOT NULL AUTO_INCREMENT, `studentname` varchar(100) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1; To do this from SQL Panel refer to the following screenshot. create a table from SQL panel The structure of the table will look like this table structure 4. Insert student record: Here I have only taken the name and id of students. You can add more fields, according to your requirements. Copy and paste the following code into the SQL panel of your PHPMyAdmin. INSERT INTO `fetch_record` (`id`, `studentname`) VALUES (NULL, 'Neha'), (NULL, 'Honey'), (NULL, 'Amulaya Sharma'), (NULL, 'Kajal Singhal'), (NULL, 'Neeraj Pandey'), (NULL, 'Nikhil Kumar'); insert records After inserting the information, the table will look like this. table records 5. Create a folder “fetch”, that includes the two following files: The folder should be in “C:\xampp\htdocs\” (or where your XAMPP is installed). 5.1. index.php: Here foreach construct provides an easy way to iterate over arrays. foreach works only on arrays and objects and will issue an error when you try to use it on a variable with a different data type or an uninitialized variable. There are two syntaxes: foreach (array_expression as $value) statement foreach (array_expression as $key => $value) statement The following SQL query is used to fetch all data from the table. SELECT * FROM fetch_record; Example: HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content= "width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <title>Attendance Page</title></head> <body> <div class="container"> <div class="row"> <h2>Attendance</h2> <table class="table table-hover"> <thead> <tr> <th>Sno.</th> <th>Student Name</th> <th>Attendance</th> </tr> </thead> <tbody> <?php include_once('connection.php'); $a=1; $stmt = $conn->prepare( "SELECT * FROM fetch_record"); $stmt->execute(); $users = $stmt->fetchAll(); foreach($users as $user) { ?> <tr> <td> <?php echo $user['id']; ?> </td> <td> <?php echo $user['studentname']; ?> </td> <td> <div class="form-check form-check-inline"> <input class="form-check-input" type="radio" name="''" id="inlineRadio1" value="'..$a..'"> <label class="form-check-label" for="inlineRadio1">A</label> </div> <div class="form-check form-check-inline"> <input class="form-check-input" type="radio" name="'..$a..'" id="inlineRadio2" value="option2"> <label class="form-check-label" for="inlineRadio2">P</label> </div> </td> </tr> <?php } ?> </tbody> </table> <input class="btn btn-primary" type="submit" value="Submit"> </div> </div></body> </html> 5.2. connection.php: PHP <?php $conn = ""; try { $servername = "localhost:3306"; $dbname = "geeksforgeeks"; $username = "root"; $password = ""; $conn = new PDO( "mysql:host=$servername; dbname=geeksforgeeks", $username, $password ); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch(PDOException $e) { echo "Connection failed: " . $e->getMessage();} ?> 6. After completing all these steps, now do the following steps: Run XAMPPStart Apache server and MySQLType http://localhost/fetchData/dashboard.php in your browser. Run XAMPP Start Apache server and MySQL Type http://localhost/fetchData/dashboard.php in your browser. The table will look like this and that’s how you fetch the information from the Database in PHP PDO. PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples. sanjyotpanure Bootstrap-Misc CSS-Misc HTML-Misc PHP-Misc Bootstrap CSS HTML PHP PHP Programs Web Technologies Web technologies Questions HTML PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n30 May, 2022" }, { "code": null, "e": 160, "s": 54, "text": "The PDO (PHP Data Objects) defines the lightweight, consistent interface for accessing databases in PHP. " }, { "code": null, "e": 347, "s": 160, "text": "Approach: Make sure you have XAMPP or WAMP installed on your windows machine. In case you’re using Linux then install the LAMP server. In this article, we will be using the XAMPP server." }, { "code": null, "e": 409, "s": 347, "text": "Follow the steps to fetch data from the Database in PHP PDO: " }, { "code": null, "e": 545, "s": 409, "text": "1. Create Database: Create a database using XAMPP, the database is named “geeksforgeeks” here. You can give any name to your database. " }, { "code": null, "e": 577, "s": 545, "text": "create database “geeksforgeeks”" }, { "code": null, "e": 664, "s": 577, "text": "2. Create Table: Create a table named “fetch_record” with 2 columns to store the data." }, { "code": null, "e": 692, "s": 664, "text": "create table “fetch_record”" }, { "code": null, "e": 763, "s": 692, "text": "3. Create Table Structure: The table “fetch_record” contains 2 fields." }, { "code": null, "e": 797, "s": 763, "text": "id – primary key – auto increment" }, { "code": null, "e": 824, "s": 797, "text": "studentname – varchar(100)" }, { "code": null, "e": 1340, "s": 824, "text": "The datatype for studentname is varchar. The size can be altered as per the requirement. However, 100 is sufficient, and the datatype for “id” is int and it is a primary key. Set the primary key to auto-increment, so that the value of id increase automatically. A primary key also called a primary keyword, is a key in a relational database that is unique for each record. It is a unique identifier, such as a driver’s license number, telephone number (including area code), or vehicle identification number (VIN). " }, { "code": null, "e": 1431, "s": 1340, "text": "To create a table copy and paste the following code into the SQL panel of your PHPMyAdmin." }, { "code": null, "e": 1652, "s": 1431, "text": "DROP TABLE IF EXISTS `fetch_record`;\nCREATE TABLE IF NOT EXISTS `fetch_record` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `studentname` varchar(100) NOT NULL,\n PRIMARY KEY (`id`)\n) ENGINE=MyISAM DEFAULT CHARSET=latin1;" }, { "code": null, "e": 1713, "s": 1652, "text": "To do this from SQL Panel refer to the following screenshot." }, { "code": null, "e": 1743, "s": 1713, "text": "create a table from SQL panel" }, { "code": null, "e": 1791, "s": 1743, "text": "The structure of the table will look like this " }, { "code": null, "e": 1807, "s": 1791, "text": "table structure" }, { "code": null, "e": 1943, "s": 1807, "text": "4. Insert student record: Here I have only taken the name and id of students. You can add more fields, according to your requirements. " }, { "code": null, "e": 2016, "s": 1943, "text": "Copy and paste the following code into the SQL panel of your PHPMyAdmin." }, { "code": null, "e": 2206, "s": 2016, "text": "INSERT INTO `fetch_record` (`id`, `studentname`) VALUES (NULL, 'Neha'), (NULL, 'Honey'), (NULL, 'Amulaya Sharma'), \n(NULL, 'Kajal Singhal'), (NULL, 'Neeraj Pandey'), (NULL, 'Nikhil Kumar');" }, { "code": null, "e": 2221, "s": 2206, "text": "insert records" }, { "code": null, "e": 2286, "s": 2221, "text": "After inserting the information, the table will look like this. " }, { "code": null, "e": 2300, "s": 2286, "text": "table records" }, { "code": null, "e": 2447, "s": 2300, "text": "5. Create a folder “fetch”, that includes the two following files: The folder should be in “C:\\xampp\\htdocs\\” (or where your XAMPP is installed). " }, { "code": null, "e": 2714, "s": 2447, "text": "5.1. index.php: Here foreach construct provides an easy way to iterate over arrays. foreach works only on arrays and objects and will issue an error when you try to use it on a variable with a different data type or an uninitialized variable. There are two syntaxes:" }, { "code": null, "e": 2826, "s": 2714, "text": "foreach (array_expression as $value)\n statement\n\nforeach (array_expression as $key => $value)\n statement " }, { "code": null, "e": 2892, "s": 2826, "text": "The following SQL query is used to fetch all data from the table." }, { "code": null, "e": 2920, "s": 2892, "text": "SELECT * FROM fetch_record;" }, { "code": null, "e": 2930, "s": 2920, "text": "Example: " }, { "code": null, "e": 2935, "s": 2930, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\"> <meta http-equiv=\"X-UA-Compatible\" content=\"ie=edge\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"> <title>Attendance Page</title></head> <body> <div class=\"container\"> <div class=\"row\"> <h2>Attendance</h2> <table class=\"table table-hover\"> <thead> <tr> <th>Sno.</th> <th>Student Name</th> <th>Attendance</th> </tr> </thead> <tbody> <?php include_once('connection.php'); $a=1; $stmt = $conn->prepare( \"SELECT * FROM fetch_record\"); $stmt->execute(); $users = $stmt->fetchAll(); foreach($users as $user) { ?> <tr> <td> <?php echo $user['id']; ?> </td> <td> <?php echo $user['studentname']; ?> </td> <td> <div class=\"form-check form-check-inline\"> <input class=\"form-check-input\" type=\"radio\" name=\"''\" id=\"inlineRadio1\" value=\"'..$a..'\"> <label class=\"form-check-label\" for=\"inlineRadio1\">A</label> </div> <div class=\"form-check form-check-inline\"> <input class=\"form-check-input\" type=\"radio\" name=\"'..$a..'\" id=\"inlineRadio2\" value=\"option2\"> <label class=\"form-check-label\" for=\"inlineRadio2\">P</label> </div> </td> </tr> <?php } ?> </tbody> </table> <input class=\"btn btn-primary\" type=\"submit\" value=\"Submit\"> </div> </div></body> </html>", "e": 5588, "s": 2935, "text": null }, { "code": null, "e": 5610, "s": 5588, "text": "5.2. connection.php: " }, { "code": null, "e": 5614, "s": 5610, "text": "PHP" }, { "code": "<?php $conn = \"\"; try { $servername = \"localhost:3306\"; $dbname = \"geeksforgeeks\"; $username = \"root\"; $password = \"\"; $conn = new PDO( \"mysql:host=$servername; dbname=geeksforgeeks\", $username, $password ); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch(PDOException $e) { echo \"Connection failed: \" . $e->getMessage();} ?>", "e": 6034, "s": 5614, "text": null }, { "code": null, "e": 6099, "s": 6034, "text": "6. After completing all these steps, now do the following steps:" }, { "code": null, "e": 6200, "s": 6099, "text": "Run XAMPPStart Apache server and MySQLType http://localhost/fetchData/dashboard.php in your browser." }, { "code": null, "e": 6210, "s": 6200, "text": "Run XAMPP" }, { "code": null, "e": 6240, "s": 6210, "text": "Start Apache server and MySQL" }, { "code": null, "e": 6303, "s": 6240, "text": "Type http://localhost/fetchData/dashboard.php in your browser." }, { "code": null, "e": 6405, "s": 6303, "text": "The table will look like this and that’s how you fetch the information from the Database in PHP PDO. " }, { "code": null, "e": 6574, "s": 6405, "text": "PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples." }, { "code": null, "e": 6588, "s": 6574, "text": "sanjyotpanure" }, { "code": null, "e": 6603, "s": 6588, "text": "Bootstrap-Misc" }, { "code": null, "e": 6612, "s": 6603, "text": "CSS-Misc" }, { "code": null, "e": 6622, "s": 6612, "text": "HTML-Misc" }, { "code": null, "e": 6631, "s": 6622, "text": "PHP-Misc" }, { "code": null, "e": 6641, "s": 6631, "text": "Bootstrap" }, { "code": null, "e": 6645, "s": 6641, "text": "CSS" }, { "code": null, "e": 6650, "s": 6645, "text": "HTML" }, { "code": null, "e": 6654, "s": 6650, "text": "PHP" }, { "code": null, "e": 6667, "s": 6654, "text": "PHP Programs" }, { "code": null, "e": 6684, "s": 6667, "text": "Web Technologies" }, { "code": null, "e": 6711, "s": 6684, "text": "Web technologies Questions" }, { "code": null, "e": 6716, "s": 6711, "text": "HTML" }, { "code": null, "e": 6720, "s": 6716, "text": "PHP" } ]
Java Program to Find closest number in array
17 Jan, 2022 Given an array of sorted integers. We need to find the closest value to the given number. Array may contain duplicate values and negative numbers. Examples: Input : arr[] = {1, 2, 4, 5, 6, 6, 8, 9} Target number = 11 Output : 9 9 is closest to 11 in given array Input :arr[] = {2, 5, 6, 7, 8, 8, 9}; Target number = 4 Output : 5 A simple solution is to traverse through the given array and keep track of absolute difference of current element with every element. Finally return the element that has minimum absolution difference. An efficient solution is to use Binary Search. Java // Java program to find element closest to given target.import java.util.*;import java.lang.*;import java.io.*; class FindClosestNumber { // Returns element closest to target in arr[] public static int findClosest(int arr[], int target) { int n = arr.length; // Corner cases if (target <= arr[0]) return arr[0]; if (target >= arr[n - 1]) return arr[n - 1]; // Doing binary search int i = 0, j = n, mid = 0; while (i < j) { mid = (i + j) / 2; if (arr[mid] == target) return arr[mid]; /* If target is less than array element, then search in left */ if (target < arr[mid]) { // If target is greater than previous // to mid, return closest of two if (mid > 0 && target > arr[mid - 1]) return getClosest(arr[mid - 1], arr[mid], target); /* Repeat for left half */ j = mid; } // If target is greater than mid else { if (mid < n-1 && target < arr[mid + 1]) return getClosest(arr[mid], arr[mid + 1], target); i = mid + 1; // update i } } // Only single element left after search return arr[mid]; } // Method to compare which one is the more close // We find the closest by taking the difference // between the target and both values. It assumes // that val2 is greater than val1 and target lies // between these two. public static int getClosest(int val1, int val2, int target) { if (target - val1 >= val2 - target) return val2; else return val1; } // Driver code public static void main(String[] args) { int arr[] = { 1, 2, 4, 5, 6, 6, 8, 9 }; int target = 11; System.out.println(findClosest(arr, target)); }} Output: 9 Please refer complete article on Find closest number in array for more details! arorakashish0911 Binary Search Arrays Divide and Conquer Java Java Programs Searching Arrays Searching Divide and Conquer Java Binary Search Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Data Structures Window Sliding Technique Search, insert and delete in an unsorted array Chocolate Distribution Problem What is Data Structure: Types, Classifications and Applications Merge Sort QuickSort Binary Search Median of two sorted arrays of different sizes Program for Tower of Hanoi
[ { "code": null, "e": 28, "s": 0, "text": "\n17 Jan, 2022" }, { "code": null, "e": 176, "s": 28, "text": "Given an array of sorted integers. We need to find the closest value to the given number. Array may contain duplicate values and negative numbers. " }, { "code": null, "e": 188, "s": 176, "text": "Examples: " }, { "code": null, "e": 382, "s": 188, "text": "Input : arr[] = {1, 2, 4, 5, 6, 6, 8, 9}\n Target number = 11\nOutput : 9\n9 is closest to 11 in given array\n\nInput :arr[] = {2, 5, 6, 7, 8, 8, 9}; \n Target number = 4\nOutput : 5" }, { "code": null, "e": 583, "s": 382, "text": "A simple solution is to traverse through the given array and keep track of absolute difference of current element with every element. Finally return the element that has minimum absolution difference." }, { "code": null, "e": 632, "s": 583, "text": "An efficient solution is to use Binary Search. " }, { "code": null, "e": 637, "s": 632, "text": "Java" }, { "code": "// Java program to find element closest to given target.import java.util.*;import java.lang.*;import java.io.*; class FindClosestNumber { // Returns element closest to target in arr[] public static int findClosest(int arr[], int target) { int n = arr.length; // Corner cases if (target <= arr[0]) return arr[0]; if (target >= arr[n - 1]) return arr[n - 1]; // Doing binary search int i = 0, j = n, mid = 0; while (i < j) { mid = (i + j) / 2; if (arr[mid] == target) return arr[mid]; /* If target is less than array element, then search in left */ if (target < arr[mid]) { // If target is greater than previous // to mid, return closest of two if (mid > 0 && target > arr[mid - 1]) return getClosest(arr[mid - 1], arr[mid], target); /* Repeat for left half */ j = mid; } // If target is greater than mid else { if (mid < n-1 && target < arr[mid + 1]) return getClosest(arr[mid], arr[mid + 1], target); i = mid + 1; // update i } } // Only single element left after search return arr[mid]; } // Method to compare which one is the more close // We find the closest by taking the difference // between the target and both values. It assumes // that val2 is greater than val1 and target lies // between these two. public static int getClosest(int val1, int val2, int target) { if (target - val1 >= val2 - target) return val2; else return val1; } // Driver code public static void main(String[] args) { int arr[] = { 1, 2, 4, 5, 6, 6, 8, 9 }; int target = 11; System.out.println(findClosest(arr, target)); }}", "e": 2776, "s": 637, "text": null }, { "code": null, "e": 2785, "s": 2776, "text": "Output: " }, { "code": null, "e": 2787, "s": 2785, "text": "9" }, { "code": null, "e": 2868, "s": 2787, "text": "Please refer complete article on Find closest number in array for more details! " }, { "code": null, "e": 2885, "s": 2868, "text": "arorakashish0911" }, { "code": null, "e": 2899, "s": 2885, "text": "Binary Search" }, { "code": null, "e": 2906, "s": 2899, "text": "Arrays" }, { "code": null, "e": 2925, "s": 2906, "text": "Divide and Conquer" }, { "code": null, "e": 2930, "s": 2925, "text": "Java" }, { "code": null, "e": 2944, "s": 2930, "text": "Java Programs" }, { "code": null, "e": 2954, "s": 2944, "text": "Searching" }, { "code": null, "e": 2961, "s": 2954, "text": "Arrays" }, { "code": null, "e": 2971, "s": 2961, "text": "Searching" }, { "code": null, "e": 2990, "s": 2971, "text": "Divide and Conquer" }, { "code": null, "e": 2995, "s": 2990, "text": "Java" }, { "code": null, "e": 3009, "s": 2995, "text": "Binary Search" }, { "code": null, "e": 3107, "s": 3009, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3139, "s": 3107, "text": "Introduction to Data Structures" }, { "code": null, "e": 3164, "s": 3139, "text": "Window Sliding Technique" }, { "code": null, "e": 3211, "s": 3164, "text": "Search, insert and delete in an unsorted array" }, { "code": null, "e": 3242, "s": 3211, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 3306, "s": 3242, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 3317, "s": 3306, "text": "Merge Sort" }, { "code": null, "e": 3327, "s": 3317, "text": "QuickSort" }, { "code": null, "e": 3341, "s": 3327, "text": "Binary Search" }, { "code": null, "e": 3388, "s": 3341, "text": "Median of two sorted arrays of different sizes" } ]
Python | Layouts in layouts (Multiple Layouts) in Kivy
22 Sep, 2021 Kivy is a platform independent GUI tool in Python. As it can be run on Android, IOS, linux and Windows etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktops applications.In this article, we are going to discuss how we can use layouts in layouts basically multiple Layouts the most basic example of it. Most of the time we are able to use one layout but having difficulty to use multiple layouts. Kivy Tutorial – Learn Kivy with Examples. In kivy there are many Types of Layouts: AnchorLayout: Widgets can be anchored to the ‘top’, ‘bottom’, ‘left’, ‘right’ or ‘center’.BoxLayout: Widgets are arranged sequentially, in either a ‘vertical’ or a ‘horizontal’ orientation.FloatLayout: Widgets are essentially unrestricted.RelativeLayout: Child widgets are positioned relative to the layout.GridLayout: Widgets are arranged in a grid defined by the rows and cols properties.PageLayout: Used to create simple multi-page layouts, in a way that allows easy flipping from one page to another using borders.ScatterLayout: Widgets are positioned similarly to a RelativeLayout, but they can be translated, rotate and scaled.StackLayout: Widgets are stacked in a lr-tb (left to right then top to bottom) or tb-lr order. AnchorLayout: Widgets can be anchored to the ‘top’, ‘bottom’, ‘left’, ‘right’ or ‘center’. BoxLayout: Widgets are arranged sequentially, in either a ‘vertical’ or a ‘horizontal’ orientation. FloatLayout: Widgets are essentially unrestricted. RelativeLayout: Child widgets are positioned relative to the layout. GridLayout: Widgets are arranged in a grid defined by the rows and cols properties. PageLayout: Used to create simple multi-page layouts, in a way that allows easy flipping from one page to another using borders. ScatterLayout: Widgets are positioned similarly to a RelativeLayout, but they can be translated, rotate and scaled. StackLayout: Widgets are stacked in a lr-tb (left to right then top to bottom) or tb-lr order. Note:You can use as many as you can in a single file. Basic Approach to create multiple layouts in one file: 1) import kivy 2) import kivyApp 3) import BoxLayout 4) import 4) set minimum version(optional) 5) Extend the container class 6) set up .kv file : 7) create App class 8) return container class or layout 9) Run an instance of the class Implementation of the Approach –main.py file Note: If you were using .kv file to make multiple layouts There is no need to import Gridlayout, Boxlayout, AnchorLayout, FloatLayout, StackLayout, PageLayout, Button, etc. As .kv file supports all this as It has all this imported already. But if doing this without .kv file you must have to import these. Python3 ## Sample Python application demonstrating the## Program of How to use Multiple Layouts in Single file ######################################################################## # import kivy module import kivy # base Class of your App inherits from the App class. # app:always refers to the instance of your application from kivy.app import App # this restrict the kivy version i.e# below this kivy version you cannot# use the app or softwarekivy.require('1.9.0') # creates the button in kivy # if not imported shows the errorfrom kivy.uix.button import Button # BoxLayout arranges children in a vertical or horizontal box.# or help to put the childrens at the desired location.from kivy.uix.boxlayout import BoxLayout # The GridLayout arranges children in a matrix.# It takes the available space and# divides it into columns and rows,# then adds widgets to the resulting “cells”.from kivy.uix.gridlayout import GridLayout # The PageLayout class is used to create# a simple multi-page layout,# in a way that allows easy flipping from# one page to another using borders.from kivy.uix.pagelayout import PageLayout ######################################################################## # creating the root widget used in .kv fileclass MultipleLayout(PageLayout): pass ######################################################################## # creating the App class in which name#.kv file is to be named PageLayout.kvclass Multiple_LayoutApp(App): # defining build() def build(self): # returning the instance of root class return MultipleLayout() ######################################################################## # creating object of Multiple_LayoutApp() classMlApp = Multiple_LayoutApp() # run the classMlApp.run() In this file we are creating/using all the layout as it is Simpler to built/ use all these in .kv file .kv file of the code Python3 # Program of How to use Multiple Layouts in Single .kv file ######################################################################## # creating page Layout<PageLayout>: ######################################################################### # Creating Page 1 # Using BoxLayout inside PageLayout BoxLayout: # creating Canvas canvas: Color: rgba: 216 / 255., 195 / 255., 88 / 255., 1 Rectangle: pos: self.pos size: self.size # Providing orientation to the BoxLayout orientation: 'vertical' # Adding Label to Page 1 Label: size_hint_y: None height: 1.5 * self.texture_size[1] text: 'page 1' # Creating Button Button: text: 'GFG :)' # Adding On_press function # i.e binding function to press / touch on_press: print("This Is The First Page") ######################################################################### # Creating Page 2 BoxLayout: orientation: 'vertical' canvas: Color: rgba: 109 / 255., 8 / 255., 57 / 255., 1 Rectangle: pos: self.pos size: self.size Label: text: 'page 2' # This Image is directly from the websource # By using AsyncImage you can use that AsyncImage: source: 'http://kivy.org / logos / kivy-logo-black-64.png' ########################################################################## # Creating Page 3 # Using The Second Layout # Creating GridLayout GridLayout: canvas: Color: rgba: 37 / 255., 39 / 255., 30 / 255., 1 Rectangle: pos: self.pos size: self.size # Adding grids to Page 3 # It may be row or column cols: 2 # In first Grid # Adding Label + Image Label: text: 'page 3' AsyncImage: source: 'http://kivy.org/slides/kivyandroid-thumb.jpg' # In Second Grid # Adding Button + Image Button: text: 'Its User:):)' on_press: print("Heloo User This is the Last Page") AsyncImage: source: 'http://kivy.org/slides/kivypictures-thumb.jpg' # In third grid # Adding Widget + Image Widget AsyncImage: source: 'http://kivy.org/slides/particlepanda-thumb.jpg' Output:Image 1: Image 2: Image 3: Video Output: Reference: https://kivy.org/doc/stable/gettingstarted/layouts.html sweetyty kk9826225 simranarora5sos sagartomar9927 Python-gui Python-kivy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Different ways to create Pandas Dataframe Enumerate() in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Introduction To PYTHON Python OOPs Concepts Convert integer to string in Python Python | os.path.join() method
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Sep, 2021" }, { "code": null, "e": 489, "s": 28, "text": "Kivy is a platform independent GUI tool in Python. As it can be run on Android, IOS, linux and Windows etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktops applications.In this article, we are going to discuss how we can use layouts in layouts basically multiple Layouts the most basic example of it. Most of the time we are able to use one layout but having difficulty to use multiple layouts." }, { "code": null, "e": 531, "s": 489, "text": "Kivy Tutorial – Learn Kivy with Examples." }, { "code": null, "e": 574, "s": 531, "text": "In kivy there are many Types of Layouts: " }, { "code": null, "e": 1302, "s": 574, "text": "AnchorLayout: Widgets can be anchored to the ‘top’, ‘bottom’, ‘left’, ‘right’ or ‘center’.BoxLayout: Widgets are arranged sequentially, in either a ‘vertical’ or a ‘horizontal’ orientation.FloatLayout: Widgets are essentially unrestricted.RelativeLayout: Child widgets are positioned relative to the layout.GridLayout: Widgets are arranged in a grid defined by the rows and cols properties.PageLayout: Used to create simple multi-page layouts, in a way that allows easy flipping from one page to another using borders.ScatterLayout: Widgets are positioned similarly to a RelativeLayout, but they can be translated, rotate and scaled.StackLayout: Widgets are stacked in a lr-tb (left to right then top to bottom) or tb-lr order." }, { "code": null, "e": 1393, "s": 1302, "text": "AnchorLayout: Widgets can be anchored to the ‘top’, ‘bottom’, ‘left’, ‘right’ or ‘center’." }, { "code": null, "e": 1493, "s": 1393, "text": "BoxLayout: Widgets are arranged sequentially, in either a ‘vertical’ or a ‘horizontal’ orientation." }, { "code": null, "e": 1544, "s": 1493, "text": "FloatLayout: Widgets are essentially unrestricted." }, { "code": null, "e": 1613, "s": 1544, "text": "RelativeLayout: Child widgets are positioned relative to the layout." }, { "code": null, "e": 1697, "s": 1613, "text": "GridLayout: Widgets are arranged in a grid defined by the rows and cols properties." }, { "code": null, "e": 1826, "s": 1697, "text": "PageLayout: Used to create simple multi-page layouts, in a way that allows easy flipping from one page to another using borders." }, { "code": null, "e": 1942, "s": 1826, "text": "ScatterLayout: Widgets are positioned similarly to a RelativeLayout, but they can be translated, rotate and scaled." }, { "code": null, "e": 2037, "s": 1942, "text": "StackLayout: Widgets are stacked in a lr-tb (left to right then top to bottom) or tb-lr order." }, { "code": null, "e": 2091, "s": 2037, "text": "Note:You can use as many as you can in a single file." }, { "code": null, "e": 2148, "s": 2091, "text": "Basic Approach to create multiple layouts in one file: " }, { "code": null, "e": 2384, "s": 2148, "text": "1) import kivy\n2) import kivyApp\n3) import BoxLayout\n4) import \n4) set minimum version(optional)\n5) Extend the container class\n6) set up .kv file :\n7) create App class\n8) return container class or layout\n9) Run an instance of the class" }, { "code": null, "e": 2429, "s": 2384, "text": "Implementation of the Approach –main.py file" }, { "code": null, "e": 2736, "s": 2429, "text": "Note: If you were using .kv file to make multiple layouts There is no need to import Gridlayout, Boxlayout, AnchorLayout, FloatLayout, StackLayout, PageLayout, Button, etc. As .kv file supports all this as It has all this imported already. But if doing this without .kv file you must have to import these. " }, { "code": null, "e": 2744, "s": 2736, "text": "Python3" }, { "code": "## Sample Python application demonstrating the## Program of How to use Multiple Layouts in Single file ######################################################################## # import kivy module import kivy # base Class of your App inherits from the App class. # app:always refers to the instance of your application from kivy.app import App # this restrict the kivy version i.e# below this kivy version you cannot# use the app or softwarekivy.require('1.9.0') # creates the button in kivy # if not imported shows the errorfrom kivy.uix.button import Button # BoxLayout arranges children in a vertical or horizontal box.# or help to put the childrens at the desired location.from kivy.uix.boxlayout import BoxLayout # The GridLayout arranges children in a matrix.# It takes the available space and# divides it into columns and rows,# then adds widgets to the resulting “cells”.from kivy.uix.gridlayout import GridLayout # The PageLayout class is used to create# a simple multi-page layout,# in a way that allows easy flipping from# one page to another using borders.from kivy.uix.pagelayout import PageLayout ######################################################################## # creating the root widget used in .kv fileclass MultipleLayout(PageLayout): pass ######################################################################## # creating the App class in which name#.kv file is to be named PageLayout.kvclass Multiple_LayoutApp(App): # defining build() def build(self): # returning the instance of root class return MultipleLayout() ######################################################################## # creating object of Multiple_LayoutApp() classMlApp = Multiple_LayoutApp() # run the classMlApp.run()", "e": 4499, "s": 2744, "text": null }, { "code": null, "e": 4623, "s": 4499, "text": "In this file we are creating/using all the layout as it is Simpler to built/ use all these in .kv file .kv file of the code" }, { "code": null, "e": 4631, "s": 4623, "text": "Python3" }, { "code": "# Program of How to use Multiple Layouts in Single .kv file ######################################################################## # creating page Layout<PageLayout>: ######################################################################### # Creating Page 1 # Using BoxLayout inside PageLayout BoxLayout: # creating Canvas canvas: Color: rgba: 216 / 255., 195 / 255., 88 / 255., 1 Rectangle: pos: self.pos size: self.size # Providing orientation to the BoxLayout orientation: 'vertical' # Adding Label to Page 1 Label: size_hint_y: None height: 1.5 * self.texture_size[1] text: 'page 1' # Creating Button Button: text: 'GFG :)' # Adding On_press function # i.e binding function to press / touch on_press: print(\"This Is The First Page\") ######################################################################### # Creating Page 2 BoxLayout: orientation: 'vertical' canvas: Color: rgba: 109 / 255., 8 / 255., 57 / 255., 1 Rectangle: pos: self.pos size: self.size Label: text: 'page 2' # This Image is directly from the websource # By using AsyncImage you can use that AsyncImage: source: 'http://kivy.org / logos / kivy-logo-black-64.png' ########################################################################## # Creating Page 3 # Using The Second Layout # Creating GridLayout GridLayout: canvas: Color: rgba: 37 / 255., 39 / 255., 30 / 255., 1 Rectangle: pos: self.pos size: self.size # Adding grids to Page 3 # It may be row or column cols: 2 # In first Grid # Adding Label + Image Label: text: 'page 3' AsyncImage: source: 'http://kivy.org/slides/kivyandroid-thumb.jpg' # In Second Grid # Adding Button + Image Button: text: 'Its User:):)' on_press: print(\"Heloo User This is the Last Page\") AsyncImage: source: 'http://kivy.org/slides/kivypictures-thumb.jpg' # In third grid # Adding Widget + Image Widget AsyncImage: source: 'http://kivy.org/slides/particlepanda-thumb.jpg'", "e": 7171, "s": 4631, "text": null }, { "code": null, "e": 7188, "s": 7171, "text": "Output:Image 1: " }, { "code": null, "e": 7198, "s": 7188, "text": "Image 2: " }, { "code": null, "e": 7208, "s": 7198, "text": "Image 3: " }, { "code": null, "e": 7223, "s": 7208, "text": "Video Output: " }, { "code": null, "e": 7293, "s": 7223, "text": " Reference: https://kivy.org/doc/stable/gettingstarted/layouts.html " }, { "code": null, "e": 7302, "s": 7293, "text": "sweetyty" }, { "code": null, "e": 7312, "s": 7302, "text": "kk9826225" }, { "code": null, "e": 7328, "s": 7312, "text": "simranarora5sos" }, { "code": null, "e": 7343, "s": 7328, "text": "sagartomar9927" }, { "code": null, "e": 7354, "s": 7343, "text": "Python-gui" }, { "code": null, "e": 7366, "s": 7354, "text": "Python-kivy" }, { "code": null, "e": 7373, "s": 7366, "text": "Python" }, { "code": null, "e": 7471, "s": 7373, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7513, "s": 7471, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 7535, "s": 7513, "text": "Enumerate() in Python" }, { "code": null, "e": 7561, "s": 7535, "text": "Python String | replace()" }, { "code": null, "e": 7593, "s": 7561, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 7622, "s": 7593, "text": "*args and **kwargs in Python" }, { "code": null, "e": 7649, "s": 7622, "text": "Python Classes and Objects" }, { "code": null, "e": 7672, "s": 7649, "text": "Introduction To PYTHON" }, { "code": null, "e": 7693, "s": 7672, "text": "Python OOPs Concepts" }, { "code": null, "e": 7729, "s": 7693, "text": "Convert integer to string in Python" } ]
Using Iterations in Python Effectively
07 Jul, 2022 Prerequisite : Iterators in Python Following are different ways to use iterators. C-style approach:This approach requires prior knowledge of total number of iterations. Python # A C-style way of accessing list elementscars = ["Aston", "Audi", "McLaren"]i = 0while (i < len(cars)): print cars[i] i += 1 Output: Aston Audi McLaren Important Points: This style of looping is rarely used by python programmers. This 4-step approach creates no compactness with single-view looping construct. This is also prone to errors in large-scale programs or designs. There is no C-Style for loop in Python, i.e., a loop like for (int i=0; i<n; i++) Use of for-in (or for each) style: This style is used in python containing iterator of lists, dictionary, n dimensional-arrays etc. The iterator fetches each component and prints data while looping. The iterator is automatically incremented/decremented in this construct. Python # Accessing items using for-in loop cars = ["Aston", "Audi", "McLaren"]for x in cars: print x Output: Aston Audi McLaren See this for more examples of different data types. Indexing using Range function: We can also use indexing using range() in Python. Python # Accessing items using indexes and for-in cars = ["Aston", "Audi", "McLaren"]for i in range(len(cars)): print cars[i] Output: Aston Audi McLaren Enumerate: Enumerate is built-in python function that takes input as iterator, list etc and returns a tuple containing index and data at that index in the iterator sequence. For example, enumerate(cars), returns a iterator that will return (0, cars[0]), (1, cars[1]), (2, cars[2]), and so on. Python # Accessing items using enumerate() cars = ["Aston" , "Audi", "McLaren "]for i, x in enumerate(cars): print (x) Output : Aston Audi McLaren Below solution also works. Python # Accessing items and indexes enumerate() cars = ["Aston" , "Audi", "McLaren "]for x in enumerate(cars): print (x[0], x[1]) Output : (0, 'Aston') (1, 'Audi') (2, 'McLaren ') We can also directly print returned value of enumerate() to see what it returns. Python # Printing return value of enumerate() cars = ["Aston" , "Audi", "McLaren "]print enumerate(cars) Output : [(0, 'Aston'), (1, 'Audi'), (2, 'McLaren ')] Enumerate takes parameter start which is default set to zero. We can change this parameter to any value we like. In the below code we have used start as 1. Python # demonstrating the use of start in enumerate cars = ["Aston" , "Audi", "McLaren "]for x in enumerate(cars, start=1): print (x[0], x[1]) Output : (1, 'Aston') (2, 'Audi') (3, 'McLaren ') enumerate() helps to embed solution for accessing each data item in the iterator and fetching index of each data item. Looping extensions: i) Two iterators for a single looping construct: In this case, a list and dictionary are to be used for each iteration in a single looping block using enumerate function. Let us see example. Python # Two separate listscars = ["Aston", "Audi", "McLaren"]accessories = ["GPS kit", "Car repair-tool kit"] # Single dictionary holds prices of cars and# its accessories.# First three items store prices of cars and# next two items store prices of accessories.prices = {1:"570000$", 2:"68000$", 3:"450000$", 4:"8900$", 5:"4500$"} # Printing prices of carsfor index, c in enumerate(cars, start=1): print "Car: %s Price: %s"%(c, prices[index]) # Printing prices of accessoriesfor index, a in enumerate(accessories,start=1): print ("Accessory: %s Price: %s"\ %(a,prices[index+len(cars)])) Output: Car: Aston Price: 570000$ Car: Audi Price: 68000$ Car: McLaren Price: 450000$ Accessory: GPS kit Price: 8900$ Accessory: Car repair-tool kit Price: 4500$ ii) zip function (Both iterators to be used in single looping construct): This function is helpful to combine similar type iterators(list-list or dict- dict etc,) data items at ith position. It uses the shortest length of these input iterators. Other items of larger length iterators are skipped. In case of empty iterators, it returns No output. For example, the use of zip for two lists (iterators) helped to combine a single car and its required accessory. Python # Python program to demonstrate the working of zip # Two separate listscars = ["Aston", "Audi", "McLaren"]accessories = ["GPS", "Car Repair Kit", "Dolby sound kit"] # Combining lists and printingfor c, a in zip(cars, accessories): print "Car: %s, Accessory required: %s"\ %(c, a) Output: Car: Aston, Accessory required: GPS Car: Audi, Accessory required: Car Repair Kit Car: McLaren, Accessory required: Dolby sound kit The reverse of these iterators from zip function is known as unzipping using “*” operator. Use of enumerate function and zip function helps to achieve an effective extension of iteration logic in python and solves many more sub-problems of a huge task or problem. Python # Python program to demonstrate unzip (reverse# of zip)using * with zip function # Unzip listsl1,l2 = zip(*[('Aston', 'GPS'), ('Audi', 'Car Repair'), ('McLaren', 'Dolby sound kit') ]) # Printing unzipped lists print(l1)print(l2) Output: ('Aston', 'Audi', 'McLaren') ('GPS', 'Car Repair', 'Dolby sound kit') PRIYESH PATEL 1 simmytarika5 ashishbhaskar0123 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 Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Convert integer to string in Python Python OOPs Concepts Introduction To PYTHON Python | os.path.join() method
[ { "code": null, "e": 52, "s": 24, "text": "\n07 Jul, 2022" }, { "code": null, "e": 135, "s": 52, "text": "Prerequisite : Iterators in Python Following are different ways to use iterators. " }, { "code": null, "e": 223, "s": 135, "text": "C-style approach:This approach requires prior knowledge of total number of iterations. " }, { "code": null, "e": 230, "s": 223, "text": "Python" }, { "code": "# A C-style way of accessing list elementscars = [\"Aston\", \"Audi\", \"McLaren\"]i = 0while (i < len(cars)): print cars[i] i += 1", "e": 362, "s": 230, "text": null }, { "code": null, "e": 370, "s": 362, "text": "Output:" }, { "code": null, "e": 391, "s": 370, "text": "Aston\nAudi \nMcLaren " }, { "code": null, "e": 409, "s": 391, "text": "Important Points:" }, { "code": null, "e": 469, "s": 409, "text": "This style of looping is rarely used by python programmers." }, { "code": null, "e": 549, "s": 469, "text": "This 4-step approach creates no compactness with single-view looping construct." }, { "code": null, "e": 614, "s": 549, "text": "This is also prone to errors in large-scale programs or designs." }, { "code": null, "e": 696, "s": 614, "text": "There is no C-Style for loop in Python, i.e., a loop like for (int i=0; i<n; i++)" }, { "code": null, "e": 971, "s": 696, "text": " Use of for-in (or for each) style: This style is used in python containing iterator of lists, dictionary, n dimensional-arrays etc. The iterator fetches each component and prints data while looping. The iterator is automatically incremented/decremented in this construct. " }, { "code": null, "e": 978, "s": 971, "text": "Python" }, { "code": "# Accessing items using for-in loop cars = [\"Aston\", \"Audi\", \"McLaren\"]for x in cars: print x", "e": 1075, "s": 978, "text": null }, { "code": null, "e": 1083, "s": 1075, "text": "Output:" }, { "code": null, "e": 1104, "s": 1083, "text": "Aston\nAudi \nMcLaren " }, { "code": null, "e": 1238, "s": 1104, "text": "See this for more examples of different data types. Indexing using Range function: We can also use indexing using range() in Python. " }, { "code": null, "e": 1245, "s": 1238, "text": "Python" }, { "code": "# Accessing items using indexes and for-in cars = [\"Aston\", \"Audi\", \"McLaren\"]for i in range(len(cars)): print cars[i]", "e": 1367, "s": 1245, "text": null }, { "code": null, "e": 1375, "s": 1367, "text": "Output:" }, { "code": null, "e": 1396, "s": 1375, "text": "Aston\nAudi \nMcLaren " }, { "code": null, "e": 1692, "s": 1396, "text": " Enumerate: Enumerate is built-in python function that takes input as iterator, list etc and returns a tuple containing index and data at that index in the iterator sequence. For example, enumerate(cars), returns a iterator that will return (0, cars[0]), (1, cars[1]), (2, cars[2]), and so on. " }, { "code": null, "e": 1699, "s": 1692, "text": "Python" }, { "code": "# Accessing items using enumerate() cars = [\"Aston\" , \"Audi\", \"McLaren \"]for i, x in enumerate(cars): print (x)", "e": 1814, "s": 1699, "text": null }, { "code": null, "e": 1823, "s": 1814, "text": "Output :" }, { "code": null, "e": 1843, "s": 1823, "text": "Aston\nAudi\nMcLaren " }, { "code": null, "e": 1871, "s": 1843, "text": "Below solution also works. " }, { "code": null, "e": 1878, "s": 1871, "text": "Python" }, { "code": "# Accessing items and indexes enumerate() cars = [\"Aston\" , \"Audi\", \"McLaren \"]for x in enumerate(cars): print (x[0], x[1])", "e": 2005, "s": 1878, "text": null }, { "code": null, "e": 2014, "s": 2005, "text": "Output :" }, { "code": null, "e": 2055, "s": 2014, "text": "(0, 'Aston')\n(1, 'Audi')\n(2, 'McLaren ')" }, { "code": null, "e": 2137, "s": 2055, "text": "We can also directly print returned value of enumerate() to see what it returns. " }, { "code": null, "e": 2144, "s": 2137, "text": "Python" }, { "code": "# Printing return value of enumerate() cars = [\"Aston\" , \"Audi\", \"McLaren \"]print enumerate(cars)", "e": 2242, "s": 2144, "text": null }, { "code": null, "e": 2251, "s": 2242, "text": "Output :" }, { "code": null, "e": 2296, "s": 2251, "text": "[(0, 'Aston'), (1, 'Audi'), (2, 'McLaren ')]" }, { "code": null, "e": 2453, "s": 2296, "text": "Enumerate takes parameter start which is default set to zero. We can change this parameter to any value we like. In the below code we have used start as 1. " }, { "code": null, "e": 2460, "s": 2453, "text": "Python" }, { "code": "# demonstrating the use of start in enumerate cars = [\"Aston\" , \"Audi\", \"McLaren \"]for x in enumerate(cars, start=1): print (x[0], x[1])", "e": 2600, "s": 2460, "text": null }, { "code": null, "e": 2609, "s": 2600, "text": "Output :" }, { "code": null, "e": 2650, "s": 2609, "text": "(1, 'Aston')\n(2, 'Audi')\n(3, 'McLaren ')" }, { "code": null, "e": 2769, "s": 2650, "text": "enumerate() helps to embed solution for accessing each data item in the iterator and fetching index of each data item." }, { "code": null, "e": 2982, "s": 2769, "text": " Looping extensions: i) Two iterators for a single looping construct: In this case, a list and dictionary are to be used for each iteration in a single looping block using enumerate function. Let us see example." }, { "code": null, "e": 2989, "s": 2982, "text": "Python" }, { "code": "# Two separate listscars = [\"Aston\", \"Audi\", \"McLaren\"]accessories = [\"GPS kit\", \"Car repair-tool kit\"] # Single dictionary holds prices of cars and# its accessories.# First three items store prices of cars and# next two items store prices of accessories.prices = {1:\"570000$\", 2:\"68000$\", 3:\"450000$\", 4:\"8900$\", 5:\"4500$\"} # Printing prices of carsfor index, c in enumerate(cars, start=1): print \"Car: %s Price: %s\"%(c, prices[index]) # Printing prices of accessoriesfor index, a in enumerate(accessories,start=1): print (\"Accessory: %s Price: %s\"\\ %(a,prices[index+len(cars)]))", "e": 3595, "s": 2989, "text": null }, { "code": null, "e": 3603, "s": 3595, "text": "Output:" }, { "code": null, "e": 3757, "s": 3603, "text": "Car: Aston Price: 570000$\nCar: Audi Price: 68000$\nCar: McLaren Price: 450000$\nAccessory: GPS kit Price: 8900$\nAccessory: Car repair-tool kit Price: 4500$" }, { "code": null, "e": 4104, "s": 3757, "text": "ii) zip function (Both iterators to be used in single looping construct): This function is helpful to combine similar type iterators(list-list or dict- dict etc,) data items at ith position. It uses the shortest length of these input iterators. Other items of larger length iterators are skipped. In case of empty iterators, it returns No output." }, { "code": null, "e": 4218, "s": 4104, "text": "For example, the use of zip for two lists (iterators) helped to combine a single car and its required accessory. " }, { "code": null, "e": 4225, "s": 4218, "text": "Python" }, { "code": "# Python program to demonstrate the working of zip # Two separate listscars = [\"Aston\", \"Audi\", \"McLaren\"]accessories = [\"GPS\", \"Car Repair Kit\", \"Dolby sound kit\"] # Combining lists and printingfor c, a in zip(cars, accessories): print \"Car: %s, Accessory required: %s\"\\ %(c, a)", "e": 4531, "s": 4225, "text": null }, { "code": null, "e": 4539, "s": 4531, "text": "Output:" }, { "code": null, "e": 4671, "s": 4539, "text": "Car: Aston, Accessory required: GPS\nCar: Audi, Accessory required: Car Repair Kit\nCar: McLaren, Accessory required: Dolby sound kit" }, { "code": null, "e": 4936, "s": 4671, "text": "The reverse of these iterators from zip function is known as unzipping using “*” operator. Use of enumerate function and zip function helps to achieve an effective extension of iteration logic in python and solves many more sub-problems of a huge task or problem. " }, { "code": null, "e": 4943, "s": 4936, "text": "Python" }, { "code": "# Python program to demonstrate unzip (reverse# of zip)using * with zip function # Unzip listsl1,l2 = zip(*[('Aston', 'GPS'), ('Audi', 'Car Repair'), ('McLaren', 'Dolby sound kit') ]) # Printing unzipped lists print(l1)print(l2)", "e": 5212, "s": 4943, "text": null }, { "code": null, "e": 5220, "s": 5212, "text": "Output:" }, { "code": null, "e": 5290, "s": 5220, "text": "('Aston', 'Audi', 'McLaren')\n('GPS', 'Car Repair', 'Dolby sound kit')" }, { "code": null, "e": 5306, "s": 5290, "text": "PRIYESH PATEL 1" }, { "code": null, "e": 5319, "s": 5306, "text": "simmytarika5" }, { "code": null, "e": 5337, "s": 5319, "text": "ashishbhaskar0123" }, { "code": null, "e": 5344, "s": 5337, "text": "Python" }, { "code": null, "e": 5442, "s": 5344, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5460, "s": 5442, "text": "Python Dictionary" }, { "code": null, "e": 5502, "s": 5460, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 5528, "s": 5502, "text": "Python String | replace()" }, { "code": null, "e": 5560, "s": 5528, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 5589, "s": 5560, "text": "*args and **kwargs in Python" }, { "code": null, "e": 5616, "s": 5589, "text": "Python Classes and Objects" }, { "code": null, "e": 5652, "s": 5616, "text": "Convert integer to string in Python" }, { "code": null, "e": 5673, "s": 5652, "text": "Python OOPs Concepts" }, { "code": null, "e": 5696, "s": 5673, "text": "Introduction To PYTHON" } ]
Prim’s algorithm using priority_queue in STL
30 Jun, 2022 Given an undirected, connected and weighted graph, find Minimum Spanning Tree (MST) of the graph using Prim’s algorithm. Input : Adjacency List representation of above graph Output : Edges in MST 0 - 1 1 - 2 2 - 3 3 - 4 2 - 5 5 - 6 6 - 7 2 - 8 Note: There are two possible MSTs, the other MST includes edge 0-7 in place of 1-2. We have discussed below Prim’s MST implementations. Prim’s Algorithm for Adjacency Matrix Representation (In C/C++ with time complexity O(v2) Prim’s Algorithm for Adjacency List Representation (In C with Time Complexity O(ELogV)) The second implementation is time complexity wise better, but is really complex as we have implemented our own priority queue. STL provides priority_queue, but the provided priority queue doesn’t support decrease key operation. And in Prim’s algorithm, we need a priority queue and below operations on priority queue : ExtractMin : from all those vertices which have not yet been included in MST, we need to get vertex with minimum key value. DecreaseKey : After extracting vertex we need to update keys of its adjacent vertices, and if new key is smaller, then update that in data structure. The algorithm discussed here can be modified so that decrease key is never required. The idea is, not to insert all vertices in priority queue, but only those which are not MST and have been visited through a vertex that has included in MST. We keep track of vertices included in MST in a separate boolean array inMST[]. 1) Initialize keys of all vertices as infinite and parent of every vertex as -1. 2) Create an empty priority_queue pq. Every item of pq is a pair (weight, vertex). Weight (or key) is used as first item of pair as first item is by default used to compare two pairs. 3) Initialize all vertices as not part of MST yet. We use boolean array inMST[] for this purpose. This array is required to make sure that an already considered vertex is not included in pq again. This is where Prim's implementation differs from Dijkstra. In Dijkstra's algorithm, we didn't need this array as distances always increase. We require this array here because key value of a processed vertex may decrease if not checked. 4) Insert source vertex into pq and make its key as 0. 5) While either pq doesn't become empty a) Extract minimum key vertex from pq. Let the extracted vertex be u. b) Include u in MST using inMST[u] = true. c) Loop through all adjacent of u and do following for every vertex v. // If weight of edge (u,v) is smaller than // key of v and v is not already in MST If inMST[v] = false && key[v] > weight(u, v) (i) Update key of v, i.e., do key[v] = weight(u, v) (ii) Insert v into the pq (iv) parent[v] = u 6) Print MST edges using parent array. Below is C++ implementation of above idea. C++ // STL implementation of Prim's algorithm for MST#include<bits/stdc++.h>using namespace std;# define INF 0x3f3f3f3f // iPair ==> Integer Pairtypedef pair<int, int> iPair; // This class represents a directed graph using// adjacency list representationclass Graph{ int V; // No. of vertices // In a weighted graph, we need to store vertex // and weight pair for every edge list< pair<int, int> > *adj; public: Graph(int V); // Constructor // function to add an edge to graph void addEdge(int u, int v, int w); // Print MST using Prim's algorithm void primMST();}; // Allocates memory for adjacency listGraph::Graph(int V){ this->V = V; adj = new list<iPair> [V];} void Graph::addEdge(int u, int v, int w){ adj[u].push_back(make_pair(v, w)); adj[v].push_back(make_pair(u, w));} // Prints shortest paths from src to all other verticesvoid Graph::primMST(){ // Create a priority queue to store vertices that // are being primMST. This is weird syntax in C++. // Refer below link for details of this syntax // http://geeksquiz.com/implement-min-heap-using-stl/ priority_queue< iPair, vector <iPair> , greater<iPair> > pq; int src = 0; // Taking vertex 0 as source // Create a vector for keys and initialize all // keys as infinite (INF) vector<int> key(V, INF); // To store parent array which in turn store MST vector<int> parent(V, -1); // To keep track of vertices included in MST vector<bool> inMST(V, false); // Insert source itself in priority queue and initialize // its key as 0. pq.push(make_pair(0, src)); key[src] = 0; /* Looping till priority queue becomes empty */ while (!pq.empty()) { // The first vertex in pair is the minimum key // vertex, extract it from priority queue. // vertex label is stored in second of pair (it // has to be done this way to keep the vertices // sorted key (key must be first item // in pair) int u = pq.top().second; pq.pop(); //Different key values for same vertex may exist in the priority queue. //The one with the least key value is always processed first. //Therefore, ignore the rest. if(inMST[u] == true){ continue; } inMST[u] = true; // Include vertex in MST // 'i' is used to get all adjacent vertices of a vertex list< pair<int, int> >::iterator i; for (i = adj[u].begin(); i != adj[u].end(); ++i) { // Get vertex label and weight of current adjacent // of u. int v = (*i).first; int weight = (*i).second; // If v is not in MST and weight of (u,v) is smaller // than current key of v if (inMST[v] == false && key[v] > weight) { // Updating key of v key[v] = weight; pq.push(make_pair(key[v], v)); parent[v] = u; } } } // Print edges of MST using parent array for (int i = 1; i < V; ++i) printf("%d - %d\n", parent[i], i);} // Driver program to test methods of graph classint main(){ // create the graph given in above figure int V = 9; Graph g(V); // making above shown graph g.addEdge(0, 1, 4); g.addEdge(0, 7, 8); g.addEdge(1, 2, 8); g.addEdge(1, 7, 11); g.addEdge(2, 3, 7); g.addEdge(2, 8, 2); g.addEdge(2, 5, 4); g.addEdge(3, 4, 9); g.addEdge(3, 5, 14); g.addEdge(4, 5, 10); g.addEdge(5, 6, 2); g.addEdge(6, 7, 1); g.addEdge(6, 8, 6); g.addEdge(7, 8, 7); g.primMST(); return 0;} 0 - 1 1 - 2 2 - 3 3 - 4 2 - 5 5 - 6 6 - 7 2 - 8 Time complexity : O(E Log V)) A Quicker Implementation using array of vectors representation of a weighted graph : C++ // STL implementation of Prim's algorithm for MST#include<bits/stdc++.h>using namespace std;# define INF 0x3f3f3f3f // iPair ==> Integer Pairtypedef pair<int, int> iPair; // To add an edgevoid addEdge(vector <pair<int, int> > adj[], int u, int v, int wt){ adj[u].push_back(make_pair(v, wt)); adj[v].push_back(make_pair(u, wt));} // Prints shortest paths from src to all other verticesvoid primMST(vector<pair<int,int> > adj[], int V){ // Create a priority queue to store vertices that // are being primMST. This is weird syntax in C++. // Refer below link for details of this syntax // http://geeksquiz.com/implement-min-heap-using-stl/ priority_queue< iPair, vector <iPair> , greater<iPair> > pq; int src = 0; // Taking vertex 0 as source // Create a vector for keys and initialize all // keys as infinite (INF) vector<int> key(V, INF); // To store parent array which in turn store MST vector<int> parent(V, -1); // To keep track of vertices included in MST vector<bool> inMST(V, false); // Insert source itself in priority queue and initialize // its key as 0. pq.push(make_pair(0, src)); key[src] = 0; /* Looping till priority queue becomes empty */ while (!pq.empty()) { // The first vertex in pair is the minimum key // vertex, extract it from priority queue. // vertex label is stored in second of pair (it // has to be done this way to keep the vertices // sorted key (key must be first item // in pair) int u = pq.top().second; pq.pop(); //Different key values for same vertex may exist in the priority queue. //The one with the least key value is always processed first. //Therefore, ignore the rest. if(inMST[u] == true){ continue; } inMST[u] = true; // Include vertex in MST // Traverse all adjacent of u for (auto x : adj[u]) { // Get vertex label and weight of current adjacent // of u. int v = x.first; int weight = x.second; // If v is not in MST and weight of (u,v) is smaller // than current key of v if (inMST[v] == false && key[v] > weight) { // Updating key of v key[v] = weight; pq.push(make_pair(key[v], v)); parent[v] = u; } } } // Print edges of MST using parent array for (int i = 1; i < V; ++i) printf("%d - %d\n", parent[i], i);} // Driver program to test methods of graph classint main(){ int V = 9; vector<iPair > adj[V]; // making above shown graph addEdge(adj, 0, 1, 4); addEdge(adj, 0, 7, 8); addEdge(adj, 1, 2, 8); addEdge(adj, 1, 7, 11); addEdge(adj, 2, 3, 7); addEdge(adj, 2, 8, 2); addEdge(adj, 2, 5, 4); addEdge(adj, 3, 4, 9); addEdge(adj, 3, 5, 14); addEdge(adj, 4, 5, 10); addEdge(adj, 5, 6, 2); addEdge(adj, 6, 7, 1); addEdge(adj, 6, 8, 6); addEdge(adj, 7, 8, 7); primMST(adj, V); return 0;} 0 - 1 1 - 2 2 - 3 3 - 4 2 - 5 5 - 6 6 - 7 2 - 8 Note: Like Dijkstra’s priority_queue implementation, we may have multiple entries for same vertex as we do not (and we can not) make isMST[v] = true in if condition. C++ Java Python3 C# Javascript // If v is not in MST and weight of (u,v) is smaller // than current key of v if (inMST[v] == false && key[v] > weight) { // Updating key of v key[v] = weight; pq.push(make_pair(key[v], v)); parent[v] = u;} // If v is not in MST and weight of (u,v) is smaller// than current key of v if (inMST[v] == false && key[v] > weight){ // Updating key of v key[v] = weight; pq.add(new Pair<Integer, Integer>(key[v], v)); parent[v] = u;} // This code is contributed by avanitrachhadiya2155 # If v is not in MST and weight of (u,v) is smaller# than current key of v if (inMST[v] == False and key[v] > weight) : # Updating key of v key[v] = weight pq.append([key[v], v]) parent[v] = u # This code is contributed by divyeshrabadiya07. // If v is not in MST and weight of (u,v) is smaller// than current key of v if (inMST[v] == false && key[v] > weight){ // Updating key of v key[v] = weight; pq.Add(new Tuple<int,int>(key[v], v)); parent[v] = u;} // This code is contributed by divyesh072019. <script> // If v is not in MST and weight of (u,v)// is smaller than current key of vif (inMST[v] == false && key[v] > weight){ // Updating key of v key[v] = weight; value = [key[v], v]; pq.push(value); parent[v] = u;} // This code is contributed by suresh07 </script> But as explained in Dijkstra’s algorithm, time complexity remains O(E Log V) as there will be at most O(E) vertices in priority queue and O(Log E) is same as O(Log V). Unlike Dijkstra’s implementation, a boolean array inMST[] is mandatory here because the key values of newly inserted items can be less than the key values of extracted items. So we must not consider extracted items. This article is contributed by Shubham Agrawal. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. divyesh072019 divyeshrabadiya07 avanitrachhadiya2155 suresh07 sandravsnair surindertarika1234 surinderdawra388 adityakumar129 sagartomar9927 hardikkoriintern cpp-priority-queue MST priority-queue STL Graph Graph STL priority-queue Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Find if there is a path between two vertices in a directed graph Introduction to Data Structures Find if there is a path between two vertices in an undirected graph What is Data Structure: Types, Classifications and Applications Top 50 Graph Coding Problems for Interviews K Centers Problem | Set 1 (Greedy Approximate Algorithm) Bridges in a graph Real-time application of Data Structures Longest Path in a Directed Acyclic Graph Water Jug problem using BFS
[ { "code": null, "e": 52, "s": 24, "text": "\n30 Jun, 2022" }, { "code": null, "e": 173, "s": 52, "text": "Given an undirected, connected and weighted graph, find Minimum Spanning Tree (MST) of the graph using Prim’s algorithm." }, { "code": null, "e": 481, "s": 173, "text": "Input : Adjacency List representation\n of above graph\nOutput : Edges in MST\n 0 - 1\n 1 - 2\n 2 - 3\n 3 - 4\n 2 - 5\n 5 - 6\n 6 - 7\n 2 - 8\n\n\nNote: There are two possible MSTs, the other\n MST includes edge 0-7 in place of 1-2. " }, { "code": null, "e": 534, "s": 481, "text": "We have discussed below Prim’s MST implementations. " }, { "code": null, "e": 624, "s": 534, "text": "Prim’s Algorithm for Adjacency Matrix Representation (In C/C++ with time complexity O(v2)" }, { "code": null, "e": 712, "s": 624, "text": "Prim’s Algorithm for Adjacency List Representation (In C with Time Complexity O(ELogV))" }, { "code": null, "e": 1032, "s": 712, "text": "The second implementation is time complexity wise better, but is really complex as we have implemented our own priority queue. STL provides priority_queue, but the provided priority queue doesn’t support decrease key operation. And in Prim’s algorithm, we need a priority queue and below operations on priority queue : " }, { "code": null, "e": 1156, "s": 1032, "text": "ExtractMin : from all those vertices which have not yet been included in MST, we need to get vertex with minimum key value." }, { "code": null, "e": 1306, "s": 1156, "text": "DecreaseKey : After extracting vertex we need to update keys of its adjacent vertices, and if new key is smaller, then update that in data structure." }, { "code": null, "e": 1627, "s": 1306, "text": "The algorithm discussed here can be modified so that decrease key is never required. The idea is, not to insert all vertices in priority queue, but only those which are not MST and have been visited through a vertex that has included in MST. We keep track of vertices included in MST in a separate boolean array inMST[]." }, { "code": null, "e": 3066, "s": 1627, "text": "1) Initialize keys of all vertices as infinite and \n parent of every vertex as -1.\n\n2) Create an empty priority_queue pq. Every item\n of pq is a pair (weight, vertex). Weight (or \n key) is used as first item of pair\n as first item is by default used to compare\n two pairs.\n\n3) Initialize all vertices as not part of MST yet.\n We use boolean array inMST[] for this purpose.\n This array is required to make sure that an already\n considered vertex is not included in pq again. This\n is where Prim's implementation differs from Dijkstra.\n In Dijkstra's algorithm, we didn't need this array as\n distances always increase. We require this array here \n because key value of a processed vertex may decrease\n if not checked.\n\n4) Insert source vertex into pq and make its key as 0.\n\n5) While either pq doesn't become empty \n a) Extract minimum key vertex from pq. \n Let the extracted vertex be u.\n\n b) Include u in MST using inMST[u] = true.\n\n c) Loop through all adjacent of u and do \n following for every vertex v.\n\n // If weight of edge (u,v) is smaller than\n // key of v and v is not already in MST\n If inMST[v] = false && key[v] > weight(u, v)\n\n (i) Update key of v, i.e., do\n key[v] = weight(u, v)\n (ii) Insert v into the pq \n (iv) parent[v] = u\n \n6) Print MST edges using parent array." }, { "code": null, "e": 3110, "s": 3066, "text": "Below is C++ implementation of above idea. " }, { "code": null, "e": 3114, "s": 3110, "text": "C++" }, { "code": "// STL implementation of Prim's algorithm for MST#include<bits/stdc++.h>using namespace std;# define INF 0x3f3f3f3f // iPair ==> Integer Pairtypedef pair<int, int> iPair; // This class represents a directed graph using// adjacency list representationclass Graph{ int V; // No. of vertices // In a weighted graph, we need to store vertex // and weight pair for every edge list< pair<int, int> > *adj; public: Graph(int V); // Constructor // function to add an edge to graph void addEdge(int u, int v, int w); // Print MST using Prim's algorithm void primMST();}; // Allocates memory for adjacency listGraph::Graph(int V){ this->V = V; adj = new list<iPair> [V];} void Graph::addEdge(int u, int v, int w){ adj[u].push_back(make_pair(v, w)); adj[v].push_back(make_pair(u, w));} // Prints shortest paths from src to all other verticesvoid Graph::primMST(){ // Create a priority queue to store vertices that // are being primMST. This is weird syntax in C++. // Refer below link for details of this syntax // http://geeksquiz.com/implement-min-heap-using-stl/ priority_queue< iPair, vector <iPair> , greater<iPair> > pq; int src = 0; // Taking vertex 0 as source // Create a vector for keys and initialize all // keys as infinite (INF) vector<int> key(V, INF); // To store parent array which in turn store MST vector<int> parent(V, -1); // To keep track of vertices included in MST vector<bool> inMST(V, false); // Insert source itself in priority queue and initialize // its key as 0. pq.push(make_pair(0, src)); key[src] = 0; /* Looping till priority queue becomes empty */ while (!pq.empty()) { // The first vertex in pair is the minimum key // vertex, extract it from priority queue. // vertex label is stored in second of pair (it // has to be done this way to keep the vertices // sorted key (key must be first item // in pair) int u = pq.top().second; pq.pop(); //Different key values for same vertex may exist in the priority queue. //The one with the least key value is always processed first. //Therefore, ignore the rest. if(inMST[u] == true){ continue; } inMST[u] = true; // Include vertex in MST // 'i' is used to get all adjacent vertices of a vertex list< pair<int, int> >::iterator i; for (i = adj[u].begin(); i != adj[u].end(); ++i) { // Get vertex label and weight of current adjacent // of u. int v = (*i).first; int weight = (*i).second; // If v is not in MST and weight of (u,v) is smaller // than current key of v if (inMST[v] == false && key[v] > weight) { // Updating key of v key[v] = weight; pq.push(make_pair(key[v], v)); parent[v] = u; } } } // Print edges of MST using parent array for (int i = 1; i < V; ++i) printf(\"%d - %d\\n\", parent[i], i);} // Driver program to test methods of graph classint main(){ // create the graph given in above figure int V = 9; Graph g(V); // making above shown graph g.addEdge(0, 1, 4); g.addEdge(0, 7, 8); g.addEdge(1, 2, 8); g.addEdge(1, 7, 11); g.addEdge(2, 3, 7); g.addEdge(2, 8, 2); g.addEdge(2, 5, 4); g.addEdge(3, 4, 9); g.addEdge(3, 5, 14); g.addEdge(4, 5, 10); g.addEdge(5, 6, 2); g.addEdge(6, 7, 1); g.addEdge(6, 8, 6); g.addEdge(7, 8, 7); g.primMST(); return 0;}", "e": 6769, "s": 3114, "text": null }, { "code": null, "e": 6817, "s": 6769, "text": "0 - 1\n1 - 2\n2 - 3\n3 - 4\n2 - 5\n5 - 6\n6 - 7\n2 - 8" }, { "code": null, "e": 6847, "s": 6817, "text": "Time complexity : O(E Log V))" }, { "code": null, "e": 6933, "s": 6847, "text": "A Quicker Implementation using array of vectors representation of a weighted graph : " }, { "code": null, "e": 6937, "s": 6933, "text": "C++" }, { "code": "// STL implementation of Prim's algorithm for MST#include<bits/stdc++.h>using namespace std;# define INF 0x3f3f3f3f // iPair ==> Integer Pairtypedef pair<int, int> iPair; // To add an edgevoid addEdge(vector <pair<int, int> > adj[], int u, int v, int wt){ adj[u].push_back(make_pair(v, wt)); adj[v].push_back(make_pair(u, wt));} // Prints shortest paths from src to all other verticesvoid primMST(vector<pair<int,int> > adj[], int V){ // Create a priority queue to store vertices that // are being primMST. This is weird syntax in C++. // Refer below link for details of this syntax // http://geeksquiz.com/implement-min-heap-using-stl/ priority_queue< iPair, vector <iPair> , greater<iPair> > pq; int src = 0; // Taking vertex 0 as source // Create a vector for keys and initialize all // keys as infinite (INF) vector<int> key(V, INF); // To store parent array which in turn store MST vector<int> parent(V, -1); // To keep track of vertices included in MST vector<bool> inMST(V, false); // Insert source itself in priority queue and initialize // its key as 0. pq.push(make_pair(0, src)); key[src] = 0; /* Looping till priority queue becomes empty */ while (!pq.empty()) { // The first vertex in pair is the minimum key // vertex, extract it from priority queue. // vertex label is stored in second of pair (it // has to be done this way to keep the vertices // sorted key (key must be first item // in pair) int u = pq.top().second; pq.pop(); //Different key values for same vertex may exist in the priority queue. //The one with the least key value is always processed first. //Therefore, ignore the rest. if(inMST[u] == true){ continue; } inMST[u] = true; // Include vertex in MST // Traverse all adjacent of u for (auto x : adj[u]) { // Get vertex label and weight of current adjacent // of u. int v = x.first; int weight = x.second; // If v is not in MST and weight of (u,v) is smaller // than current key of v if (inMST[v] == false && key[v] > weight) { // Updating key of v key[v] = weight; pq.push(make_pair(key[v], v)); parent[v] = u; } } } // Print edges of MST using parent array for (int i = 1; i < V; ++i) printf(\"%d - %d\\n\", parent[i], i);} // Driver program to test methods of graph classint main(){ int V = 9; vector<iPair > adj[V]; // making above shown graph addEdge(adj, 0, 1, 4); addEdge(adj, 0, 7, 8); addEdge(adj, 1, 2, 8); addEdge(adj, 1, 7, 11); addEdge(adj, 2, 3, 7); addEdge(adj, 2, 8, 2); addEdge(adj, 2, 5, 4); addEdge(adj, 3, 4, 9); addEdge(adj, 3, 5, 14); addEdge(adj, 4, 5, 10); addEdge(adj, 5, 6, 2); addEdge(adj, 6, 7, 1); addEdge(adj, 6, 8, 6); addEdge(adj, 7, 8, 7); primMST(adj, V); return 0;}", "e": 10068, "s": 6937, "text": null }, { "code": null, "e": 10116, "s": 10068, "text": "0 - 1\n1 - 2\n2 - 3\n3 - 4\n2 - 5\n5 - 6\n6 - 7\n2 - 8" }, { "code": null, "e": 10283, "s": 10116, "text": "Note: Like Dijkstra’s priority_queue implementation, we may have multiple entries for same vertex as we do not (and we can not) make isMST[v] = true in if condition. " }, { "code": null, "e": 10287, "s": 10283, "text": "C++" }, { "code": null, "e": 10292, "s": 10287, "text": "Java" }, { "code": null, "e": 10300, "s": 10292, "text": "Python3" }, { "code": null, "e": 10303, "s": 10300, "text": "C#" }, { "code": null, "e": 10314, "s": 10303, "text": "Javascript" }, { "code": "// If v is not in MST and weight of (u,v) is smaller // than current key of v if (inMST[v] == false && key[v] > weight) { // Updating key of v key[v] = weight; pq.push(make_pair(key[v], v)); parent[v] = u;}", "e": 10541, "s": 10314, "text": null }, { "code": "// If v is not in MST and weight of (u,v) is smaller// than current key of v if (inMST[v] == false && key[v] > weight){ // Updating key of v key[v] = weight; pq.add(new Pair<Integer, Integer>(key[v], v)); parent[v] = u;} // This code is contributed by avanitrachhadiya2155", "e": 10823, "s": 10541, "text": null }, { "code": "# If v is not in MST and weight of (u,v) is smaller# than current key of v if (inMST[v] == False and key[v] > weight) : # Updating key of v key[v] = weight pq.append([key[v], v]) parent[v] = u # This code is contributed by divyeshrabadiya07.", "e": 11074, "s": 10823, "text": null }, { "code": "// If v is not in MST and weight of (u,v) is smaller// than current key of v if (inMST[v] == false && key[v] > weight){ // Updating key of v key[v] = weight; pq.Add(new Tuple<int,int>(key[v], v)); parent[v] = u;} // This code is contributed by divyesh072019.", "e": 11337, "s": 11074, "text": null }, { "code": "<script> // If v is not in MST and weight of (u,v)// is smaller than current key of vif (inMST[v] == false && key[v] > weight){ // Updating key of v key[v] = weight; value = [key[v], v]; pq.push(value); parent[v] = u;} // This code is contributed by suresh07 </script>", "e": 11626, "s": 11337, "text": null }, { "code": null, "e": 11794, "s": 11626, "text": "But as explained in Dijkstra’s algorithm, time complexity remains O(E Log V) as there will be at most O(E) vertices in priority queue and O(Log E) is same as O(Log V)." }, { "code": null, "e": 12010, "s": 11794, "text": "Unlike Dijkstra’s implementation, a boolean array inMST[] is mandatory here because the key values of newly inserted items can be less than the key values of extracted items. So we must not consider extracted items." }, { "code": null, "e": 12183, "s": 12010, "text": "This article is contributed by Shubham Agrawal. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 12197, "s": 12183, "text": "divyesh072019" }, { "code": null, "e": 12215, "s": 12197, "text": "divyeshrabadiya07" }, { "code": null, "e": 12236, "s": 12215, "text": "avanitrachhadiya2155" }, { "code": null, "e": 12245, "s": 12236, "text": "suresh07" }, { "code": null, "e": 12258, "s": 12245, "text": "sandravsnair" }, { "code": null, "e": 12277, "s": 12258, "text": "surindertarika1234" }, { "code": null, "e": 12294, "s": 12277, "text": "surinderdawra388" }, { "code": null, "e": 12309, "s": 12294, "text": "adityakumar129" }, { "code": null, "e": 12324, "s": 12309, "text": "sagartomar9927" }, { "code": null, "e": 12341, "s": 12324, "text": "hardikkoriintern" }, { "code": null, "e": 12360, "s": 12341, "text": "cpp-priority-queue" }, { "code": null, "e": 12364, "s": 12360, "text": "MST" }, { "code": null, "e": 12379, "s": 12364, "text": "priority-queue" }, { "code": null, "e": 12383, "s": 12379, "text": "STL" }, { "code": null, "e": 12389, "s": 12383, "text": "Graph" }, { "code": null, "e": 12395, "s": 12389, "text": "Graph" }, { "code": null, "e": 12399, "s": 12395, "text": "STL" }, { "code": null, "e": 12414, "s": 12399, "text": "priority-queue" }, { "code": null, "e": 12512, "s": 12414, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 12577, "s": 12512, "text": "Find if there is a path between two vertices in a directed graph" }, { "code": null, "e": 12609, "s": 12577, "text": "Introduction to Data Structures" }, { "code": null, "e": 12677, "s": 12609, "text": "Find if there is a path between two vertices in an undirected graph" }, { "code": null, "e": 12741, "s": 12677, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 12785, "s": 12741, "text": "Top 50 Graph Coding Problems for Interviews" }, { "code": null, "e": 12842, "s": 12785, "text": "K Centers Problem | Set 1 (Greedy Approximate Algorithm)" }, { "code": null, "e": 12861, "s": 12842, "text": "Bridges in a graph" }, { "code": null, "e": 12902, "s": 12861, "text": "Real-time application of Data Structures" }, { "code": null, "e": 12943, "s": 12902, "text": "Longest Path in a Directed Acyclic Graph" } ]
Find Non-overlapping intervals among a given set of intervals
08 Nov, 2021 Given N set of time intervals, the task is to find the intervals which don’t overlap with the given set of intervals.Examples: Input: interval arr[] = { {1, 3}, {2, 4}, {3, 5}, {7, 9} } Output: [5, 7] Explanation: The only interval which doesn’t overlaps with the other intervals is [5, 7].Input: interval arr[] = { {1, 3}, {9, 12}, {2, 4}, {6, 8} } Output: [4, 6] [8, 9] Explanation: There are two intervals which don’t overlap with other intervals are [4, 6], [8, 9]. Approach: The idea is to sort the given time intervals according to starting time and if the consecutive intervals don’t overlap then the difference between them is the free interval. Below are the steps: Sort the given set of intervals according to starting time.Traverse all the set of intervals and check whether the consecutive intervals overlaps or not.If the intervals(say interval a & interval b) doesn’t overlap then the set of pairs form by [a.end, b.start] is the non-overlapping interval.If the intervals overlaps, then check for next consecutive intervals. Sort the given set of intervals according to starting time. Traverse all the set of intervals and check whether the consecutive intervals overlaps or not. If the intervals(say interval a & interval b) doesn’t overlap then the set of pairs form by [a.end, b.start] is the non-overlapping interval. If the intervals overlaps, then check for next consecutive intervals. Below is the implementation of the above approach: C++ Java Python3 Javascript // C++ program for the above approach #include "bits/stdc++.h"using namespace std; // interval with start time & end timestruct interval { int start, end;}; // Comparator function to sort the given// interval according to timebool compareinterval(interval i1, interval i2){ return (i1.start < i2.start);} // Function that find the free intervalvoid findFreeinterval(interval arr[], int N){ // If there are no set of interval if (N <= 0) { return; } // To store the set of free interval vector<pair<int, int> > P; // Sort the given interval according // starting time sort(arr, arr + N, compareinterval); // Iterate over all the interval for (int i = 1; i < N; i++) { // Previous interval end int prevEnd = arr[i - 1].end; // Current interval start int currStart = arr[i].start; // If ending index of previous // is less than starting index // of current, then it is free // interval if (prevEnd < currStart) { P.push_back({ prevEnd, currStart }); } } // Print the free interval for (auto& it : P) { cout << "[" << it.first << ", " << it.second << "]" << endl; }} // Driver Codeint main(){ // Given set of interval interval arr[] = { { 1, 3 }, { 2, 4 }, { 3, 5 }, { 7, 9 } }; int N = sizeof(arr) / sizeof(arr[0]); // Function Call findFreeinterval(arr, N); return 0;} // Java program for the above approachimport java.util.*;class GFG { // Interval with start time & end timestatic class Interval{ int start, end; Interval(int start, int end) { this.start = start; this.end = end; }} // Function that find the free intervalstatic void findFreeinterval(int[][] arr, int N){ // If there are no set of interval if (N <= 0) { return; } // To store the set of free interval ArrayList<Interval> p = new ArrayList<>(); // Sort the given interval according // starting time Arrays.sort(arr, new Comparator<int[]>() { public int compare(int[] a, int[] b) { return a[0] - b[0]; } }); // Iterate over all the interval for (int i = 1; i < N; i++) { // Previous interval end int prevEnd = arr[i - 1][1]; // Current interval start int currStart = arr[i][0]; // If ending index of previous // is less than starting index // of current, then it is free // interval if (prevEnd < currStart) { Interval interval = new Interval(prevEnd, currStart); p.add(interval); } } // Print the free interval for (int i = 0; i < p.size(); i++) { System.out.println("[" + p.get(i).start + ", " + p.get(i).end + "]"); }} // Driver codepublic static void main(String[] args){ // Given set of interval int[][] arr = { { 1, 3 }, { 2, 4 }, { 3, 5 }, { 7, 9 } }; int N = arr.length; // Function Call findFreeinterval(arr, N);}} // This code is contributed by offbeat # Python3 program for the above approachdef findFreeinterval(arr, N): # If there are no set of interval if N < 1: return # To store the set of free interval P = [] # Sort the given interval according # Starting time arr.sort(key = lambda a:a[0]) # Iterate over all the interval for i in range(1, N): # Previous interval end prevEnd = arr[i - 1][1] # Current interval start currStart = arr[i][0] # If Previous Interval is less # than current Interval then we # store that answer if prevEnd < currStart: P.append([prevEnd, currStart]) # Print the intervals for i in P: print(i) # Driver codeif __name__ == "__main__": # Given List of intervals arr = [ [ 1, 3 ], [ 2, 4 ], [ 3, 5 ], [ 7, 9 ] ] N = len(arr) # Function call findFreeinterval(arr, N) # This code is contributed by Tokir Manva <script> // Javascript program for the above approach // Function that find the free intervalfunction findFreeinterval(arr, N){ // If there are no set of interval if (N <= 0) { return; } // To store the set of free interval var P = []; // Sort the given interval according // starting time arr.sort((a,b) => a[0]-b[0]) // Iterate over all the interval for (var i = 1; i < N; i++) { // Previous interval end var prevEnd = arr[i - 1][1]; // Current interval start var currStart = arr[i][0]; // If ending index of previous // is less than starting index // of current, then it is free // interval if (prevEnd < currStart) { P.push([prevEnd, currStart]); } } // Print the free interval P.forEach(it => { document.write( "[" + it[0] + ", " + it[1] + "]"); });} // Driver Code // Given set of intervalvar arr = [ [ 1, 3 ], [ 2, 4 ], [ 3, 5 ], [ 7, 9 ] ];var N = arr.length; // Function CallfindFreeinterval(arr, N); // This code is contributed by noob2000.</script> [5, 7] Time Complexity: O(N*log N), where N is the number of set of intervals. Auxiliary Space: O(N) offbeat draculemihawk noob2000 rohitsingh07052 Competitive Programming Heap Sorting Sorting Heap Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Modulo 10^9+7 (1000000007) Prefix Sum Array - Implementation and Applications in Competitive Programming Bits manipulation (Important tactics) What is Competitive Programming and How to Prepare for It? Algorithm Library | C++ Magicians STL Algorithm HeapSort K'th Smallest/Largest Element in Unsorted Array | Set 1 Binary Heap Introduction to Data Structures Huffman Coding | Greedy Algo-3
[ { "code": null, "e": 52, "s": 24, "text": "\n08 Nov, 2021" }, { "code": null, "e": 181, "s": 52, "text": "Given N set of time intervals, the task is to find the intervals which don’t overlap with the given set of intervals.Examples: " }, { "code": null, "e": 525, "s": 181, "text": "Input: interval arr[] = { {1, 3}, {2, 4}, {3, 5}, {7, 9} } Output: [5, 7] Explanation: The only interval which doesn’t overlaps with the other intervals is [5, 7].Input: interval arr[] = { {1, 3}, {9, 12}, {2, 4}, {6, 8} } Output: [4, 6] [8, 9] Explanation: There are two intervals which don’t overlap with other intervals are [4, 6], [8, 9]. " }, { "code": null, "e": 734, "s": 527, "text": "Approach: The idea is to sort the given time intervals according to starting time and if the consecutive intervals don’t overlap then the difference between them is the free interval. Below are the steps: " }, { "code": null, "e": 1098, "s": 734, "text": "Sort the given set of intervals according to starting time.Traverse all the set of intervals and check whether the consecutive intervals overlaps or not.If the intervals(say interval a & interval b) doesn’t overlap then the set of pairs form by [a.end, b.start] is the non-overlapping interval.If the intervals overlaps, then check for next consecutive intervals." }, { "code": null, "e": 1158, "s": 1098, "text": "Sort the given set of intervals according to starting time." }, { "code": null, "e": 1253, "s": 1158, "text": "Traverse all the set of intervals and check whether the consecutive intervals overlaps or not." }, { "code": null, "e": 1395, "s": 1253, "text": "If the intervals(say interval a & interval b) doesn’t overlap then the set of pairs form by [a.end, b.start] is the non-overlapping interval." }, { "code": null, "e": 1465, "s": 1395, "text": "If the intervals overlaps, then check for next consecutive intervals." }, { "code": null, "e": 1518, "s": 1465, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 1522, "s": 1518, "text": "C++" }, { "code": null, "e": 1527, "s": 1522, "text": "Java" }, { "code": null, "e": 1535, "s": 1527, "text": "Python3" }, { "code": null, "e": 1546, "s": 1535, "text": "Javascript" }, { "code": "// C++ program for the above approach #include \"bits/stdc++.h\"using namespace std; // interval with start time & end timestruct interval { int start, end;}; // Comparator function to sort the given// interval according to timebool compareinterval(interval i1, interval i2){ return (i1.start < i2.start);} // Function that find the free intervalvoid findFreeinterval(interval arr[], int N){ // If there are no set of interval if (N <= 0) { return; } // To store the set of free interval vector<pair<int, int> > P; // Sort the given interval according // starting time sort(arr, arr + N, compareinterval); // Iterate over all the interval for (int i = 1; i < N; i++) { // Previous interval end int prevEnd = arr[i - 1].end; // Current interval start int currStart = arr[i].start; // If ending index of previous // is less than starting index // of current, then it is free // interval if (prevEnd < currStart) { P.push_back({ prevEnd, currStart }); } } // Print the free interval for (auto& it : P) { cout << \"[\" << it.first << \", \" << it.second << \"]\" << endl; }} // Driver Codeint main(){ // Given set of interval interval arr[] = { { 1, 3 }, { 2, 4 }, { 3, 5 }, { 7, 9 } }; int N = sizeof(arr) / sizeof(arr[0]); // Function Call findFreeinterval(arr, N); return 0;}", "e": 3088, "s": 1546, "text": null }, { "code": "// Java program for the above approachimport java.util.*;class GFG { // Interval with start time & end timestatic class Interval{ int start, end; Interval(int start, int end) { this.start = start; this.end = end; }} // Function that find the free intervalstatic void findFreeinterval(int[][] arr, int N){ // If there are no set of interval if (N <= 0) { return; } // To store the set of free interval ArrayList<Interval> p = new ArrayList<>(); // Sort the given interval according // starting time Arrays.sort(arr, new Comparator<int[]>() { public int compare(int[] a, int[] b) { return a[0] - b[0]; } }); // Iterate over all the interval for (int i = 1; i < N; i++) { // Previous interval end int prevEnd = arr[i - 1][1]; // Current interval start int currStart = arr[i][0]; // If ending index of previous // is less than starting index // of current, then it is free // interval if (prevEnd < currStart) { Interval interval = new Interval(prevEnd, currStart); p.add(interval); } } // Print the free interval for (int i = 0; i < p.size(); i++) { System.out.println(\"[\" + p.get(i).start + \", \" + p.get(i).end + \"]\"); }} // Driver codepublic static void main(String[] args){ // Given set of interval int[][] arr = { { 1, 3 }, { 2, 4 }, { 3, 5 }, { 7, 9 } }; int N = arr.length; // Function Call findFreeinterval(arr, N);}} // This code is contributed by offbeat", "e": 4834, "s": 3088, "text": null }, { "code": "# Python3 program for the above approachdef findFreeinterval(arr, N): # If there are no set of interval if N < 1: return # To store the set of free interval P = [] # Sort the given interval according # Starting time arr.sort(key = lambda a:a[0]) # Iterate over all the interval for i in range(1, N): # Previous interval end prevEnd = arr[i - 1][1] # Current interval start currStart = arr[i][0] # If Previous Interval is less # than current Interval then we # store that answer if prevEnd < currStart: P.append([prevEnd, currStart]) # Print the intervals for i in P: print(i) # Driver codeif __name__ == \"__main__\": # Given List of intervals arr = [ [ 1, 3 ], [ 2, 4 ], [ 3, 5 ], [ 7, 9 ] ] N = len(arr) # Function call findFreeinterval(arr, N) # This code is contributed by Tokir Manva", "e": 5836, "s": 4834, "text": null }, { "code": "<script> // Javascript program for the above approach // Function that find the free intervalfunction findFreeinterval(arr, N){ // If there are no set of interval if (N <= 0) { return; } // To store the set of free interval var P = []; // Sort the given interval according // starting time arr.sort((a,b) => a[0]-b[0]) // Iterate over all the interval for (var i = 1; i < N; i++) { // Previous interval end var prevEnd = arr[i - 1][1]; // Current interval start var currStart = arr[i][0]; // If ending index of previous // is less than starting index // of current, then it is free // interval if (prevEnd < currStart) { P.push([prevEnd, currStart]); } } // Print the free interval P.forEach(it => { document.write( \"[\" + it[0] + \", \" + it[1] + \"]\"); });} // Driver Code // Given set of intervalvar arr = [ [ 1, 3 ], [ 2, 4 ], [ 3, 5 ], [ 7, 9 ] ];var N = arr.length; // Function CallfindFreeinterval(arr, N); // This code is contributed by noob2000.</script>", "e": 7033, "s": 5836, "text": null }, { "code": null, "e": 7040, "s": 7033, "text": "[5, 7]" }, { "code": null, "e": 7114, "s": 7042, "text": "Time Complexity: O(N*log N), where N is the number of set of intervals." }, { "code": null, "e": 7137, "s": 7114, "text": "Auxiliary Space: O(N) " }, { "code": null, "e": 7145, "s": 7137, "text": "offbeat" }, { "code": null, "e": 7159, "s": 7145, "text": "draculemihawk" }, { "code": null, "e": 7168, "s": 7159, "text": "noob2000" }, { "code": null, "e": 7184, "s": 7168, "text": "rohitsingh07052" }, { "code": null, "e": 7208, "s": 7184, "text": "Competitive Programming" }, { "code": null, "e": 7213, "s": 7208, "text": "Heap" }, { "code": null, "e": 7221, "s": 7213, "text": "Sorting" }, { "code": null, "e": 7229, "s": 7221, "text": "Sorting" }, { "code": null, "e": 7234, "s": 7229, "text": "Heap" }, { "code": null, "e": 7332, "s": 7234, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7359, "s": 7332, "text": "Modulo 10^9+7 (1000000007)" }, { "code": null, "e": 7437, "s": 7359, "text": "Prefix Sum Array - Implementation and Applications in Competitive Programming" }, { "code": null, "e": 7475, "s": 7437, "text": "Bits manipulation (Important tactics)" }, { "code": null, "e": 7534, "s": 7475, "text": "What is Competitive Programming and How to Prepare for It?" }, { "code": null, "e": 7582, "s": 7534, "text": "Algorithm Library | C++ Magicians STL Algorithm" }, { "code": null, "e": 7591, "s": 7582, "text": "HeapSort" }, { "code": null, "e": 7647, "s": 7591, "text": "K'th Smallest/Largest Element in Unsorted Array | Set 1" }, { "code": null, "e": 7659, "s": 7647, "text": "Binary Heap" }, { "code": null, "e": 7691, "s": 7659, "text": "Introduction to Data Structures" } ]
Python | Merge two lists into list of tuples
27 Dec, 2018 Given two lists, write a Python program to merge the two lists into list of tuples. Examples: Input : list1 = [1, 2, 3] list2 = ['a', 'b', 'c'] Output : [(1, 'a'), (2, 'b'), (3, 'c')] Input : list1 = [1, 2, 3, 4] list2 = [ 1, 4, 9] Output : [(1, 1), (2, 4), (3, 9), (4, '')] Approach #1 : NaiveMerge both the list into a list of tuple using a for loop. But the drawback is given two lists need to be of the same length. def merge(list1, list2): merged_list = [(list1[i], list2[i]) for i in range(0, len(list1))] return merged_list # Driver codelist1 = [1, 2, 3]list2 = ['a', 'b', 'c']print(merge(list1, list2)) [(1, 'a'), (2, 'b'), (3, 'c')] Approach #2 : Naive but more efficientThis method remove the above given drawback and work well with uneven lengths of the two lists. It also provide try catch error for Index error. def merge(list1, list2): merged_list = [] for i in range(max((len(list1), len(list2)))): while True: try: tup = (list1[i], list2[i]) except IndexError: if len(list1) > len(list2): list2.append('') tup = (list1[i], list2[i]) elif len(list1) < len(list2): list1.append('') tup = (list1[i], list2[i]) continue merged_list.append(tup) break return merged_list # Driver codelist1 = [1, 2, 3]list2 = ['a', 'b', 'c']print(merge(list1, list2)) [(1, 'a'), (2, 'b'), (3, 'c')] Approach #3 : Using zip()using zip() method to merge the two list elements and then typecasting into tuple. def merge(list1, list2): merged_list = tuple(zip(list1, list2)) return merged_list # Driver codelist1 = [1, 2, 3]list2 = ['a', 'b', 'c']print(merge(list1, list2)) ((1, 'a'), (2, 'b'), (3, 'c')) Approach #4 : Using enumerate(), alternative to zip(). This method uses two for loops to enumerate through lists and merge the two lists. def merge(list1, list2): merged_list = [(p1, p2) for idx1, p1 in enumerate(list1) for idx2, p2 in enumerate(list2) if idx1 == idx2] return merged_list # Driver codelist1 = [1, 2, 3]list2 = ['a', 'b', 'c']print(merge(list1, list2)) [(1, 'a'), (2, 'b'), (3, 'c')] Approach #5: Using map() and lambda. # Using map() and lambdadef listOfTuples(l1, l2): return list(map(lambda x, y:(x,y), l1, l2)) # Driver Codelist1 = [1, 2, 3]list2 = ['a', 'b', 'c'] print(listOfTuples(list1, list2)) [(1, 'a'), (2, 'b'), (3, 'c')] Python list-programs Python tuple-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n27 Dec, 2018" }, { "code": null, "e": 136, "s": 52, "text": "Given two lists, write a Python program to merge the two lists into list of tuples." }, { "code": null, "e": 146, "s": 136, "text": "Examples:" }, { "code": null, "e": 345, "s": 146, "text": "Input : list1 = [1, 2, 3]\n list2 = ['a', 'b', 'c']\nOutput : [(1, 'a'), (2, 'b'), (3, 'c')]\n\nInput : list1 = [1, 2, 3, 4]\n list2 = [ 1, 4, 9]\nOutput : [(1, 1), (2, 4), (3, 9), (4, '')]\n" }, { "code": null, "e": 490, "s": 345, "text": "Approach #1 : NaiveMerge both the list into a list of tuple using a for loop. But the drawback is given two lists need to be of the same length." }, { "code": "def merge(list1, list2): merged_list = [(list1[i], list2[i]) for i in range(0, len(list1))] return merged_list # Driver codelist1 = [1, 2, 3]list2 = ['a', 'b', 'c']print(merge(list1, list2))", "e": 698, "s": 490, "text": null }, { "code": null, "e": 730, "s": 698, "text": "[(1, 'a'), (2, 'b'), (3, 'c')]\n" }, { "code": null, "e": 914, "s": 730, "text": " Approach #2 : Naive but more efficientThis method remove the above given drawback and work well with uneven lengths of the two lists. It also provide try catch error for Index error." }, { "code": "def merge(list1, list2): merged_list = [] for i in range(max((len(list1), len(list2)))): while True: try: tup = (list1[i], list2[i]) except IndexError: if len(list1) > len(list2): list2.append('') tup = (list1[i], list2[i]) elif len(list1) < len(list2): list1.append('') tup = (list1[i], list2[i]) continue merged_list.append(tup) break return merged_list # Driver codelist1 = [1, 2, 3]list2 = ['a', 'b', 'c']print(merge(list1, list2))", "e": 1557, "s": 914, "text": null }, { "code": null, "e": 1589, "s": 1557, "text": "[(1, 'a'), (2, 'b'), (3, 'c')]\n" }, { "code": null, "e": 1698, "s": 1589, "text": " Approach #3 : Using zip()using zip() method to merge the two list elements and then typecasting into tuple." }, { "code": "def merge(list1, list2): merged_list = tuple(zip(list1, list2)) return merged_list # Driver codelist1 = [1, 2, 3]list2 = ['a', 'b', 'c']print(merge(list1, list2))", "e": 1879, "s": 1698, "text": null }, { "code": null, "e": 1911, "s": 1879, "text": "((1, 'a'), (2, 'b'), (3, 'c'))\n" }, { "code": null, "e": 1967, "s": 1911, "text": " Approach #4 : Using enumerate(), alternative to zip()." }, { "code": null, "e": 2050, "s": 1967, "text": "This method uses two for loops to enumerate through lists and merge the two lists." }, { "code": "def merge(list1, list2): merged_list = [(p1, p2) for idx1, p1 in enumerate(list1) for idx2, p2 in enumerate(list2) if idx1 == idx2] return merged_list # Driver codelist1 = [1, 2, 3]list2 = ['a', 'b', 'c']print(merge(list1, list2))", "e": 2302, "s": 2050, "text": null }, { "code": null, "e": 2334, "s": 2302, "text": "[(1, 'a'), (2, 'b'), (3, 'c')]\n" }, { "code": null, "e": 2372, "s": 2334, "text": " Approach #5: Using map() and lambda." }, { "code": "# Using map() and lambdadef listOfTuples(l1, l2): return list(map(lambda x, y:(x,y), l1, l2)) # Driver Codelist1 = [1, 2, 3]list2 = ['a', 'b', 'c'] print(listOfTuples(list1, list2))", "e": 2559, "s": 2372, "text": null }, { "code": null, "e": 2591, "s": 2559, "text": "[(1, 'a'), (2, 'b'), (3, 'c')]\n" }, { "code": null, "e": 2612, "s": 2591, "text": "Python list-programs" }, { "code": null, "e": 2634, "s": 2612, "text": "Python tuple-programs" }, { "code": null, "e": 2641, "s": 2634, "text": "Python" }, { "code": null, "e": 2657, "s": 2641, "text": "Python Programs" } ]
Length of Longest Balanced Subsequence
24 May, 2021 Given a string S, find the length of the longest balanced subsequence in it. A balanced string is defined as:- A null string is a balanced string. If X and Y are balanced strings, then (X)Y and XY are balanced strings. Examples: Input : S = "()())" Output : 4 ()() is the longest balanced subsequence of length 4. Input : s = "()(((((()" Output : 4 Approach 1: A brute force approach is to find all subsequences of the given string S and check for all possible subsequences if they form a balanced sequence. If yes, compare it with the maximum value.The better approach is to use Dynamic Programming. Longest Balanced Subsequence (LBS), can be recursively defined as below. LBS of substring str[i..j] : If str[i] == str[j] LBS(str, i, j) = LBS(str, i + 1, j - 1) + 2 Else LBS(str, i, j) = max(LBS(str, i, k) + LBS(str, k + 1, j)) Where i <= k < j Declare a 2D matrix dp[][], where our state dp[i][j] will denote the length of the longest balanced subsequence from index i to j. We will compute this state in order of increasing j – i. For a particular state dp[i][j], we will try to match the jth symbol with the kth symbol. That can be done only if S[k] is ‘(‘ and S[j] is ‘)’. We will take the max of 2 + dp[i][k – 1] + dp[k + 1][j – 1] for all such possible k and also max(dp[i + 1][j], dp[i][j – 1]) and put the value in dp[i][j]. In this way, we can fill out all the dp states. dp[0][length of string – 1] (considering 0 indexing) will be our answer.Below is the implementation of this approach: C++ Java Python3 C# PHP Javascript // C++ program to find length of// the longest balanced subsequence#include <bits/stdc++.h>using namespace std; int maxLength(char s[], int n){ int dp[n][n]; memset(dp, 0, sizeof(dp)); // Considering all balanced // substrings of length 2 for (int i = 0; i < n - 1; i++) if (s[i] == '(' && s[i + 1] == ')') dp[i][i + 1] = 2; // Considering all other substrings for (int l = 2; l < n; l++) { for (int i = 0, j = l; j < n; i++, j++) { if (s[i] == '(' && s[j] == ')') dp[i][j] = 2 + dp[i + 1][j - 1]; for (int k = i; k < j; k++) dp[i][j] = max(dp[i][j], dp[i][k] + dp[k + 1][j]); } } return dp[0][n - 1];} // Driver Codeint main(){ char s[] = "()(((((()"; int n = strlen(s); cout << maxLength(s, n) << endl; return 0;} // Java program to find length of the// longest balanced subsequence.import java.io.*; class GFG { static int maxLength(String s, int n) { int dp[][] = new int[n][n]; // Considering all balanced substrings // of length 2 for (int i = 0; i < n - 1; i++) if (s.charAt(i) == '(' && s.charAt(i + 1) == ')') dp[i][i + 1] = 2; // Considering all other substrings for (int l = 2; l < n; l++) { for (int i = 0, j = l; j < n; i++, j++) { if (s.charAt(i) == '(' && s.charAt(j) == ')') dp[i][j] = 2 + dp[i + 1][j - 1]; for (int k = i; k < j; k++) dp[i][j] = Math.max(dp[i][j], dp[i][k] + dp[k + 1][j]); } } return dp[0][n - 1]; } // Driver Code public static void main(String[] args) { String s = "()(((((()"; int n = s.length(); System.out.println(maxLength(s, n)); }}// This code is contributed by Prerna Saini # Python3 program to find length of# the longest balanced subsequence def maxLength(s, n): dp = [[0 for i in range(n)] for i in range(n)] # Considering all balanced # substrings of length 2 for i in range(n - 1): if (s[i] == '(' and s[i + 1] == ')'): dp[i][i + 1] = 2 # Considering all other substrings for l in range(2, n): i = -1 for j in range(l, n): i += 1 if (s[i] == '(' and s[j] == ')'): dp[i][j] = 2 + dp[i + 1][j - 1] for k in range(i, j): dp[i][j] = max(dp[i][j], dp[i][k] + dp[k + 1][j]) return dp[0][n - 1] # Driver Codes = "()(((((()"n = len(s)print(maxLength(s, n)) # This code is contributed# by sahishelangia // C# program to find length of the// longest balanced subsequence.using System; class GFG { static int maxLength(String s, int n) { int[, ] dp = new int[n, n]; // Considering all balanced substrings // of length 2 for (int i = 0; i < n - 1; i++) if (s[i] == '(' && s[i + 1] == ')') dp[i, i + 1] = 2; // Considering all other substrings for (int l = 2; l < n; l++) { for (int i = 0, j = l; j < n; i++, j++) { if (s[i] == '(' && s[j] == ')') dp[i, j] = 2 + dp[i + 1, j - 1]; for (int k = i; k < j; k++) dp[i, j] = Math.Max(dp[i, j], dp[i, k] + dp[k + 1, j]); } } return dp[0, n - 1]; } // Driver Code public static void Main() { string s = "()(((((()"; int n = s.Length; Console.WriteLine(maxLength(s, n)); }} // This code is contributed by vt_m. <?php// PHP program to find length of// the longest balanced subsequencefunction maxLength($s, $n){ $dp = array_fill(0, $n, array_fill(0, $n, NULL)); // Considering all balanced // substrings of length 2 for ($i = 0; $i < $n - 1; $i++) if ($s[$i] == '(' && $s[$i + 1] == ')') $dp[$i][$i + 1] = 2; // Considering all other substrings for ($l = 2; $l < $n; $l++) { for ($i = 0, $j = $l; $j < $n; $i++, $j++) { if ($s[$i] == '(' && $s[$j] == ')') $dp[$i][$j] = 2 + $dp[$i + 1][$j - 1]; for ($k = $i; $k < $j; $k++) $dp[$i][$j] = max($dp[$i][$j], $dp[$i][$k] + $dp[$k + 1][$j]); } } return $dp[0][$n - 1];} // Driver Code$s = "()(((((()";$n = strlen($s);echo maxLength($s, $n)."\n"; // This code is contributed by ita_c?> <script> // Javascript program to find length of the // longest balanced subsequence. function maxLength(s, n) { let dp = new Array(n); for (let i = 0; i < n; i++) { dp[i] = new Array(n); for (let j = 0; j < n; j++) { dp[i][j] = 0; } } // Considering all balanced substrings // of length 2 for (let i = 0; i < n - 1; i++) if (s[i] == '(' && s[i + 1] == ')') dp[i][i + 1] = 2; // Considering all other substrings for (let l = 2; l < n; l++) { for (let i = 0, j = l; j < n; i++, j++) { if (s[i] == '(' && s[j] == ')') dp[i][j] = 2 + dp[i + 1][j - 1]; for (let k = i; k < j; k++) dp[i][j] = Math.max(dp[i][j], dp[i][k] + dp[k + 1][j]); } } return dp[0][n - 1]; } let s = "()(((((()"; let n = s.length; document.write(maxLength(s, n)); </script> 4 Time Complexity : O(n2) Auxiliary Space : O(n2) Approach 2: This approach solves the problem in a more efficient manner. Count the number of braces to be removed to get the longest balanced parentheses sub-sequence.If the i-th index number of close braces is greater than the number of open braces, then that close brace has to be removed.Count the number of close braces that need to be removed.In the end, the number of extra open braces will also be removed.So, the total count to be removed would be the sum of extra open braces and invalid close braces. Count the number of braces to be removed to get the longest balanced parentheses sub-sequence. If the i-th index number of close braces is greater than the number of open braces, then that close brace has to be removed. Count the number of close braces that need to be removed. In the end, the number of extra open braces will also be removed. So, the total count to be removed would be the sum of extra open braces and invalid close braces. C++ Java Python3 C# Javascript // C++ program to find length of// the longest balanced subsequence#include <bits/stdc++.h>using namespace std; int maxLength(char s[], int n){ // As it's subsequence - assuming first // open brace would map to a first close // brace which occurs after the open brace // to make subsequence balanced and second // open brace would map to second close // brace and so on. // Variable to count all the open brace // that does not have the corresponding // closing brace. int invalidOpenBraces = 0; // To count all the close brace that // does not have the corresponding open brace. int invalidCloseBraces = 0; // Iterating over the String for (int i = 0; i < n; i++) { if (s[i] == '(') { // Number of open braces that // hasn't been closed yet. invalidOpenBraces++; } else { if (invalidOpenBraces == 0) { // Number of close braces that // cannot be mapped to any open // brace. invalidCloseBraces++; } else { // Mapping the ith close brace // to one of the open brace. invalidOpenBraces--; } } } return ( n - (invalidOpenBraces + invalidCloseBraces));} // Driver Codeint main(){ char s[] = "()(((((()"; int n = strlen(s); cout << maxLength(s, n) << endl; return 0;} // Java program to find the length of the// longest balanced subsequence.import java.io.*; class GFG { static int maxLength(String s, int n) { // As it's subsequence - assuming first // open brace would map to a first close // brace which occurs after the open brace // to make subsequence balanced and second // open brace would map to second close // brace and so on. // Variable to count all the open brace // that does not have the corresponding // closing brace. int invalidOpenBraces = 0; // To count all the close brace that // does not have the corresponding open brace. int invalidCloseBraces = 0; // Iterating over the String for (int i = 0; i < n; i++) { if (s.charAt(i) == '(') { // Number of open braces that // hasn't been closed yet.vvvvvv invalidOpenBraces++; } else { if (invalidOpenBraces == 0) { // Number of close braces that // cannot be mapped to any open // brace. invalidCloseBraces++; } else { // Mapping the ith close brace // to one of the open brace. invalidOpenBraces--; } } } return ( n - (invalidOpenBraces + invalidCloseBraces)); } // Driver Code public static void main(String[] args) { String s = "()(((((()"; int n = s.length(); System.out.println(maxLength(s, n)); }} # Python3 program to find length of# the longest balanced subsequence def maxLength(s, n): # As it's subsequence - assuming first # open brace would map to a first close # brace which occurs after the open brace # to make subsequence balanced and second # open brace would map to second close # brace and so on. # Variable to count all the open brace # that does not have the corresponding # closing brace. invalidOpenBraces = 0; # To count all the close brace that does # not have the corresponding open brace. invalidCloseBraces = 0; # Iterating over the String for i in range(n): if( s[i] == '(' ): # Number of open braces that # hasn't been closed yet. invalidOpenBraces += 1 else: if(invalidOpenBraces == 0): # Number of close braces that # cannot be mapped to any open # brace. invalidCloseBraces += 1 else: # Mapping the ith close brace # to one of the open brace. invalidOpenBraces -= 1 return (n - (invalidOpenBraces + invalidCloseBraces)) # Driver Codes = "()(((((()"n = len(s)print(maxLength(s, n)) // C# program to find length of the// longest balanced subsequence.using System; class GFG { static int maxLength(String s, int n) { // As it's subsequence - assuming first // open brace would map to a first close // brace which occurs after the open brace // to make subsequence balanced and second // open brace would map to second close // brace and so on. // Variable to count all the open brace // that does not have the corresponding // closing brace. int invalidOpenBraces = 0; // To count all the close brace that // does not have the corresponding open brace. int invalidCloseBraces = 0; // Iterating over the String for (int i = 0; i < n; i++) { if (s[i] == '(') { // Number of open braces that // hasn't been closed yet. invalidOpenBraces++; } else { if (invalidOpenBraces == 0) { // Number of close braces that // cannot be mapped to any open brace. invalidCloseBraces++; } else { // Mapping the ith close brace to // one of the open brace. invalidOpenBraces--; } } } return ( n - (invalidOpenBraces + invalidCloseBraces)); } // Driver Code public static void Main() { string s = "()(((((()"; int n = s.Length; Console.WriteLine(maxLength(s, n)); }} <script> // Javascript program to find the length of the// longest balanced subsequence. function maxLength(s, n) { // As it's subsequence - assuming first // open brace would map to a first close // brace which occurs after the open brace // to make subsequence balanced and second // open brace would map to second close // brace and so on. // Variable to count all the open brace // that does not have the corresponding // closing brace. let invalidOpenBraces = 0; // To count all the close brace that // does not have the corresponding open brace. let invalidCloseBraces = 0; // Iterating over the String for (let i = 0; i < n; i++) { if (s[i] == '(') { // Number of open braces that // hasn't been closed yet.vvvvvv invalidOpenBraces++; } else { if (invalidOpenBraces == 0) { // Number of close braces that // cannot be mapped to any open // brace. invalidCloseBraces++; } else { // Mapping the ith close brace // to one of the open brace. invalidOpenBraces--; } } } return ( n - (invalidOpenBraces + invalidCloseBraces)); } // driver program let s = "()(((((()"; let n = s.length; document.write(maxLength(s, n)); </script> 4 Time Complexity : O(n) Auxiliary Space : O(1) 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 contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. vt_m sahilshelangia ukasp mayankbansal2 souravghosh0416 suresh07 subsequence Dynamic Programming Strings Strings Dynamic Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. 0-1 Knapsack Problem | DP-10 Largest Sum Contiguous Subarray Program for Fibonacci numbers Longest Common Subsequence | DP-4 Longest Increasing Subsequence | DP-3 Write a program to reverse an array or string Reverse a string in Java C++ Data Types Write a program to print all permutations of a given string Check for Balanced Brackets in an expression (well-formedness) using Stack
[ { "code": null, "e": 54, "s": 26, "text": "\n24 May, 2021" }, { "code": null, "e": 166, "s": 54, "text": "Given a string S, find the length of the longest balanced subsequence in it. A balanced string is defined as:- " }, { "code": null, "e": 202, "s": 166, "text": "A null string is a balanced string." }, { "code": null, "e": 274, "s": 202, "text": "If X and Y are balanced strings, then (X)Y and XY are balanced strings." }, { "code": null, "e": 285, "s": 274, "text": "Examples: " }, { "code": null, "e": 408, "s": 285, "text": "Input : S = \"()())\"\nOutput : 4\n\n()() is the longest balanced subsequence \nof length 4.\n\nInput : s = \"()(((((()\"\nOutput : 4" }, { "code": null, "e": 736, "s": 410, "text": "Approach 1: A brute force approach is to find all subsequences of the given string S and check for all possible subsequences if they form a balanced sequence. If yes, compare it with the maximum value.The better approach is to use Dynamic Programming. Longest Balanced Subsequence (LBS), can be recursively defined as below. " }, { "code": null, "e": 967, "s": 736, "text": "LBS of substring str[i..j] : \nIf str[i] == str[j]\n LBS(str, i, j) = LBS(str, i + 1, j - 1) + 2\nElse\n LBS(str, i, j) = max(LBS(str, i, k) +\n LBS(str, k + 1, j))\n Where i <= k < j " }, { "code": null, "e": 1623, "s": 967, "text": "Declare a 2D matrix dp[][], where our state dp[i][j] will denote the length of the longest balanced subsequence from index i to j. We will compute this state in order of increasing j – i. For a particular state dp[i][j], we will try to match the jth symbol with the kth symbol. That can be done only if S[k] is ‘(‘ and S[j] is ‘)’. We will take the max of 2 + dp[i][k – 1] + dp[k + 1][j – 1] for all such possible k and also max(dp[i + 1][j], dp[i][j – 1]) and put the value in dp[i][j]. In this way, we can fill out all the dp states. dp[0][length of string – 1] (considering 0 indexing) will be our answer.Below is the implementation of this approach: " }, { "code": null, "e": 1627, "s": 1623, "text": "C++" }, { "code": null, "e": 1632, "s": 1627, "text": "Java" }, { "code": null, "e": 1640, "s": 1632, "text": "Python3" }, { "code": null, "e": 1643, "s": 1640, "text": "C#" }, { "code": null, "e": 1647, "s": 1643, "text": "PHP" }, { "code": null, "e": 1658, "s": 1647, "text": "Javascript" }, { "code": "// C++ program to find length of// the longest balanced subsequence#include <bits/stdc++.h>using namespace std; int maxLength(char s[], int n){ int dp[n][n]; memset(dp, 0, sizeof(dp)); // Considering all balanced // substrings of length 2 for (int i = 0; i < n - 1; i++) if (s[i] == '(' && s[i + 1] == ')') dp[i][i + 1] = 2; // Considering all other substrings for (int l = 2; l < n; l++) { for (int i = 0, j = l; j < n; i++, j++) { if (s[i] == '(' && s[j] == ')') dp[i][j] = 2 + dp[i + 1][j - 1]; for (int k = i; k < j; k++) dp[i][j] = max(dp[i][j], dp[i][k] + dp[k + 1][j]); } } return dp[0][n - 1];} // Driver Codeint main(){ char s[] = \"()(((((()\"; int n = strlen(s); cout << maxLength(s, n) << endl; return 0;}", "e": 2531, "s": 1658, "text": null }, { "code": "// Java program to find length of the// longest balanced subsequence.import java.io.*; class GFG { static int maxLength(String s, int n) { int dp[][] = new int[n][n]; // Considering all balanced substrings // of length 2 for (int i = 0; i < n - 1; i++) if (s.charAt(i) == '(' && s.charAt(i + 1) == ')') dp[i][i + 1] = 2; // Considering all other substrings for (int l = 2; l < n; l++) { for (int i = 0, j = l; j < n; i++, j++) { if (s.charAt(i) == '(' && s.charAt(j) == ')') dp[i][j] = 2 + dp[i + 1][j - 1]; for (int k = i; k < j; k++) dp[i][j] = Math.max(dp[i][j], dp[i][k] + dp[k + 1][j]); } } return dp[0][n - 1]; } // Driver Code public static void main(String[] args) { String s = \"()(((((()\"; int n = s.length(); System.out.println(maxLength(s, n)); }}// This code is contributed by Prerna Saini", "e": 3591, "s": 2531, "text": null }, { "code": "# Python3 program to find length of# the longest balanced subsequence def maxLength(s, n): dp = [[0 for i in range(n)] for i in range(n)] # Considering all balanced # substrings of length 2 for i in range(n - 1): if (s[i] == '(' and s[i + 1] == ')'): dp[i][i + 1] = 2 # Considering all other substrings for l in range(2, n): i = -1 for j in range(l, n): i += 1 if (s[i] == '(' and s[j] == ')'): dp[i][j] = 2 + dp[i + 1][j - 1] for k in range(i, j): dp[i][j] = max(dp[i][j], dp[i][k] + dp[k + 1][j]) return dp[0][n - 1] # Driver Codes = \"()(((((()\"n = len(s)print(maxLength(s, n)) # This code is contributed# by sahishelangia", "e": 4404, "s": 3591, "text": null }, { "code": "// C# program to find length of the// longest balanced subsequence.using System; class GFG { static int maxLength(String s, int n) { int[, ] dp = new int[n, n]; // Considering all balanced substrings // of length 2 for (int i = 0; i < n - 1; i++) if (s[i] == '(' && s[i + 1] == ')') dp[i, i + 1] = 2; // Considering all other substrings for (int l = 2; l < n; l++) { for (int i = 0, j = l; j < n; i++, j++) { if (s[i] == '(' && s[j] == ')') dp[i, j] = 2 + dp[i + 1, j - 1]; for (int k = i; k < j; k++) dp[i, j] = Math.Max(dp[i, j], dp[i, k] + dp[k + 1, j]); } } return dp[0, n - 1]; } // Driver Code public static void Main() { string s = \"()(((((()\"; int n = s.Length; Console.WriteLine(maxLength(s, n)); }} // This code is contributed by vt_m.", "e": 5409, "s": 4404, "text": null }, { "code": "<?php// PHP program to find length of// the longest balanced subsequencefunction maxLength($s, $n){ $dp = array_fill(0, $n, array_fill(0, $n, NULL)); // Considering all balanced // substrings of length 2 for ($i = 0; $i < $n - 1; $i++) if ($s[$i] == '(' && $s[$i + 1] == ')') $dp[$i][$i + 1] = 2; // Considering all other substrings for ($l = 2; $l < $n; $l++) { for ($i = 0, $j = $l; $j < $n; $i++, $j++) { if ($s[$i] == '(' && $s[$j] == ')') $dp[$i][$j] = 2 + $dp[$i + 1][$j - 1]; for ($k = $i; $k < $j; $k++) $dp[$i][$j] = max($dp[$i][$j], $dp[$i][$k] + $dp[$k + 1][$j]); } } return $dp[0][$n - 1];} // Driver Code$s = \"()(((((()\";$n = strlen($s);echo maxLength($s, $n).\"\\n\"; // This code is contributed by ita_c?>", "e": 6332, "s": 5409, "text": null }, { "code": "<script> // Javascript program to find length of the // longest balanced subsequence. function maxLength(s, n) { let dp = new Array(n); for (let i = 0; i < n; i++) { dp[i] = new Array(n); for (let j = 0; j < n; j++) { dp[i][j] = 0; } } // Considering all balanced substrings // of length 2 for (let i = 0; i < n - 1; i++) if (s[i] == '(' && s[i + 1] == ')') dp[i][i + 1] = 2; // Considering all other substrings for (let l = 2; l < n; l++) { for (let i = 0, j = l; j < n; i++, j++) { if (s[i] == '(' && s[j] == ')') dp[i][j] = 2 + dp[i + 1][j - 1]; for (let k = i; k < j; k++) dp[i][j] = Math.max(dp[i][j], dp[i][k] + dp[k + 1][j]); } } return dp[0][n - 1]; } let s = \"()(((((()\"; let n = s.length; document.write(maxLength(s, n)); </script>", "e": 7419, "s": 6332, "text": null }, { "code": null, "e": 7421, "s": 7419, "text": "4" }, { "code": null, "e": 7471, "s": 7423, "text": "Time Complexity : O(n2) Auxiliary Space : O(n2)" }, { "code": null, "e": 7545, "s": 7471, "text": "Approach 2: This approach solves the problem in a more efficient manner. " }, { "code": null, "e": 7984, "s": 7545, "text": "Count the number of braces to be removed to get the longest balanced parentheses sub-sequence.If the i-th index number of close braces is greater than the number of open braces, then that close brace has to be removed.Count the number of close braces that need to be removed.In the end, the number of extra open braces will also be removed.So, the total count to be removed would be the sum of extra open braces and invalid close braces. " }, { "code": null, "e": 8079, "s": 7984, "text": "Count the number of braces to be removed to get the longest balanced parentheses sub-sequence." }, { "code": null, "e": 8204, "s": 8079, "text": "If the i-th index number of close braces is greater than the number of open braces, then that close brace has to be removed." }, { "code": null, "e": 8262, "s": 8204, "text": "Count the number of close braces that need to be removed." }, { "code": null, "e": 8328, "s": 8262, "text": "In the end, the number of extra open braces will also be removed." }, { "code": null, "e": 8427, "s": 8328, "text": "So, the total count to be removed would be the sum of extra open braces and invalid close braces. " }, { "code": null, "e": 8431, "s": 8427, "text": "C++" }, { "code": null, "e": 8436, "s": 8431, "text": "Java" }, { "code": null, "e": 8444, "s": 8436, "text": "Python3" }, { "code": null, "e": 8447, "s": 8444, "text": "C#" }, { "code": null, "e": 8458, "s": 8447, "text": "Javascript" }, { "code": "// C++ program to find length of// the longest balanced subsequence#include <bits/stdc++.h>using namespace std; int maxLength(char s[], int n){ // As it's subsequence - assuming first // open brace would map to a first close // brace which occurs after the open brace // to make subsequence balanced and second // open brace would map to second close // brace and so on. // Variable to count all the open brace // that does not have the corresponding // closing brace. int invalidOpenBraces = 0; // To count all the close brace that // does not have the corresponding open brace. int invalidCloseBraces = 0; // Iterating over the String for (int i = 0; i < n; i++) { if (s[i] == '(') { // Number of open braces that // hasn't been closed yet. invalidOpenBraces++; } else { if (invalidOpenBraces == 0) { // Number of close braces that // cannot be mapped to any open // brace. invalidCloseBraces++; } else { // Mapping the ith close brace // to one of the open brace. invalidOpenBraces--; } } } return ( n - (invalidOpenBraces + invalidCloseBraces));} // Driver Codeint main(){ char s[] = \"()(((((()\"; int n = strlen(s); cout << maxLength(s, n) << endl; return 0;}", "e": 9920, "s": 8458, "text": null }, { "code": "// Java program to find the length of the// longest balanced subsequence.import java.io.*; class GFG { static int maxLength(String s, int n) { // As it's subsequence - assuming first // open brace would map to a first close // brace which occurs after the open brace // to make subsequence balanced and second // open brace would map to second close // brace and so on. // Variable to count all the open brace // that does not have the corresponding // closing brace. int invalidOpenBraces = 0; // To count all the close brace that // does not have the corresponding open brace. int invalidCloseBraces = 0; // Iterating over the String for (int i = 0; i < n; i++) { if (s.charAt(i) == '(') { // Number of open braces that // hasn't been closed yet.vvvvvv invalidOpenBraces++; } else { if (invalidOpenBraces == 0) { // Number of close braces that // cannot be mapped to any open // brace. invalidCloseBraces++; } else { // Mapping the ith close brace // to one of the open brace. invalidOpenBraces--; } } } return ( n - (invalidOpenBraces + invalidCloseBraces)); } // Driver Code public static void main(String[] args) { String s = \"()(((((()\"; int n = s.length(); System.out.println(maxLength(s, n)); }}", "e": 11601, "s": 9920, "text": null }, { "code": "# Python3 program to find length of# the longest balanced subsequence def maxLength(s, n): # As it's subsequence - assuming first # open brace would map to a first close # brace which occurs after the open brace # to make subsequence balanced and second # open brace would map to second close # brace and so on. # Variable to count all the open brace # that does not have the corresponding # closing brace. invalidOpenBraces = 0; # To count all the close brace that does # not have the corresponding open brace. invalidCloseBraces = 0; # Iterating over the String for i in range(n): if( s[i] == '(' ): # Number of open braces that # hasn't been closed yet. invalidOpenBraces += 1 else: if(invalidOpenBraces == 0): # Number of close braces that # cannot be mapped to any open # brace. invalidCloseBraces += 1 else: # Mapping the ith close brace # to one of the open brace. invalidOpenBraces -= 1 return (n - (invalidOpenBraces + invalidCloseBraces)) # Driver Codes = \"()(((((()\"n = len(s)print(maxLength(s, n))", "e": 12887, "s": 11601, "text": null }, { "code": "// C# program to find length of the// longest balanced subsequence.using System; class GFG { static int maxLength(String s, int n) { // As it's subsequence - assuming first // open brace would map to a first close // brace which occurs after the open brace // to make subsequence balanced and second // open brace would map to second close // brace and so on. // Variable to count all the open brace // that does not have the corresponding // closing brace. int invalidOpenBraces = 0; // To count all the close brace that // does not have the corresponding open brace. int invalidCloseBraces = 0; // Iterating over the String for (int i = 0; i < n; i++) { if (s[i] == '(') { // Number of open braces that // hasn't been closed yet. invalidOpenBraces++; } else { if (invalidOpenBraces == 0) { // Number of close braces that // cannot be mapped to any open brace. invalidCloseBraces++; } else { // Mapping the ith close brace to // one of the open brace. invalidOpenBraces--; } } } return ( n - (invalidOpenBraces + invalidCloseBraces)); } // Driver Code public static void Main() { string s = \"()(((((()\"; int n = s.Length; Console.WriteLine(maxLength(s, n)); }}", "e": 14509, "s": 12887, "text": null }, { "code": "<script> // Javascript program to find the length of the// longest balanced subsequence. function maxLength(s, n) { // As it's subsequence - assuming first // open brace would map to a first close // brace which occurs after the open brace // to make subsequence balanced and second // open brace would map to second close // brace and so on. // Variable to count all the open brace // that does not have the corresponding // closing brace. let invalidOpenBraces = 0; // To count all the close brace that // does not have the corresponding open brace. let invalidCloseBraces = 0; // Iterating over the String for (let i = 0; i < n; i++) { if (s[i] == '(') { // Number of open braces that // hasn't been closed yet.vvvvvv invalidOpenBraces++; } else { if (invalidOpenBraces == 0) { // Number of close braces that // cannot be mapped to any open // brace. invalidCloseBraces++; } else { // Mapping the ith close brace // to one of the open brace. invalidOpenBraces--; } } } return ( n - (invalidOpenBraces + invalidCloseBraces)); } // driver program let s = \"()(((((()\"; let n = s.length; document.write(maxLength(s, n)); </script>", "e": 16123, "s": 14509, "text": null }, { "code": null, "e": 16125, "s": 16123, "text": "4" }, { "code": null, "e": 16173, "s": 16127, "text": "Time Complexity : O(n) Auxiliary Space : O(1)" }, { "code": null, "e": 16593, "s": 16173, "text": "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 contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 16598, "s": 16593, "text": "vt_m" }, { "code": null, "e": 16613, "s": 16598, "text": "sahilshelangia" }, { "code": null, "e": 16619, "s": 16613, "text": "ukasp" }, { "code": null, "e": 16633, "s": 16619, "text": "mayankbansal2" }, { "code": null, "e": 16649, "s": 16633, "text": "souravghosh0416" }, { "code": null, "e": 16658, "s": 16649, "text": "suresh07" }, { "code": null, "e": 16670, "s": 16658, "text": "subsequence" }, { "code": null, "e": 16690, "s": 16670, "text": "Dynamic Programming" }, { "code": null, "e": 16698, "s": 16690, "text": "Strings" }, { "code": null, "e": 16706, "s": 16698, "text": "Strings" }, { "code": null, "e": 16726, "s": 16706, "text": "Dynamic Programming" }, { "code": null, "e": 16824, "s": 16726, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 16853, "s": 16824, "text": "0-1 Knapsack Problem | DP-10" }, { "code": null, "e": 16885, "s": 16853, "text": "Largest Sum Contiguous Subarray" }, { "code": null, "e": 16915, "s": 16885, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 16949, "s": 16915, "text": "Longest Common Subsequence | DP-4" }, { "code": null, "e": 16987, "s": 16949, "text": "Longest Increasing Subsequence | DP-3" }, { "code": null, "e": 17033, "s": 16987, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 17058, "s": 17033, "text": "Reverse a string in Java" }, { "code": null, "e": 17073, "s": 17058, "text": "C++ Data Types" }, { "code": null, "e": 17133, "s": 17073, "text": "Write a program to print all permutations of a given string" } ]
Element methods in Selenium Python
11 May, 2020 Selenium’s Python Module is built to perform automated testing with Python. Selenium in Python works with elements. An element can be a tag, property, or anything, it is an instance of class selenium.webdriver.remote.webelement.WebElement. After you find an element on screen using selenium, you might want to click it or find sub-elements, etc. Selenium provides methods around this WebElement of Selenium. In this article, we have discussed various methods that one can use to perform multiple tasks with Selenium and its WebElement. To use a method on a WebElement, first of all we need to locate it into the webpage. There are various methods n how to locate an element in Selenium Python. Checkout – Locator Strategies – Selenium Python. After you have grabbed an element you can use a method according to following syntax –Syntax – element.method_name 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") element = driver.find_element_by_xpath("//input[@id='passwd-id']") Also, to find multiple elements, we can use – elements = driver.find_elements_by_name("passwd") Now one can use any method as – element.method_name Python-selenium selenium Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n11 May, 2020" }, { "code": null, "e": 564, "s": 28, "text": "Selenium’s Python Module is built to perform automated testing with Python. Selenium in Python works with elements. An element can be a tag, property, or anything, it is an instance of class selenium.webdriver.remote.webelement.WebElement. After you find an element on screen using selenium, you might want to click it or find sub-elements, etc. Selenium provides methods around this WebElement of Selenium. In this article, we have discussed various methods that one can use to perform multiple tasks with Selenium and its WebElement." }, { "code": null, "e": 866, "s": 564, "text": "To use a method on a WebElement, first of all we need to locate it into the webpage. There are various methods n how to locate an element in Selenium Python. Checkout – Locator Strategies – Selenium Python. After you have grabbed an element you can use a method according to following syntax –Syntax –" }, { "code": null, "e": 886, "s": 866, "text": "element.method_name" }, { "code": null, "e": 896, "s": 886, "text": "Example –" }, { "code": "<input type=\"text\" name=\"passwd\" id=\"passwd-id\" />", "e": 947, "s": 896, "text": null }, { "code": null, "e": 1028, "s": 947, "text": "To find an element one needs to use one of the locating strategies, For example," }, { "code": null, "e": 1192, "s": 1028, "text": "element = driver.find_element_by_id(\"passwd-id\")\nelement = driver.find_element_by_name(\"passwd\")\nelement = driver.find_element_by_xpath(\"//input[@id='passwd-id']\")" }, { "code": null, "e": 1238, "s": 1192, "text": "Also, to find multiple elements, we can use –" }, { "code": null, "e": 1288, "s": 1238, "text": "elements = driver.find_elements_by_name(\"passwd\")" }, { "code": null, "e": 1320, "s": 1288, "text": "Now one can use any method as –" }, { "code": null, "e": 1340, "s": 1320, "text": "element.method_name" }, { "code": null, "e": 1356, "s": 1340, "text": "Python-selenium" }, { "code": null, "e": 1365, "s": 1356, "text": "selenium" }, { "code": null, "e": 1372, "s": 1365, "text": "Python" } ]
How to use Regex to get the string between curly braces using JavaScript ?
17 Sep, 2019 The problem is to get the string between the curly braces. Here we are going to see different Regular Expressions to get the string. Approach 1: Selecting the string between the outer curly braces. The RegExp selects the all curly braces, removes them and then get the content. Example: This example illustrate the above approach . <!DOCTYPE HTML><html> <head> <title> How to use Regex to get the string between curly braces using JavaScript ? </title></head> <body style="text-align:center;"> <h1 id="h1" style="color:green;"> GeeksforGeeks </h1> <p id="GFG_UP" style= "font-size: 15px; font-weight: bold;"> </p> <button onclick="gfg_Run()"> Click here </button> <p id="GFG_DOWN" style= "font-size: 23px; font-weight: bold; color: green; "> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var st = '{This is GeeksforGeeks}'; el_up.innerHTML = "Click on the button to get the content between" + " the curly brackets.<br> Str = '" + st + "'"; function gfg_Run() { st = st.replace(/\{|\}/gi, ''); el_down.innerHTML = st; } </script></body> </html> Output: Before clicking on the button: After clicking on the button: Approach 2: In this approach we are selecting the string between the curly braces. The RegExp selects the string from right side. It looks for the opening curly brace from the rightmost curly brace and print that as string. Example: This example illustrate the above approach . <!DOCTYPE HTML><html> <head> <title> How to use Regex to get the string between curly braces using JavaScript ? </title></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksforGeeks </h1> <p id="GFG_UP" style= "font-size: 15px; font-weight: bold;"> </p> <button onclick="gfg_Run()"> Click here </button> <p id="GFG_DOWN" style= "font-size: 23px; font-weight: bold; color: green; "> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var st = '{This is {GeeksforGeeks}}'; el_up.innerHTML = "Click on the button to get the " + "content between the curly brackets.<br>" + "Str = '" + st + "'"; function gfg_Run() { st = st.replace(/.*\{|\}/gi, ''); el_down.innerHTML = st; } </script></body> </html> Output: Before clicking on the button: After clicking on the button: JavaScript-Misc 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 Difference Between PUT and PATCH Request Roadmap to Learn JavaScript For Beginners 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": "\n17 Sep, 2019" }, { "code": null, "e": 161, "s": 28, "text": "The problem is to get the string between the curly braces. Here we are going to see different Regular Expressions to get the string." }, { "code": null, "e": 173, "s": 161, "text": "Approach 1:" }, { "code": null, "e": 226, "s": 173, "text": "Selecting the string between the outer curly braces." }, { "code": null, "e": 306, "s": 226, "text": "The RegExp selects the all curly braces, removes them and then get the content." }, { "code": null, "e": 360, "s": 306, "text": "Example: This example illustrate the above approach ." }, { "code": "<!DOCTYPE HTML><html> <head> <title> How to use Regex to get the string between curly braces using JavaScript ? </title></head> <body style=\"text-align:center;\"> <h1 id=\"h1\" style=\"color:green;\"> GeeksforGeeks </h1> <p id=\"GFG_UP\" style= \"font-size: 15px; font-weight: bold;\"> </p> <button onclick=\"gfg_Run()\"> Click here </button> <p id=\"GFG_DOWN\" style= \"font-size: 23px; font-weight: bold; color: green; \"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); var st = '{This is GeeksforGeeks}'; el_up.innerHTML = \"Click on the button to get the content between\" + \" the curly brackets.<br> Str = '\" + st + \"'\"; function gfg_Run() { st = st.replace(/\\{|\\}/gi, ''); el_down.innerHTML = st; } </script></body> </html>", "e": 1349, "s": 360, "text": null }, { "code": null, "e": 1357, "s": 1349, "text": "Output:" }, { "code": null, "e": 1388, "s": 1357, "text": "Before clicking on the button:" }, { "code": null, "e": 1418, "s": 1388, "text": "After clicking on the button:" }, { "code": null, "e": 1430, "s": 1418, "text": "Approach 2:" }, { "code": null, "e": 1501, "s": 1430, "text": "In this approach we are selecting the string between the curly braces." }, { "code": null, "e": 1642, "s": 1501, "text": "The RegExp selects the string from right side. It looks for the opening curly brace from the rightmost curly brace and print that as string." }, { "code": null, "e": 1696, "s": 1642, "text": "Example: This example illustrate the above approach ." }, { "code": "<!DOCTYPE HTML><html> <head> <title> How to use Regex to get the string between curly braces using JavaScript ? </title></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <p id=\"GFG_UP\" style= \"font-size: 15px; font-weight: bold;\"> </p> <button onclick=\"gfg_Run()\"> Click here </button> <p id=\"GFG_DOWN\" style= \"font-size: 23px; font-weight: bold; color: green; \"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); var st = '{This is {GeeksforGeeks}}'; el_up.innerHTML = \"Click on the button to get the \" + \"content between the curly brackets.<br>\" + \"Str = '\" + st + \"'\"; function gfg_Run() { st = st.replace(/.*\\{|\\}/gi, ''); el_down.innerHTML = st; } </script></body> </html>", "e": 2693, "s": 1696, "text": null }, { "code": null, "e": 2701, "s": 2693, "text": "Output:" }, { "code": null, "e": 2732, "s": 2701, "text": "Before clicking on the button:" }, { "code": null, "e": 2762, "s": 2732, "text": "After clicking on the button:" }, { "code": null, "e": 2778, "s": 2762, "text": "JavaScript-Misc" }, { "code": null, "e": 2789, "s": 2778, "text": "JavaScript" }, { "code": null, "e": 2806, "s": 2789, "text": "Web Technologies" }, { "code": null, "e": 2833, "s": 2806, "text": "Web technologies Questions" }, { "code": null, "e": 2931, "s": 2833, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2992, "s": 2931, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3064, "s": 2992, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 3104, "s": 3064, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 3145, "s": 3104, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 3187, "s": 3145, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 3249, "s": 3187, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 3282, "s": 3249, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 3343, "s": 3282, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3393, "s": 3343, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
How to Split a String in Golang?
02 Mar, 2022 In Go language, strings are different from other languages like Java, C++, Python, etc. It is a sequence of variable-width characters where each and every character is represented by one or more bytes using UTF-8 Encoding. In Go strings, you are allowed to split a string into a slice with the help of the following functions. These functions are defined under the strings package so, you have to import strings package in your program for accessing these functions:1. Split: This function splits a string into all substrings separated by the given separator and returns a slice that contains these substrings.Syntax: func Split(str, sep string) []string Here, str is the string and sep is the separator. If str does not contain the given sep and sep is non-empty, then it will return a slice of length 1 which contains only str. Or if the sep is empty, then it will split after each UTF-8 sequence. Or if both str and sep are empty, then it will return an empty slice. Example: C // Go program to illustrate how to split a stringpackage main import ( "fmt" "strings") // Main functionfunc main() { // Creating and initializing the strings str1 := "Welcome, to the, online portal, of GeeksforGeeks" str2 := "My dog name is Dollar" str3 := "I like to play Ludo" // Displaying strings fmt.Println("String 1: ", str1) fmt.Println("String 2: ", str2) fmt.Println("String 3: ", str3) // Splitting the given strings // Using Split() function res1 := strings.Split(str1, ",") res2 := strings.Split(str2, "") res3 := strings.Split(str3, "!") res4 := strings.Split("", "GeeksforGeeks, geeks") // Displaying the result fmt.Println("\nResult 1: ", res1) fmt.Println("Result 2: ", res2) fmt.Println("Result 3: ", res3) fmt.Println("Result 4: ", res4) } Output: String 1: Welcome, to the, online portal, of GeeksforGeeks String 2: My dog name is Dollar String 3: I like to play Ludo Result 1: [Welcome to the online portal of GeeksforGeeks] Result 2: [M y d o g n a m e i s D o l l a r] Result 3: [I like to play Ludo] Result 4: [] 2. SplitAfter: This function splits a string into all substrings after each instance of the given separator and returns a slice that contains these substrings.Syntax: func SplitAfter(str, sep string) []string Here, str is the string and sep is the separator. If str does not contain the given sep and sep is non-empty, then it will return a slice of length 1 which contains only str. Or if the sep is empty, then it will split after each UTF-8 sequence. Or if both str and sep are empty, then it will return an empty slice. Example: C // Go program to illustrate how to split a stringpackage main import ( "fmt" "strings") // Main functionfunc main() { // Creating and initializing the strings str1 := "Welcome, to the, online portal, of GeeksforGeeks" str2 := "My dog name is Dollar" str3 := "I like to play Ludo" // Displaying strings fmt.Println("String 1: ", str1) fmt.Println("String 2: ", str2) fmt.Println("String 3: ", str3) // Splitting the given strings // Using SplitAfter() function res1 := strings.SplitAfter(str1, ",") res2 := strings.SplitAfter(str2, "") res3 := strings.SplitAfter(str3, "!") res4 := strings.SplitAfter("", "GeeksforGeeks, geeks") // Displaying the result fmt.Println("\nResult 1: ", res1) fmt.Println("Result 2: ", res2) fmt.Println("Result 3: ", res3) fmt.Println("Result 4: ", res4) } Output: String 1: Welcome, to the, online portal, of GeeksforGeeks String 2: My dog name is Dollar String 3: I like to play Ludo Result 1: [Welcome, to the, online portal, of GeeksforGeeks] Result 2: [M y d o g n a m e i s N a w a b] Result 3: [I like to play Ludo] Result 4: [] 3. SplitAfterN: This function splits a string into all substrings after each instance of the given separator and returns a slice that contains these substrings.Syntax: func SplitAfterN(str, sep string, m int) []string Here, str is the string, sep is the separator, and m is used to find the number of substrings to return. Here, if m>0, then it returns at most m substrings and the last string substring will not split. If m == 0, then it will return nil. If m<0, then it will return all substrings.Example: C // Go program to illustrate how to split a stringpackage main import ( "fmt" "strings") // Main functionfunc main() { // Creating and initializing the strings str1 := "Welcome, to the, online portal, of GeeksforGeeks" str2 := "My dog name is Dollar" str3 := "I like to play Ludo" // Displaying strings fmt.Println("String 1: ", str1) fmt.Println("String 2: ", str2) fmt.Println("String 3: ", str3) // Splitting the given strings // Using SplitAfterN() function res1 := strings.SplitAfterN(str1, ",", 2) res2 := strings.SplitAfterN(str2, "", 4) res3 := strings.SplitAfterN(str3, "!", 1) res4 := strings.SplitAfterN("", "GeeksforGeeks, geeks", 3) // Displaying the result fmt.Println("\nResult 1: ", res1) fmt.Println("Result 2: ", res2) fmt.Println("Result 3: ", res3) fmt.Println("Result 4: ", res4) } Output: String 1: Welcome, to the, online portal, of GeeksforGeeks String 2: My dog name is Dollar String 3: I like to play Ludo Result 1: [Welcome, to the, online portal, of GeeksforGeeks] Result 2: [M y dog name is Dollar] Result 3: [I like to play Ludo] Result 4: [] Gulsan Borbhuiya Golang Golang-String Go Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Different ways to concatenate two strings in Golang time.Sleep() Function in Golang With Examples strings.Contains Function in Golang with Examples strings.Replace() Function in Golang With Examples fmt.Sprintf() Function in Golang With Examples Golang Maps Time Formatting in Golang Interfaces in Golang Different Ways to Find the Type of Variable in Golang How to Parse JSON in Golang?
[ { "code": null, "e": 53, "s": 25, "text": "\n02 Mar, 2022" }, { "code": null, "e": 672, "s": 53, "text": "In Go language, strings are different from other languages like Java, C++, Python, etc. It is a sequence of variable-width characters where each and every character is represented by one or more bytes using UTF-8 Encoding. In Go strings, you are allowed to split a string into a slice with the help of the following functions. These functions are defined under the strings package so, you have to import strings package in your program for accessing these functions:1. Split: This function splits a string into all substrings separated by the given separator and returns a slice that contains these substrings.Syntax: " }, { "code": null, "e": 709, "s": 672, "text": "func Split(str, sep string) []string" }, { "code": null, "e": 1033, "s": 709, "text": "Here, str is the string and sep is the separator. If str does not contain the given sep and sep is non-empty, then it will return a slice of length 1 which contains only str. Or if the sep is empty, then it will split after each UTF-8 sequence. Or if both str and sep are empty, then it will return an empty slice. Example:" }, { "code": null, "e": 1035, "s": 1033, "text": "C" }, { "code": "// Go program to illustrate how to split a stringpackage main import ( \"fmt\" \"strings\") // Main functionfunc main() { // Creating and initializing the strings str1 := \"Welcome, to the, online portal, of GeeksforGeeks\" str2 := \"My dog name is Dollar\" str3 := \"I like to play Ludo\" // Displaying strings fmt.Println(\"String 1: \", str1) fmt.Println(\"String 2: \", str2) fmt.Println(\"String 3: \", str3) // Splitting the given strings // Using Split() function res1 := strings.Split(str1, \",\") res2 := strings.Split(str2, \"\") res3 := strings.Split(str3, \"!\") res4 := strings.Split(\"\", \"GeeksforGeeks, geeks\") // Displaying the result fmt.Println(\"\\nResult 1: \", res1) fmt.Println(\"Result 2: \", res2) fmt.Println(\"Result 3: \", res3) fmt.Println(\"Result 4: \", res4) }", "e": 1863, "s": 1035, "text": null }, { "code": null, "e": 1871, "s": 1863, "text": "Output:" }, { "code": null, "e": 2160, "s": 1871, "text": "String 1: Welcome, to the, online portal, of GeeksforGeeks\nString 2: My dog name is Dollar\nString 3: I like to play Ludo\n\nResult 1: [Welcome to the online portal of GeeksforGeeks]\nResult 2: [M y d o g n a m e i s D o l l a r]\nResult 3: [I like to play Ludo]\nResult 4: []" }, { "code": null, "e": 2328, "s": 2160, "text": "2. SplitAfter: This function splits a string into all substrings after each instance of the given separator and returns a slice that contains these substrings.Syntax: " }, { "code": null, "e": 2370, "s": 2328, "text": "func SplitAfter(str, sep string) []string" }, { "code": null, "e": 2694, "s": 2370, "text": "Here, str is the string and sep is the separator. If str does not contain the given sep and sep is non-empty, then it will return a slice of length 1 which contains only str. Or if the sep is empty, then it will split after each UTF-8 sequence. Or if both str and sep are empty, then it will return an empty slice. Example:" }, { "code": null, "e": 2696, "s": 2694, "text": "C" }, { "code": "// Go program to illustrate how to split a stringpackage main import ( \"fmt\" \"strings\") // Main functionfunc main() { // Creating and initializing the strings str1 := \"Welcome, to the, online portal, of GeeksforGeeks\" str2 := \"My dog name is Dollar\" str3 := \"I like to play Ludo\" // Displaying strings fmt.Println(\"String 1: \", str1) fmt.Println(\"String 2: \", str2) fmt.Println(\"String 3: \", str3) // Splitting the given strings // Using SplitAfter() function res1 := strings.SplitAfter(str1, \",\") res2 := strings.SplitAfter(str2, \"\") res3 := strings.SplitAfter(str3, \"!\") res4 := strings.SplitAfter(\"\", \"GeeksforGeeks, geeks\") // Displaying the result fmt.Println(\"\\nResult 1: \", res1) fmt.Println(\"Result 2: \", res2) fmt.Println(\"Result 3: \", res3) fmt.Println(\"Result 4: \", res4) }", "e": 3548, "s": 2696, "text": null }, { "code": null, "e": 3556, "s": 3548, "text": "Output:" }, { "code": null, "e": 3846, "s": 3556, "text": "String 1: Welcome, to the, online portal, of GeeksforGeeks\nString 2: My dog name is Dollar\nString 3: I like to play Ludo\n\nResult 1: [Welcome, to the, online portal, of GeeksforGeeks]\nResult 2: [M y d o g n a m e i s N a w a b]\nResult 3: [I like to play Ludo]\nResult 4: []" }, { "code": null, "e": 4015, "s": 3846, "text": "3. SplitAfterN: This function splits a string into all substrings after each instance of the given separator and returns a slice that contains these substrings.Syntax: " }, { "code": null, "e": 4065, "s": 4015, "text": "func SplitAfterN(str, sep string, m int) []string" }, { "code": null, "e": 4355, "s": 4065, "text": "Here, str is the string, sep is the separator, and m is used to find the number of substrings to return. Here, if m>0, then it returns at most m substrings and the last string substring will not split. If m == 0, then it will return nil. If m<0, then it will return all substrings.Example:" }, { "code": null, "e": 4357, "s": 4355, "text": "C" }, { "code": "// Go program to illustrate how to split a stringpackage main import ( \"fmt\" \"strings\") // Main functionfunc main() { // Creating and initializing the strings str1 := \"Welcome, to the, online portal, of GeeksforGeeks\" str2 := \"My dog name is Dollar\" str3 := \"I like to play Ludo\" // Displaying strings fmt.Println(\"String 1: \", str1) fmt.Println(\"String 2: \", str2) fmt.Println(\"String 3: \", str3) // Splitting the given strings // Using SplitAfterN() function res1 := strings.SplitAfterN(str1, \",\", 2) res2 := strings.SplitAfterN(str2, \"\", 4) res3 := strings.SplitAfterN(str3, \"!\", 1) res4 := strings.SplitAfterN(\"\", \"GeeksforGeeks, geeks\", 3) // Displaying the result fmt.Println(\"\\nResult 1: \", res1) fmt.Println(\"Result 2: \", res2) fmt.Println(\"Result 3: \", res3) fmt.Println(\"Result 4: \", res4) }", "e": 5226, "s": 4357, "text": null }, { "code": null, "e": 5234, "s": 5226, "text": "Output:" }, { "code": null, "e": 5508, "s": 5234, "text": "String 1: Welcome, to the, online portal, of GeeksforGeeks\nString 2: My dog name is Dollar\nString 3: I like to play Ludo\n\nResult 1: [Welcome, to the, online portal, of GeeksforGeeks]\nResult 2: [M y dog name is Dollar]\nResult 3: [I like to play Ludo]\nResult 4: [] " }, { "code": null, "e": 5525, "s": 5508, "text": "Gulsan Borbhuiya" }, { "code": null, "e": 5532, "s": 5525, "text": "Golang" }, { "code": null, "e": 5546, "s": 5532, "text": "Golang-String" }, { "code": null, "e": 5558, "s": 5546, "text": "Go Language" }, { "code": null, "e": 5656, "s": 5558, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5708, "s": 5656, "text": "Different ways to concatenate two strings in Golang" }, { "code": null, "e": 5754, "s": 5708, "text": "time.Sleep() Function in Golang With Examples" }, { "code": null, "e": 5804, "s": 5754, "text": "strings.Contains Function in Golang with Examples" }, { "code": null, "e": 5855, "s": 5804, "text": "strings.Replace() Function in Golang With Examples" }, { "code": null, "e": 5902, "s": 5855, "text": "fmt.Sprintf() Function in Golang With Examples" }, { "code": null, "e": 5914, "s": 5902, "text": "Golang Maps" }, { "code": null, "e": 5940, "s": 5914, "text": "Time Formatting in Golang" }, { "code": null, "e": 5961, "s": 5940, "text": "Interfaces in Golang" }, { "code": null, "e": 6015, "s": 5961, "text": "Different Ways to Find the Type of Variable in Golang" } ]
Reading and writing binary file in C/C++
To write a binary file in C++ use write method. It is used to write a given number of bytes on the given stream, starting at the position of the "put" pointer. The file is extended if the put pointer is currently at the end of the file. If this pointer points into the middle of the file, characters in the file are overwritten with the new data. If any error has occurred during writing in the file, the stream is placed in an error state. ostream& write(const char*, int); To read a binary file in C++ use read method. It extracts a given number of bytes from the given stream and place them into the memory, pointed to by the first parameter. If any error is occurred during reading in the file, the stream is placed in an error state, all future read operation will be failed then. gcount() can be used to count the number of characters has already read. Then clear() can be used to reset the stream to a usable state. ifstream& write(const char*, int); Begin Create a structure Student to declare variables. Open binary file to write. Check if any error occurs in file opening. Initialize the variables with data. If file open successfully, write the binary data using write method. Close the file for writing. Open the binary file to read. Check if any error occurs in file opening. If file open successfully, read the binary data file using read method. Close the file for reading. Check if any error occurs. Print the data. End. Live Demo #include<iostream> #include<fstream> using namespace std; struct Student { int roll_no; string name; }; int main() { ofstream wf("student.dat", ios::out | ios::binary); if(!wf) { cout << "Cannot open file!" << endl; return 1; } Student wstu[3]; wstu[0].roll_no = 1; wstu[0].name = "Ram"; wstu[1].roll_no = 2; wstu[1].name = "Shyam"; wstu[2].roll_no = 3; wstu[2].name = "Madhu"; for(int i = 0; i < 3; i++) wf.write((char *) &wstu[i], sizeof(Student)); wf.close(); if(!wf.good()) { cout << "Error occurred at writing time!" << endl; return 1; } ifstream rf("student.dat", ios::out | ios::binary); if(!rf) { cout << "Cannot open file!" << endl; return 1; } Student rstu[3]; for(int i = 0; i < 3; i++) rf.read((char *) &rstu[i], sizeof(Student)); rf.close(); if(!rf.good()) { cout << "Error occurred at reading time!" << endl; return 1; } cout<<"Student's Details:"<<endl; for(int i=0; i < 3; i++) { cout << "Roll No: " << wstu[i].roll_no << endl; cout << "Name: " << wstu[i].name << endl; cout << endl; } return 0; } Student’s Details: Roll No: 1 Name: Ram Roll No: 2 Name: Shyam Roll No: 3 Name: Madhu
[ { "code": null, "e": 1534, "s": 1187, "text": "To write a binary file in C++ use write method. It is used to write a given number of bytes on the given stream, starting at the position of the \"put\" pointer. The file is extended if the put pointer is currently at the end of the file. If this pointer points into the middle of the file, characters in the file are overwritten with the new data." }, { "code": null, "e": 1628, "s": 1534, "text": "If any error has occurred during writing in the file, the stream is placed in an error state." }, { "code": null, "e": 1662, "s": 1628, "text": "ostream& write(const char*, int);" }, { "code": null, "e": 1973, "s": 1662, "text": "To read a binary file in C++ use read method. It extracts a given number of bytes from the given stream and place them into the memory, pointed to by the first parameter. If any error is occurred during reading in the file, the stream is placed in an error state, all future read operation will be failed then." }, { "code": null, "e": 2110, "s": 1973, "text": "gcount() can be used to count the number of characters has already read. Then clear() can be used to reset the stream to a usable state." }, { "code": null, "e": 2145, "s": 2110, "text": "ifstream& write(const char*, int);" }, { "code": null, "e": 2666, "s": 2145, "text": "Begin\n Create a structure Student to declare variables.\n Open binary file to write.\n Check if any error occurs in file opening.\n Initialize the variables with data.\n If file open successfully, write the binary data using write method.\n Close the file for writing.\n Open the binary file to read.\n Check if any error occurs in file opening.\n If file open successfully, read the binary data file using read method.\n Close the file for reading.\n Check if any error occurs.\n Print the data.\nEnd." }, { "code": null, "e": 2677, "s": 2666, "text": " Live Demo" }, { "code": null, "e": 3853, "s": 2677, "text": "#include<iostream>\n#include<fstream>\nusing namespace std;\nstruct Student {\n int roll_no;\n string name;\n};\nint main() {\n ofstream wf(\"student.dat\", ios::out | ios::binary);\n if(!wf) {\n cout << \"Cannot open file!\" << endl;\n return 1;\n }\n Student wstu[3];\n wstu[0].roll_no = 1;\n wstu[0].name = \"Ram\";\n wstu[1].roll_no = 2;\n wstu[1].name = \"Shyam\";\n wstu[2].roll_no = 3;\n wstu[2].name = \"Madhu\";\n for(int i = 0; i < 3; i++)\n wf.write((char *) &wstu[i], sizeof(Student));\n wf.close();\n if(!wf.good()) {\n cout << \"Error occurred at writing time!\" << endl;\n return 1;\n }\n ifstream rf(\"student.dat\", ios::out | ios::binary);\n if(!rf) {\n cout << \"Cannot open file!\" << endl;\n return 1;\n }\n Student rstu[3];\n for(int i = 0; i < 3; i++)\n rf.read((char *) &rstu[i], sizeof(Student));\n rf.close();\n if(!rf.good()) {\n cout << \"Error occurred at reading time!\" << endl;\n return 1;\n }\n cout<<\"Student's Details:\"<<endl;\n for(int i=0; i < 3; i++) {\n cout << \"Roll No: \" << wstu[i].roll_no << endl;\n cout << \"Name: \" << wstu[i].name << endl;\n cout << endl;\n }\n return 0;\n}" }, { "code": null, "e": 3939, "s": 3853, "text": "Student’s Details:\nRoll No: 1\nName: Ram\nRoll No: 2\nName: Shyam\nRoll No: 3\nName: Madhu" } ]
XGBoost in R Programming
23 Dec, 2021 XGBoost is a fast and efficient algorithm and is used by winners of many machine learning competitions. XG Boost works only with the numeric variables. It is a part of the boosting technique in which the selection of the sample is done more intelligently to classify observations. There are interfaces of XGBoost in C++, R, Python, Julia, Java, and Scala. The core functions in XGBoost are implemented in C++, thus it is easy to share models among different interfaces. Based on the statistics from the CRAN mirror, the package has been downloaded more than 81, 000 times. XgBoost modeling consists of two techniques: Bagging and Boosting. Bagging: It is an approach where you can take random samples of data, build learning algorithms and take simple means to find bagging probabilities. Boosting: It is an approach where a selection of approaches is made more intelligently i.e more and more weight is given to classify observations. eta: It shrinks the feature weights to make the boosting process more conservative. The range is from 0 to 1. It is also knowm as learning rate or Shrinking factor. Low eta value signifies the model is more robust to overfitting. gamma: The larger the value of gamma, more conservative the algorithm will be. It’s range is from 0 to infinity. max_depth: The maximum depth of a tree can be specified using max_depth parameter. Subsample: It is the proportion of rows that the model will randomly select to grow trees. colsample_bytree: It is the ratio of variables randomly chosen to build each tree in the model. Big Mart dataset consists of 1559 products across 10 stores in different cities. Certain attributes of each product and store have been defined. It consists of 12 features i.e Item_Identifier( is a unique product ID assigned to every distinct item), Item_Weight(includes the weight of the product), Item_Fat_Content(describes whether the product is low fat or not), Item_Visibility(mentions the percentage of the total display area of all products in a store allocated to the particular product), Item_Type(describes the food category to which the item belongs), Item_MRP(Maximum Retail Price (list price) of the product), Outlet_Identifier(unique store ID assigned. It consists of an alphanumeric string of length 6), Outlet_Establishment_Year(mentions the year in which store was established), Outlet_Size(tells the size of the store in terms of ground area covered), Outlet_Location_Type(tells about the size of the city in which the store is located), Outlet_Type(tells whether the outlet is just a grocery store or some sort of supermarket) and Item_Outlet_Sales( sales of the product in the particular store). R # Loading datatrain = fread("Train_UWu5bXk.csv")test = fread("Test_u94Q5KV.csv") # Structurestr(train) Using XGBoost algorithm on the dataset which includes 12 features with 1559 products across 10 stores in different cities. R # Installing Packagesinstall.packages("data.table")install.packages("dplyr")install.packages("ggplot2")install.packages("caret")install.packages("xgboost")install.packages("e1071")install.packages("cowplot") # Loading packageslibrary(data.table) # for reading and manipulation of datalibrary(dplyr) # for data manipulation and joininglibrary(ggplot2) # for plotinglibrary(caret) # for modelinglibrary(xgboost) # for building XGBoost modellibrary(e1071) # for skewnesslibrary(cowplot) # for combining multiple plots # Setting test dataset# Combining datasets# add Item_Outlet_Sales to test datatest[, Item_Outlet_Sales := NA]combi = rbind(train, test) # Missing Value Treatmentmissing_index = which(is.na(combi$Item_Weight))for(i in missing_index){item = combi$Item_Identifier[i]combi$Item_Weight[i] = mean(combi$Item_Weight [combi$Item_Identifier == item], na.rm = T)} # Replacing 0 in Item_Visibility with meanzero_index = which(combi$Item_Visibility == 0)for(i in zero_index){item = combi$Item_Identifier[i]combi$Item_Visibility[i] = mean( combi$Item_Visibility[combi$Item_Identifier == item], na.rm = T)} # Label Encoding# To convert categorical in numericalcombi[, Outlet_Size_num := ifelse(Outlet_Size == "Small", 0, ifelse(Outlet_Size == "Medium", 1, 2))] combi[, Outlet_Location_Type_num := ifelse(Outlet_Location_Type == "Tier 3", 0, ifelse(Outlet_Location_Type == "Tier 2", 1, 2))] combi[, c("Outlet_Size", "Outlet_Location_Type") := NULL] # One Hot Encoding# To convert categorical in numericalohe_1 = dummyVars("~.", data = combi[, -c("Item_Identifier", "Outlet_Establishment_Year", "Item_Type")], fullRank = T)ohe_df = data.table(predict(ohe_1, combi[, -c("Item_Identifier", "Outlet_Establishment_Year", "Item_Type")])) combi = cbind(combi[, "Item_Identifier"], ohe_df) # Remove skewnessskewness(combi$Item_Visibility)skewness(combi$price_per_unit_wt) # log + 1 to avoid division by zerocombi[, Item_Visibility := log(Item_Visibility + 1)] # Scaling and Centering data# index of numeric featuresnum_vars = which(sapply(combi, is.numeric))num_vars_names = names(num_vars) combi_numeric = combi[, setdiff(num_vars_names, "Item_Outlet_Sales"), with = F] prep_num = preProcess(combi_numeric, method = c("center", "scale"))combi_numeric_norm = predict(prep_num, combi_numeric) # removing numeric independent variablescombi[, setdiff(num_vars_names, "Item_Outlet_Sales") := NULL]combi = cbind(combi, combi_numeric_norm) # Splitting data back to train and testtrain = combi[1:nrow(train)]test = combi[(nrow(train) + 1):nrow(combi)] # Removing Item_Outlet_Salestest[, Item_Outlet_Sales := NULL] # Model Building: XGBoostparam_list = list(objective = "reg:linear",eta = 0.01,gamma = 1,max_depth = 6,subsample = 0.8,colsample_bytree = 0.5) # Converting train and test into xgb.DMatrix formatDtrain = xgb.DMatrix( data = as.matrix(train[, -c("Item_Identifier", "Item_Outlet_Sales")]), label = train$Item_Outlet_Sales)Dtest = xgb.DMatrix( data = as.matrix(test[, -c("Item_Identifier")])) # 5-fold cross-validation to# find optimal value of nroundsset.seed(112) # Setting seedxgbcv = xgb.cv(params = param_list, data = Dtrain, nrounds = 1000, nfold = 5, print_every_n = 10, early_stopping_rounds = 30, maximize = F) # Training XGBoost model at nrounds = 428xgb_model = xgb.train(data = Dtrain, params = param_list, nrounds = 428)xgb_model # Variable Importancevar_imp = xgb.importance( feature_names = setdiff(names(train), c("Item_Identifier", "Item_Outlet_Sales")), model = xgb_model) # Importance plotxgb.plot.importance(var_imp) Output: Training of Xgboost model: The xgboost model is trained calculating the train-rmse score and test-rmse score and finding its lowest value in many rounds. Model xgb_model: The XgBoost models consist of 21 features with the objective of regression linear, eta is 0.01, gamma is 1, max_depth is 6, subsample is 0.8, colsample_bytree = 0.5, and silent is 1. Variable Importance plot: The Item_MRP is the most important variable followed by Item_Visibility and Outlet_Location_Type_num. So, Xgboost finds its applications in many sectors of industries and is used with full capacity. kumar_satyam data-science R Machine-Learning R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change Color of Bars in Barchart using ggplot2 in R How to Split Column Into Multiple Columns in R DataFrame? Group by function in R using Dplyr How to Change Axis Scales in R Plots? How to filter R DataFrame by values in a column? R - if statement Logistic Regression in R Programming Replace Specific Characters in String in R How to import an Excel File into R ? Joining of Dataframes in R Programming
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Dec, 2021" }, { "code": null, "e": 180, "s": 28, "text": "XGBoost is a fast and efficient algorithm and is used by winners of many machine learning competitions. XG Boost works only with the numeric variables." }, { "code": null, "e": 669, "s": 180, "text": "It is a part of the boosting technique in which the selection of the sample is done more intelligently to classify observations. There are interfaces of XGBoost in C++, R, Python, Julia, Java, and Scala. The core functions in XGBoost are implemented in C++, thus it is easy to share models among different interfaces. Based on the statistics from the CRAN mirror, the package has been downloaded more than 81, 000 times. XgBoost modeling consists of two techniques: Bagging and Boosting. " }, { "code": null, "e": 818, "s": 669, "text": "Bagging: It is an approach where you can take random samples of data, build learning algorithms and take simple means to find bagging probabilities." }, { "code": null, "e": 965, "s": 818, "text": "Boosting: It is an approach where a selection of approaches is made more intelligently i.e more and more weight is given to classify observations." }, { "code": null, "e": 1195, "s": 965, "text": "eta: It shrinks the feature weights to make the boosting process more conservative. The range is from 0 to 1. It is also knowm as learning rate or Shrinking factor. Low eta value signifies the model is more robust to overfitting." }, { "code": null, "e": 1308, "s": 1195, "text": "gamma: The larger the value of gamma, more conservative the algorithm will be. It’s range is from 0 to infinity." }, { "code": null, "e": 1391, "s": 1308, "text": "max_depth: The maximum depth of a tree can be specified using max_depth parameter." }, { "code": null, "e": 1482, "s": 1391, "text": "Subsample: It is the proportion of rows that the model will randomly select to grow trees." }, { "code": null, "e": 1578, "s": 1482, "text": "colsample_bytree: It is the ratio of variables randomly chosen to build each tree in the model." }, { "code": null, "e": 2695, "s": 1578, "text": "Big Mart dataset consists of 1559 products across 10 stores in different cities. Certain attributes of each product and store have been defined. It consists of 12 features i.e Item_Identifier( is a unique product ID assigned to every distinct item), Item_Weight(includes the weight of the product), Item_Fat_Content(describes whether the product is low fat or not), Item_Visibility(mentions the percentage of the total display area of all products in a store allocated to the particular product), Item_Type(describes the food category to which the item belongs), Item_MRP(Maximum Retail Price (list price) of the product), Outlet_Identifier(unique store ID assigned. It consists of an alphanumeric string of length 6), Outlet_Establishment_Year(mentions the year in which store was established), Outlet_Size(tells the size of the store in terms of ground area covered), Outlet_Location_Type(tells about the size of the city in which the store is located), Outlet_Type(tells whether the outlet is just a grocery store or some sort of supermarket) and Item_Outlet_Sales( sales of the product in the particular store). " }, { "code": null, "e": 2697, "s": 2695, "text": "R" }, { "code": "# Loading datatrain = fread(\"Train_UWu5bXk.csv\")test = fread(\"Test_u94Q5KV.csv\") # Structurestr(train)", "e": 2800, "s": 2697, "text": null }, { "code": null, "e": 2924, "s": 2800, "text": "Using XGBoost algorithm on the dataset which includes 12 features with 1559 products across 10 stores in different cities. " }, { "code": null, "e": 2926, "s": 2924, "text": "R" }, { "code": "# Installing Packagesinstall.packages(\"data.table\")install.packages(\"dplyr\")install.packages(\"ggplot2\")install.packages(\"caret\")install.packages(\"xgboost\")install.packages(\"e1071\")install.packages(\"cowplot\") # Loading packageslibrary(data.table) # for reading and manipulation of datalibrary(dplyr) # for data manipulation and joininglibrary(ggplot2) # for plotinglibrary(caret) # for modelinglibrary(xgboost) # for building XGBoost modellibrary(e1071) # for skewnesslibrary(cowplot) # for combining multiple plots # Setting test dataset# Combining datasets# add Item_Outlet_Sales to test datatest[, Item_Outlet_Sales := NA]combi = rbind(train, test) # Missing Value Treatmentmissing_index = which(is.na(combi$Item_Weight))for(i in missing_index){item = combi$Item_Identifier[i]combi$Item_Weight[i] = mean(combi$Item_Weight [combi$Item_Identifier == item], na.rm = T)} # Replacing 0 in Item_Visibility with meanzero_index = which(combi$Item_Visibility == 0)for(i in zero_index){item = combi$Item_Identifier[i]combi$Item_Visibility[i] = mean( combi$Item_Visibility[combi$Item_Identifier == item], na.rm = T)} # Label Encoding# To convert categorical in numericalcombi[, Outlet_Size_num := ifelse(Outlet_Size == \"Small\", 0, ifelse(Outlet_Size == \"Medium\", 1, 2))] combi[, Outlet_Location_Type_num := ifelse(Outlet_Location_Type == \"Tier 3\", 0, ifelse(Outlet_Location_Type == \"Tier 2\", 1, 2))] combi[, c(\"Outlet_Size\", \"Outlet_Location_Type\") := NULL] # One Hot Encoding# To convert categorical in numericalohe_1 = dummyVars(\"~.\", data = combi[, -c(\"Item_Identifier\", \"Outlet_Establishment_Year\", \"Item_Type\")], fullRank = T)ohe_df = data.table(predict(ohe_1, combi[, -c(\"Item_Identifier\", \"Outlet_Establishment_Year\", \"Item_Type\")])) combi = cbind(combi[, \"Item_Identifier\"], ohe_df) # Remove skewnessskewness(combi$Item_Visibility)skewness(combi$price_per_unit_wt) # log + 1 to avoid division by zerocombi[, Item_Visibility := log(Item_Visibility + 1)] # Scaling and Centering data# index of numeric featuresnum_vars = which(sapply(combi, is.numeric))num_vars_names = names(num_vars) combi_numeric = combi[, setdiff(num_vars_names, \"Item_Outlet_Sales\"), with = F] prep_num = preProcess(combi_numeric, method = c(\"center\", \"scale\"))combi_numeric_norm = predict(prep_num, combi_numeric) # removing numeric independent variablescombi[, setdiff(num_vars_names, \"Item_Outlet_Sales\") := NULL]combi = cbind(combi, combi_numeric_norm) # Splitting data back to train and testtrain = combi[1:nrow(train)]test = combi[(nrow(train) + 1):nrow(combi)] # Removing Item_Outlet_Salestest[, Item_Outlet_Sales := NULL] # Model Building: XGBoostparam_list = list(objective = \"reg:linear\",eta = 0.01,gamma = 1,max_depth = 6,subsample = 0.8,colsample_bytree = 0.5) # Converting train and test into xgb.DMatrix formatDtrain = xgb.DMatrix( data = as.matrix(train[, -c(\"Item_Identifier\", \"Item_Outlet_Sales\")]), label = train$Item_Outlet_Sales)Dtest = xgb.DMatrix( data = as.matrix(test[, -c(\"Item_Identifier\")])) # 5-fold cross-validation to# find optimal value of nroundsset.seed(112) # Setting seedxgbcv = xgb.cv(params = param_list, data = Dtrain, nrounds = 1000, nfold = 5, print_every_n = 10, early_stopping_rounds = 30, maximize = F) # Training XGBoost model at nrounds = 428xgb_model = xgb.train(data = Dtrain, params = param_list, nrounds = 428)xgb_model # Variable Importancevar_imp = xgb.importance( feature_names = setdiff(names(train), c(\"Item_Identifier\", \"Item_Outlet_Sales\")), model = xgb_model) # Importance plotxgb.plot.importance(var_imp)", "e": 6850, "s": 2926, "text": null }, { "code": null, "e": 6859, "s": 6850, "text": "Output: " }, { "code": null, "e": 6886, "s": 6859, "text": "Training of Xgboost model:" }, { "code": null, "e": 7013, "s": 6886, "text": "The xgboost model is trained calculating the train-rmse score and test-rmse score and finding its lowest value in many rounds." }, { "code": null, "e": 7030, "s": 7013, "text": "Model xgb_model:" }, { "code": null, "e": 7213, "s": 7030, "text": "The XgBoost models consist of 21 features with the objective of regression linear, eta is 0.01, gamma is 1, max_depth is 6, subsample is 0.8, colsample_bytree = 0.5, and silent is 1." }, { "code": null, "e": 7239, "s": 7213, "text": "Variable Importance plot:" }, { "code": null, "e": 7342, "s": 7239, "text": "The Item_MRP is the most important variable followed by Item_Visibility and Outlet_Location_Type_num. " }, { "code": null, "e": 7439, "s": 7342, "text": "So, Xgboost finds its applications in many sectors of industries and is used with full capacity." }, { "code": null, "e": 7452, "s": 7439, "text": "kumar_satyam" }, { "code": null, "e": 7465, "s": 7452, "text": "data-science" }, { "code": null, "e": 7484, "s": 7465, "text": "R Machine-Learning" }, { "code": null, "e": 7495, "s": 7484, "text": "R Language" }, { "code": null, "e": 7593, "s": 7495, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7645, "s": 7593, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 7703, "s": 7645, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 7738, "s": 7703, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 7776, "s": 7738, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 7825, "s": 7776, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 7842, "s": 7825, "text": "R - if statement" }, { "code": null, "e": 7879, "s": 7842, "text": "Logistic Regression in R Programming" }, { "code": null, "e": 7922, "s": 7879, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 7959, "s": 7922, "text": "How to import an Excel File into R ?" } ]
Simplified Data Encryption Standard Key Generation
27 Sep, 2021 Simplified Data Encryption Standard (S-DES) is a simple version of the DES Algorithm. It is similar to the DES algorithm but is a smaller algorithm and has fewer parameters than DES. It was made for educational purposes so that understanding DES would become simpler. It is a block cipher that takes a block of plain text and converts it into ciphertext. It takes a block of 8 bit. It is a symmetric key cipher i.e. they use the same key for both encryption and decryption. In this article, we are going to demonstrate key generation for s-des encryption and decryption algorithm. We take a random 10-bit key and produce two 8-bit keys which will be used for encryption and decryption. Key Generation Concept: In the key generation algorithm, we accept the 10-bit key and convert it into two 8 bit keys. This key is shared between both sender and receiver. In the key generation, we use three functions: 1. Permutation P10 2. Permutation P8 3. Left Shift Step 1: We accepted a 10-bit key and permuted the bits by putting them in the P10 table. Key = 1 0 1 0 0 0 0 0 1 0 (k1, k2, k3, k4, k5, k6, k7, k8, k9, k10) = (1, 0, 1, 0, 0, 0, 0, 0, 1, 0) P10 Permutation is: P10(k1, k2, k3, k4, k5, k6, k7, k8, k9, k10) = (k3, k5, k2, k7, k4, k10, k1, k9, k8, k6) After P10, we get 1 0 0 0 0 0 1 1 0 0 Step 2: We divide the key into 2 halves of 5-bit each. l=1 0 0 0 0, r=0 1 1 0 0 Step 3: Now we apply one bit left-shift on each key. l = 0 0 0 0 1, r = 1 1 0 0 0 Step 4: Combine both keys after step 3 and permute the bits by putting them in the P8 table. The output of the given table is the first key K1. After LS-1 combined, we get 0 0 0 0 1 1 1 0 0 0 P8 permutation is: P8(k1, k2, k3, k4, k5, k6, k7, k8, k9, k10) = (k6, k3, k7, k4, k8, k5, k10, k9) After P8, we get Key-1 : 1 0 1 0 0 1 0 0 Step 5: The output obtained from step 3 i.e. 2 halves after one bit left shift should again undergo the process of two-bit left shift. Step 3 output - l = 0 0 0 0 1, r = 1 1 0 0 0 After two bit shift - l = 0 0 1 0 0, r = 0 0 0 1 1 Step 6: Combine the 2 halves obtained from step 5 and permute them by putting them in the P8 table. The output of the given table is the second key K2. After LS-2 combined = 0 0 1 0 0 0 0 0 1 1 P8 permutation is: P8(k1, k2, k3, k4, k5, k6, k7, k8, k9, k10) = (k6, k3, k7, k4, k8, k5, k10, k9) After P8, we get Key-2 : 0 1 0 0 0 0 1 1 Final Output: Key-1 is: 1 0 1 0 0 1 0 0 Key-2 is: 0 1 0 0 0 0 1 1 guptaaman9981 cryptography Computer Networks cryptography Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n27 Sep, 2021" }, { "code": null, "e": 436, "s": 52, "text": "Simplified Data Encryption Standard (S-DES) is a simple version of the DES Algorithm. It is similar to the DES algorithm but is a smaller algorithm and has fewer parameters than DES. It was made for educational purposes so that understanding DES would become simpler. It is a block cipher that takes a block of plain text and converts it into ciphertext. It takes a block of 8 bit." }, { "code": null, "e": 740, "s": 436, "text": "It is a symmetric key cipher i.e. they use the same key for both encryption and decryption. In this article, we are going to demonstrate key generation for s-des encryption and decryption algorithm. We take a random 10-bit key and produce two 8-bit keys which will be used for encryption and decryption." }, { "code": null, "e": 912, "s": 740, "text": "Key Generation Concept: In the key generation algorithm, we accept the 10-bit key and convert it into two 8 bit keys. This key is shared between both sender and receiver. " }, { "code": null, "e": 959, "s": 912, "text": "In the key generation, we use three functions:" }, { "code": null, "e": 978, "s": 959, "text": "1. Permutation P10" }, { "code": null, "e": 996, "s": 978, "text": "2. Permutation P8" }, { "code": null, "e": 1010, "s": 996, "text": "3. Left Shift" }, { "code": null, "e": 1099, "s": 1010, "text": "Step 1: We accepted a 10-bit key and permuted the bits by putting them in the P10 table." }, { "code": null, "e": 1349, "s": 1099, "text": "Key = 1 0 1 0 0 0 0 0 1 0\n(k1, k2, k3, k4, k5, k6, k7, k8, k9, k10) = (1, 0, 1, 0, 0, 0, 0, 0, 1, 0)\n\nP10 Permutation is: P10(k1, k2, k3, k4, k5, k6, k7, k8, k9, k10) = (k3, k5, k2, k7, k4, k10, k1, k9, k8, k6) \nAfter P10, we get 1 0 0 0 0 0 1 1 0 0" }, { "code": null, "e": 1404, "s": 1349, "text": "Step 2: We divide the key into 2 halves of 5-bit each." }, { "code": null, "e": 1429, "s": 1404, "text": "l=1 0 0 0 0, r=0 1 1 0 0" }, { "code": null, "e": 1482, "s": 1429, "text": "Step 3: Now we apply one bit left-shift on each key." }, { "code": null, "e": 1512, "s": 1482, "text": "l = 0 0 0 0 1, r = 1 1 0 0 0 " }, { "code": null, "e": 1656, "s": 1512, "text": "Step 4: Combine both keys after step 3 and permute the bits by putting them in the P8 table. The output of the given table is the first key K1." }, { "code": null, "e": 1844, "s": 1656, "text": "After LS-1 combined, we get 0 0 0 0 1 1 1 0 0 0\nP8 permutation is: P8(k1, k2, k3, k4, k5, k6, k7, k8, k9, k10) = (k6, k3, k7, k4, k8, k5, k10, k9)\nAfter P8, we get Key-1 : 1 0 1 0 0 1 0 0" }, { "code": null, "e": 1979, "s": 1844, "text": "Step 5: The output obtained from step 3 i.e. 2 halves after one bit left shift should again undergo the process of two-bit left shift." }, { "code": null, "e": 2076, "s": 1979, "text": "Step 3 output - l = 0 0 0 0 1, r = 1 1 0 0 0 \nAfter two bit shift - l = 0 0 1 0 0, r = 0 0 0 1 1" }, { "code": null, "e": 2228, "s": 2076, "text": "Step 6: Combine the 2 halves obtained from step 5 and permute them by putting them in the P8 table. The output of the given table is the second key K2." }, { "code": null, "e": 2410, "s": 2228, "text": "After LS-2 combined = 0 0 1 0 0 0 0 0 1 1\nP8 permutation is: P8(k1, k2, k3, k4, k5, k6, k7, k8, k9, k10) = (k6, k3, k7, k4, k8, k5, k10, k9)\nAfter P8, we get Key-2 : 0 1 0 0 0 0 1 1" }, { "code": null, "e": 2424, "s": 2410, "text": "Final Output:" }, { "code": null, "e": 2476, "s": 2424, "text": "Key-1 is: 1 0 1 0 0 1 0 0\nKey-2 is: 0 1 0 0 0 0 1 1" }, { "code": null, "e": 2490, "s": 2476, "text": "guptaaman9981" }, { "code": null, "e": 2503, "s": 2490, "text": "cryptography" }, { "code": null, "e": 2521, "s": 2503, "text": "Computer Networks" }, { "code": null, "e": 2534, "s": 2521, "text": "cryptography" }, { "code": null, "e": 2552, "s": 2534, "text": "Computer Networks" } ]
Float equals() method in Java with examples
26 Oct, 2018 The equals() method in Float Class is a built-in function in java that compares this object to the specified object. The result is true if and only if the argument is not null and is a Float object that contains the same double value as this object. It returns false if both the objects are not same. Syntax: public boolean equals(Object obj) Parameter: The method accepts only one parameter obj which specifies the passed object is the object that is to be compared with. Return Values: The function returns a boolean value after comparing with the object passed in the parameter: It returns true if and only if the argument is not null and is a Float object that contains the same double value as this object. It returns false if the object is not same. If f1 and f2 both is represented as Float.NaN, then the equals() method returns true, even if Float.NaN==Float.NaN has the value false. If f1 represents +0.0f while f2 represents -0.0f, or vice versa, the equal test has the value false, even though 0.0f==-0.0f has the value true. Below programs illustrates the use of Float.equals() method: Program 1: // Java program to demonstrate// Float.equals() method import java.lang.*; class Gfg1 { public static void main(String args[]) { // When two objects are different Float obj1 = new Float(123123); Float obj2 = new Float(164165); System.out.print("The objects " + obj1 + " and " + obj2 + "are : "); if (obj1.equals(obj2)) System.out.println("Equal"); else System.out.println("Not equal"); // When two objects are equal obj1 = new Float(12345); obj2 = new Float(12345); System.out.print("The objects " + obj1 + " and " + obj2 + "are : "); if (obj1.equals(obj2)) System.out.print("Equal"); else System.out.print("Not Equal"); }} The objects 123123.0 and 164165.0are : Not equal The objects 12345.0 and 12345.0are : Equal Program 2: Using Float.NaN // Java program to demonstrate// Float.equals() method import java.lang.*; class Gfg1 { public static void main(String args[]) { Float obj1 = new Float(Float.NaN); Float obj2 = new Float(Float.NaN); System.out.print("The objects " + obj1 + " and " + obj2 + "are : "); if (obj1.equals(obj2)) System.out.println("Equal"); else System.out.println("Not equal"); }} The objects NaN and NaNare : Equal Program 3: Using float value 0.0f // Java program to demonstrate// Float.equals() method import java.lang.*; class Gfg1 { public static void main(String args[]) { Float obj1 = new Float(0.0f); Float obj2 = new Float(-0.0f); System.out.print("The objects " + obj1 + " and " + obj2 + "are : "); if (obj1.equals(obj2)) System.out.println("Equal"); else System.out.println("Not equal"); }} The objects 0.0 and -0.0are : Not equal Reference: https://docs.oracle.com/javase/7/docs/api/java/lang/Float.html#equals(java.lang.Object) java-basics Java-Functions Java-lang package 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": 28, "s": 0, "text": "\n26 Oct, 2018" }, { "code": null, "e": 329, "s": 28, "text": "The equals() method in Float Class is a built-in function in java that compares this object to the specified object. The result is true if and only if the argument is not null and is a Float object that contains the same double value as this object. It returns false if both the objects are not same." }, { "code": null, "e": 337, "s": 329, "text": "Syntax:" }, { "code": null, "e": 371, "s": 337, "text": "public boolean equals(Object obj)" }, { "code": null, "e": 501, "s": 371, "text": "Parameter: The method accepts only one parameter obj which specifies the passed object is the object that is to be compared with." }, { "code": null, "e": 610, "s": 501, "text": "Return Values: The function returns a boolean value after comparing with the object passed in the parameter:" }, { "code": null, "e": 784, "s": 610, "text": "It returns true if and only if the argument is not null and is a Float object that contains the same double value as this object. It returns false if the object is not same." }, { "code": null, "e": 920, "s": 784, "text": "If f1 and f2 both is represented as Float.NaN, then the equals() method returns true, even if Float.NaN==Float.NaN has the value false." }, { "code": null, "e": 1065, "s": 920, "text": "If f1 represents +0.0f while f2 represents -0.0f, or vice versa, the equal test has the value false, even though 0.0f==-0.0f has the value true." }, { "code": null, "e": 1126, "s": 1065, "text": "Below programs illustrates the use of Float.equals() method:" }, { "code": null, "e": 1137, "s": 1126, "text": "Program 1:" }, { "code": "// Java program to demonstrate// Float.equals() method import java.lang.*; class Gfg1 { public static void main(String args[]) { // When two objects are different Float obj1 = new Float(123123); Float obj2 = new Float(164165); System.out.print(\"The objects \" + obj1 + \" and \" + obj2 + \"are : \"); if (obj1.equals(obj2)) System.out.println(\"Equal\"); else System.out.println(\"Not equal\"); // When two objects are equal obj1 = new Float(12345); obj2 = new Float(12345); System.out.print(\"The objects \" + obj1 + \" and \" + obj2 + \"are : \"); if (obj1.equals(obj2)) System.out.print(\"Equal\"); else System.out.print(\"Not Equal\"); }}", "e": 2004, "s": 1137, "text": null }, { "code": null, "e": 2097, "s": 2004, "text": "The objects 123123.0 and 164165.0are : Not equal\nThe objects 12345.0 and 12345.0are : Equal\n" }, { "code": null, "e": 2124, "s": 2097, "text": "Program 2: Using Float.NaN" }, { "code": "// Java program to demonstrate// Float.equals() method import java.lang.*; class Gfg1 { public static void main(String args[]) { Float obj1 = new Float(Float.NaN); Float obj2 = new Float(Float.NaN); System.out.print(\"The objects \" + obj1 + \" and \" + obj2 + \"are : \"); if (obj1.equals(obj2)) System.out.println(\"Equal\"); else System.out.println(\"Not equal\"); }}", "e": 2607, "s": 2124, "text": null }, { "code": null, "e": 2643, "s": 2607, "text": "The objects NaN and NaNare : Equal\n" }, { "code": null, "e": 2677, "s": 2643, "text": "Program 3: Using float value 0.0f" }, { "code": "// Java program to demonstrate// Float.equals() method import java.lang.*; class Gfg1 { public static void main(String args[]) { Float obj1 = new Float(0.0f); Float obj2 = new Float(-0.0f); System.out.print(\"The objects \" + obj1 + \" and \" + obj2 + \"are : \"); if (obj1.equals(obj2)) System.out.println(\"Equal\"); else System.out.println(\"Not equal\"); }}", "e": 3151, "s": 2677, "text": null }, { "code": null, "e": 3192, "s": 3151, "text": "The objects 0.0 and -0.0are : Not equal\n" }, { "code": null, "e": 3291, "s": 3192, "text": "Reference: https://docs.oracle.com/javase/7/docs/api/java/lang/Float.html#equals(java.lang.Object)" }, { "code": null, "e": 3303, "s": 3291, "text": "java-basics" }, { "code": null, "e": 3318, "s": 3303, "text": "Java-Functions" }, { "code": null, "e": 3336, "s": 3318, "text": "Java-lang package" }, { "code": null, "e": 3341, "s": 3336, "text": "Java" }, { "code": null, "e": 3346, "s": 3341, "text": "Java" }, { "code": null, "e": 3444, "s": 3346, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3459, "s": 3444, "text": "Stream In Java" }, { "code": null, "e": 3480, "s": 3459, "text": "Introduction to Java" }, { "code": null, "e": 3501, "s": 3480, "text": "Constructors in Java" }, { "code": null, "e": 3520, "s": 3501, "text": "Exceptions in Java" }, { "code": null, "e": 3537, "s": 3520, "text": "Generics in Java" }, { "code": null, "e": 3567, "s": 3537, "text": "Functional Interfaces in Java" }, { "code": null, "e": 3593, "s": 3567, "text": "Java Programming Examples" }, { "code": null, "e": 3609, "s": 3593, "text": "Strings in Java" }, { "code": null, "e": 3646, "s": 3609, "text": "Differences between JDK, JRE and JVM" } ]
Number of even substrings in a string of digits
08 Jul, 2022 Given a string of digits 0 – 9. The task is to count a number of substrings which when converting into integer form an even number. Examples : Input : str = "1234". Output : 6 "2", "4", "12", "34", "234", "1234" are 6 substring which are even. Input : str = "154". Output : 3 Input : str = "15". Output : 0 For a number to be even, the substring must end with an even digit. We find all the even digits in the string and for each even digit, count the number of substrings ending with it. Now, observe that the number of substrings will be an index of that even digit plus one. Implementation: C++ Java Python3 C# PHP Javascript // C++ program to count number of substring// which are even integer in a string of digits.#include<bits/stdc++.h>using namespace std; // Return the even number substrings.int evenNumSubstring(char str[]){ int len = strlen(str); int count = 0; for (int i = 0; i < len; i++) { int temp = str[i] - '0'; // If current digit is even, add // count of substrings ending with // it. The count is (i+1) if (temp % 2 == 0) count += (i + 1); } return count;} // Driven Programint main(){ char str[] = "1234"; cout << evenNumSubstring(str) << endl; return 0;} // Java program to count number of// substring which are even integer// in a string of digits.public class GFG { // Return the even number substrings. static int evenNumSubstring(String str) { int len = str.length(); int count = 0; for (int i = 0; i < len; i++) { int temp = str.charAt(i) - '0'; // If current digit is even, add // count of substrings ending with // it. The count is (i+1) if (temp % 2 == 0) count += (i + 1); } return count; } public static void main(String args[]) { String str= "1234"; System.out.println(evenNumSubstring(str)); }} // This code is contributed by Sam007. # Python 3 program to count number of substring# which are even integer in a string of digits. # Return the even number substrings.def evenNumSubstring(str): length = len(str) count = 0 for i in range(0,length,1): temp = ord(str[i]) - ord('0') # If current digit is even, add # count of substrings ending with # it. The count is (i+1) if (temp % 2 == 0): count += (i + 1) return count # Driven Programif __name__ == '__main__': str = ['1','2','3','4'] print(evenNumSubstring(str)) # This code is contributed by# Surendra_Gangwar // C# program to count number of// substring which are even integer// in a string of digits.using System; public class GFG { // Return the even number substrings. static int evenNumSubstring(string str) { int len = str.Length; int count = 0; for (int i = 0; i < len; i++) { int temp = str[i] - '0'; // If current digit is even, // add count of substrings // ending with it. The count // is (i+1) if (temp % 2 == 0) count += (i + 1); } return count; } // Driver code public static void Main() { string str= "1234"; Console.Write( evenNumSubstring(str)); }} // This code is contributed by Sam007. <?php// PHP program to count number// of substring which are even// integer in a string of digits. // Return the even number substrings.function evenNumSubstring($str){ $len = strlen($str); $count = 0; for ($i = 0; $i < $len; $i++) { $temp = $str[$i] - '0'; // If current digit is even, add // count of substrings ending with // it. The count is (i+1) if ($temp % 2 == 0) $count += ($i + 1); } return $count;} // Driver Code$str = "1234";echo evenNumSubstring($str),"\n" ; // This code is contributed by jit_t ?> <script> // Javascript program to count number of // substring which are even integer // in a string of digits. // Return the even number substrings. function evenNumSubstring(str) { let len = str.length; let count = 0; for (let i = 0; i < len; i++) { let temp = str[i] - '0'; // If current digit is even, // add count of substrings // ending with it. The count // is (i+1) if (temp % 2 == 0) count += (i + 1); } return count; } let str= "1234"; document.write(evenNumSubstring(str)); </script> 6 Time Complexity: O(length of string). 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. Sam007 jit_t SURENDRA_GANGWAR mukesh07 hardikkoriintern divisibility Strings Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Different Methods to Reverse a String in C++ KMP Algorithm for Pattern Searching Length of the longest substring without repeating characters Longest Palindromic Substring | Set 1 Convert string to char array in C++ stringstream in C++ and its Applications Iterate over characters of a string in C++ Program to add two binary strings Check for Balanced Brackets in an expression (well-formedness) using Stack Python | Check if a Substring is Present in a Given String
[ { "code": null, "e": 52, "s": 24, "text": "\n08 Jul, 2022" }, { "code": null, "e": 184, "s": 52, "text": "Given a string of digits 0 – 9. The task is to count a number of substrings which when converting into integer form an even number." }, { "code": null, "e": 196, "s": 184, "text": "Examples : " }, { "code": null, "e": 363, "s": 196, "text": "Input : str = \"1234\".\nOutput : 6\n\"2\", \"4\", \"12\", \"34\", \"234\", \"1234\" \nare 6 substring which are even.\n\nInput : str = \"154\".\nOutput : 3\n\nInput : str = \"15\".\nOutput : 0" }, { "code": null, "e": 635, "s": 363, "text": "For a number to be even, the substring must end with an even digit. We find all the even digits in the string and for each even digit, count the number of substrings ending with it. Now, observe that the number of substrings will be an index of that even digit plus one. " }, { "code": null, "e": 651, "s": 635, "text": "Implementation:" }, { "code": null, "e": 655, "s": 651, "text": "C++" }, { "code": null, "e": 660, "s": 655, "text": "Java" }, { "code": null, "e": 668, "s": 660, "text": "Python3" }, { "code": null, "e": 671, "s": 668, "text": "C#" }, { "code": null, "e": 675, "s": 671, "text": "PHP" }, { "code": null, "e": 686, "s": 675, "text": "Javascript" }, { "code": "// C++ program to count number of substring// which are even integer in a string of digits.#include<bits/stdc++.h>using namespace std; // Return the even number substrings.int evenNumSubstring(char str[]){ int len = strlen(str); int count = 0; for (int i = 0; i < len; i++) { int temp = str[i] - '0'; // If current digit is even, add // count of substrings ending with // it. The count is (i+1) if (temp % 2 == 0) count += (i + 1); } return count;} // Driven Programint main(){ char str[] = \"1234\"; cout << evenNumSubstring(str) << endl; return 0;}", "e": 1311, "s": 686, "text": null }, { "code": "// Java program to count number of// substring which are even integer// in a string of digits.public class GFG { // Return the even number substrings. static int evenNumSubstring(String str) { int len = str.length(); int count = 0; for (int i = 0; i < len; i++) { int temp = str.charAt(i) - '0'; // If current digit is even, add // count of substrings ending with // it. The count is (i+1) if (temp % 2 == 0) count += (i + 1); } return count; } public static void main(String args[]) { String str= \"1234\"; System.out.println(evenNumSubstring(str)); }} // This code is contributed by Sam007.", "e": 2092, "s": 1311, "text": null }, { "code": "# Python 3 program to count number of substring# which are even integer in a string of digits. # Return the even number substrings.def evenNumSubstring(str): length = len(str) count = 0 for i in range(0,length,1): temp = ord(str[i]) - ord('0') # If current digit is even, add # count of substrings ending with # it. The count is (i+1) if (temp % 2 == 0): count += (i + 1) return count # Driven Programif __name__ == '__main__': str = ['1','2','3','4'] print(evenNumSubstring(str)) # This code is contributed by# Surendra_Gangwar", "e": 2689, "s": 2092, "text": null }, { "code": "// C# program to count number of// substring which are even integer// in a string of digits.using System; public class GFG { // Return the even number substrings. static int evenNumSubstring(string str) { int len = str.Length; int count = 0; for (int i = 0; i < len; i++) { int temp = str[i] - '0'; // If current digit is even, // add count of substrings // ending with it. The count // is (i+1) if (temp % 2 == 0) count += (i + 1); } return count; } // Driver code public static void Main() { string str= \"1234\"; Console.Write( evenNumSubstring(str)); }} // This code is contributed by Sam007.", "e": 3486, "s": 2689, "text": null }, { "code": "<?php// PHP program to count number// of substring which are even// integer in a string of digits. // Return the even number substrings.function evenNumSubstring($str){ $len = strlen($str); $count = 0; for ($i = 0; $i < $len; $i++) { $temp = $str[$i] - '0'; // If current digit is even, add // count of substrings ending with // it. The count is (i+1) if ($temp % 2 == 0) $count += ($i + 1); } return $count;} // Driver Code$str = \"1234\";echo evenNumSubstring($str),\"\\n\" ; // This code is contributed by jit_t ?>", "e": 4068, "s": 3486, "text": null }, { "code": "<script> // Javascript program to count number of // substring which are even integer // in a string of digits. // Return the even number substrings. function evenNumSubstring(str) { let len = str.length; let count = 0; for (let i = 0; i < len; i++) { let temp = str[i] - '0'; // If current digit is even, // add count of substrings // ending with it. The count // is (i+1) if (temp % 2 == 0) count += (i + 1); } return count; } let str= \"1234\"; document.write(evenNumSubstring(str)); </script>", "e": 4760, "s": 4068, "text": null }, { "code": null, "e": 4762, "s": 4760, "text": "6" }, { "code": null, "e": 4801, "s": 4762, "text": "Time Complexity: O(length of string). " }, { "code": null, "e": 5098, "s": 4801, "text": "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. " }, { "code": null, "e": 5105, "s": 5098, "text": "Sam007" }, { "code": null, "e": 5111, "s": 5105, "text": "jit_t" }, { "code": null, "e": 5128, "s": 5111, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 5137, "s": 5128, "text": "mukesh07" }, { "code": null, "e": 5154, "s": 5137, "text": "hardikkoriintern" }, { "code": null, "e": 5167, "s": 5154, "text": "divisibility" }, { "code": null, "e": 5175, "s": 5167, "text": "Strings" }, { "code": null, "e": 5183, "s": 5175, "text": "Strings" }, { "code": null, "e": 5281, "s": 5183, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5326, "s": 5281, "text": "Different Methods to Reverse a String in C++" }, { "code": null, "e": 5362, "s": 5326, "text": "KMP Algorithm for Pattern Searching" }, { "code": null, "e": 5423, "s": 5362, "text": "Length of the longest substring without repeating characters" }, { "code": null, "e": 5461, "s": 5423, "text": "Longest Palindromic Substring | Set 1" }, { "code": null, "e": 5497, "s": 5461, "text": "Convert string to char array in C++" }, { "code": null, "e": 5538, "s": 5497, "text": "stringstream in C++ and its Applications" }, { "code": null, "e": 5581, "s": 5538, "text": "Iterate over characters of a string in C++" }, { "code": null, "e": 5615, "s": 5581, "text": "Program to add two binary strings" }, { "code": null, "e": 5690, "s": 5615, "text": "Check for Balanced Brackets in an expression (well-formedness) using Stack" } ]
How to get the enter key in ReactJS ?
11 Nov, 2021 Let us create a React project and then we will create a UI that takes input from users. Users can interact with the UI and press Enter Key to trigger an event through this. We will be creating an input field that takes the message as input. In the input, we have added an on Keypress function which will get activated whenever the user clicks and types something in the input. It will not do anything since a condition is added. The condition is that for every keystroke it will check if the key is entered or not. If the user presses enter then the code inside the condition will run. On the press of entering, the input text will be saved inside the state. After that, a call back function is called which will trigger an alert function greeting the user with the message. An alert function is added. So, input is created that sends a Welcome message whenever Enter is pressed by the user. Creating React Project: Step 1: To create a react app you need to install react modules through npx command. “Npx” is used instead of “npm” because you will be needing this command in your app’s lifecycle only once. npx create-react-app project_name Step 2: After creating your react project move into the folder to perform different operations. cd project_name Project Structure: After running the commands mentioned in the above steps, if you open the project in an editor you can see a similar project structure as shown below. The new components user makes or the code changes we will be performing will be done in the source folder. Project_Structure Example: App.js import React, { Component } from "react"; class App extends Component { state = { message: "" }; render() { return ( <div> <p>Enter Your Message and Press Enter:</p> <input onKeyPress={(e) => { if (e.key === "Enter") { this.setState({ message: e.target.value }, () => { alert(this.state.message); }); } }} type="text" /> </div> ); }}export default App; Step to run the application: Open the terminal and type the following command. npm start Output: Open your browser. It will by default open a tab with localhost running (http://localhost:3000/) and you can see the output shown in the image. Enter your message and press ENTER to see the welcome message. Detecting Enter Key Picked React-Questions ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n11 Nov, 2021" }, { "code": null, "e": 202, "s": 28, "text": "Let us create a React project and then we will create a UI that takes input from users. Users can interact with the UI and press Enter Key to trigger an event through this. " }, { "code": null, "e": 921, "s": 202, "text": "We will be creating an input field that takes the message as input. In the input, we have added an on Keypress function which will get activated whenever the user clicks and types something in the input. It will not do anything since a condition is added. The condition is that for every keystroke it will check if the key is entered or not. If the user presses enter then the code inside the condition will run. On the press of entering, the input text will be saved inside the state. After that, a call back function is called which will trigger an alert function greeting the user with the message. An alert function is added. So, input is created that sends a Welcome message whenever Enter is pressed by the user." }, { "code": null, "e": 945, "s": 921, "text": "Creating React Project:" }, { "code": null, "e": 1137, "s": 945, "text": "Step 1: To create a react app you need to install react modules through npx command. “Npx” is used instead of “npm” because you will be needing this command in your app’s lifecycle only once." }, { "code": null, "e": 1171, "s": 1137, "text": "npx create-react-app project_name" }, { "code": null, "e": 1267, "s": 1171, "text": "Step 2: After creating your react project move into the folder to perform different operations." }, { "code": null, "e": 1283, "s": 1267, "text": "cd project_name" }, { "code": null, "e": 1559, "s": 1283, "text": "Project Structure: After running the commands mentioned in the above steps, if you open the project in an editor you can see a similar project structure as shown below. The new components user makes or the code changes we will be performing will be done in the source folder." }, { "code": null, "e": 1577, "s": 1559, "text": "Project_Structure" }, { "code": null, "e": 1586, "s": 1577, "text": "Example:" }, { "code": null, "e": 1593, "s": 1586, "text": "App.js" }, { "code": "import React, { Component } from \"react\"; class App extends Component { state = { message: \"\" }; render() { return ( <div> <p>Enter Your Message and Press Enter:</p> <input onKeyPress={(e) => { if (e.key === \"Enter\") { this.setState({ message: e.target.value }, () => { alert(this.state.message); }); } }} type=\"text\" /> </div> ); }}export default App;", "e": 2266, "s": 1593, "text": null }, { "code": null, "e": 2345, "s": 2266, "text": "Step to run the application: Open the terminal and type the following command." }, { "code": null, "e": 2355, "s": 2345, "text": "npm start" }, { "code": null, "e": 2570, "s": 2355, "text": "Output: Open your browser. It will by default open a tab with localhost running (http://localhost:3000/) and you can see the output shown in the image. Enter your message and press ENTER to see the welcome message." }, { "code": null, "e": 2590, "s": 2570, "text": "Detecting Enter Key" }, { "code": null, "e": 2597, "s": 2590, "text": "Picked" }, { "code": null, "e": 2613, "s": 2597, "text": "React-Questions" }, { "code": null, "e": 2621, "s": 2613, "text": "ReactJS" }, { "code": null, "e": 2638, "s": 2621, "text": "Web Technologies" } ]
How To Check MySQL Version
Let us understand how to check the version of MySQL that the user is currently running − Before entering queries on the console, it is important to ensure that the user is connected to the server. The below query would give the version number of the server being used, and the current date. mysql> SELECT VERSION(), CURRENT_DATE; Note: The function ‘VERSION()’ and ‘CURRENT_DATE’ are case −insensitive. This means ‘version()’, ‘Version()’, ‘vERsion()’, all mean the same. Same goes with ‘CURRENT_DATE’ Learn about MySQL Queries An SQL query is followed by a semi−colon. An SQL query is followed by a semi−colon. When a query is issued to mysql, it sends the query to the server for execution. The results are computed and displayed. Another ‘mysql>’ also gets printed, indicating that the server is ready for one more query. When a query is issued to mysql, it sends the query to the server for execution. The results are computed and displayed. Another ‘mysql>’ also gets printed, indicating that the server is ready for one more query. The output after executing the mysql query is in tabular form, i.e rows and columns. The first row contains the name of the columns. The remaining rows are the query results. The output after executing the mysql query is in tabular form, i.e rows and columns. The first row contains the name of the columns. The remaining rows are the query results. Once the query is executed, ‘mysql’ also gives the number of rows that were returned, the amount of time taken to execute the query. This gives the user a rough idea about the performance of the server. Once the query is executed, ‘mysql’ also gives the number of rows that were returned, the amount of time taken to execute the query. This gives the user a rough idea about the performance of the server. MySQL server can also be used to execute multiple statement in a single line. It has been shown below − mysql > SELECT VERSION(); SELECT NOW();
[ { "code": null, "e": 1276, "s": 1187, "text": "Let us understand how to check the version of MySQL that the user is currently running −" }, { "code": null, "e": 1384, "s": 1276, "text": "Before entering queries on the console, it is important to ensure that the user is connected to the server." }, { "code": null, "e": 1478, "s": 1384, "text": "The below query would give the version number of the server being used, and the current date." }, { "code": null, "e": 1517, "s": 1478, "text": "mysql> SELECT VERSION(), CURRENT_DATE;" }, { "code": null, "e": 1689, "s": 1517, "text": "Note: The function ‘VERSION()’ and ‘CURRENT_DATE’ are case −insensitive. This means ‘version()’, ‘Version()’, ‘vERsion()’, all mean the same. Same goes with ‘CURRENT_DATE’" }, { "code": null, "e": 1715, "s": 1689, "text": "Learn about MySQL Queries" }, { "code": null, "e": 1757, "s": 1715, "text": "An SQL query is followed by a semi−colon." }, { "code": null, "e": 1799, "s": 1757, "text": "An SQL query is followed by a semi−colon." }, { "code": null, "e": 2012, "s": 1799, "text": "When a query is issued to mysql, it sends the query to the server for execution. The results are computed and displayed. Another ‘mysql>’ also gets printed, indicating that the server is ready for one more query." }, { "code": null, "e": 2225, "s": 2012, "text": "When a query is issued to mysql, it sends the query to the server for execution. The results are computed and displayed. Another ‘mysql>’ also gets printed, indicating that the server is ready for one more query." }, { "code": null, "e": 2400, "s": 2225, "text": "The output after executing the mysql query is in tabular form, i.e rows and columns. The first row contains the name of the columns. The remaining rows are the query results." }, { "code": null, "e": 2575, "s": 2400, "text": "The output after executing the mysql query is in tabular form, i.e rows and columns. The first row contains the name of the columns. The remaining rows are the query results." }, { "code": null, "e": 2778, "s": 2575, "text": "Once the query is executed, ‘mysql’ also gives the number of rows that were returned, the amount of time taken to execute the query. This gives the user a rough idea about the performance of the server." }, { "code": null, "e": 2981, "s": 2778, "text": "Once the query is executed, ‘mysql’ also gives the number of rows that were returned, the amount of time taken to execute the query. This gives the user a rough idea about the performance of the server." }, { "code": null, "e": 3085, "s": 2981, "text": "MySQL server can also be used to execute multiple statement in a single line. It has been shown below −" }, { "code": null, "e": 3125, "s": 3085, "text": "mysql > SELECT VERSION(); SELECT NOW();" } ]
Find the count of substrings in alphabetic order
30 Apr, 2021 Given a string of length consisting of lowercase alphabets. The task is to find the number of such substrings whose characters occur in alphabetical order. Minimum allowed length of substring is 2.Examples: Input : str = "refjhlmnbv" Output : 2 Substrings are: "ef", "mn" Input : str = "qwertyuiopasdfghjklzxcvbnm" Output : 3 For a substring to be in alphabetical order its character is in the same sequence as they occur in English alphabets. Also, the ASCII value of consecutive characters in such substring differs by exactly 1. For finding a total number of substrings that are in alphabetical order traverse the given string and compare two neighboring characters, if they are in alphabetic order increment the result and then find the next character in the string which is not in alphabetic order to its former character.Algorithm : Iterate over string length: if str[i]+1 == str[i+1] -> increase the result by 1 and iterate the string till next character which is out of alphabetic order else continue Below is the implementation of the above approach: C++ Java Python3 C# Javascript // CPP to find the number of substrings// in alphabetical order #include <bits/stdc++.h>using namespace std; // Function to find number of substringsint findSubstringCount(string str){ int result = 0; int n = str.size(); // Iterate over string length for (int i = 0; i < n - 1; i++) { // if any two chars are in alphabetic order if (str[i] + 1 == str[i + 1]) { result++; // find next char not in order while (str[i] + 1 == str[i + 1]) { i++; } } } // return the result return result;} // Driver functionint main(){ string str = "alphabet"; cout << findSubstringCount(str) << endl; return 0;} // Java to find the number of substrings// in alphabetical orderimport java.util.*;class Solution{ // Function to find number of substringsstatic int findSubstringCount(String str){ int result = 0; int n = str.length(); // Iterate over string length for (int i = 0; i < n - 1; i++) { // if any two chars are in alphabetic order if (str.charAt(i) + 1 == str.charAt(i+1)) { result++; // find next char not in order while (str.charAt(i) + 1 == str.charAt(i+1)) { i++; } } } // return the result return result;} // Driver functionpublic static void main(String args[]){ String str = "alphabet"; System.out.println(findSubstringCount(str)); } }//contributed by Arnab Kundu # Python3 to find the number of substrings# in alphabetical order # Function to find number of substringsdef findSubstringCount(str): result = 0 n = len (str) # Iterate over string length for i in range (n - 1) : # if any two chars are in alphabetic order if (ord(str[i]) + 1 == ord(str[i + 1])) : result += 1 # find next char not in order while (ord(str[i]) + 1 == ord(str[i + 1])) : i += 1 # return the result return result # Driver Codeif __name__ == "__main__": str = "alphabet" print(findSubstringCount(str)) # This code is contributed by ChitraNayal using System; // C# to find the number of substrings // in alphabetical order public class Solution{ // Function to find number of substrings public static int findSubstringCount(string str){ int result = 0; int n = str.Length; // Iterate over string length for (int i = 0; i < n - 1; i++) { // if any two chars are in alphabetic order if ((char)(str[i] + 1) == str[i + 1]) { result++; // find next char not in order while ((char)(str[i] + 1) == str[i + 1]) { i++; } } } // return the result return result;} // Driver function public static void Main(string[] args){ string str = "alphabet"; Console.WriteLine(findSubstringCount(str)); } } // This code is contributed by Shrikant13 <script> // javascript to find the number of substrings// in alphabetical order // Function to find number of substringsfunction findSubstringCount(str){ var result = 0; var n = str.length; // Iterate over string length for (var i = 0; i < n - 1; i++) { // if any two chars are in alphabetic order if (String.fromCharCode(str[i].charCodeAt(0) + 1) == str[i + 1]) { result++; // find next char not in order while (String.fromCharCode(str[i].charCodeAt(0) + 1) === str[i + 1]) { i++; } } } // return the result return result;} // Driver functionvar str = "alphabet";document.write( findSubstringCount(str)); </script> 1 andrew1234 shrikanth13 ukasp shubham_singh itsok substring Strings Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n30 Apr, 2021" }, { "code": null, "e": 262, "s": 53, "text": "Given a string of length consisting of lowercase alphabets. The task is to find the number of such substrings whose characters occur in alphabetical order. Minimum allowed length of substring is 2.Examples: " }, { "code": null, "e": 382, "s": 262, "text": "Input : str = \"refjhlmnbv\"\nOutput : 2\nSubstrings are: \"ef\", \"mn\"\n\nInput : str = \"qwertyuiopasdfghjklzxcvbnm\"\nOutput : 3" }, { "code": null, "e": 927, "s": 384, "text": "For a substring to be in alphabetical order its character is in the same sequence as they occur in English alphabets. Also, the ASCII value of consecutive characters in such substring differs by exactly 1. For finding a total number of substrings that are in alphabetical order traverse the given string and compare two neighboring characters, if they are in alphabetic order increment the result and then find the next character in the string which is not in alphabetic order to its former character.Algorithm : Iterate over string length: " }, { "code": null, "e": 1055, "s": 927, "text": "if str[i]+1 == str[i+1] -> increase the result by 1 and iterate the string till next character which is out of alphabetic order" }, { "code": null, "e": 1069, "s": 1055, "text": "else continue" }, { "code": null, "e": 1122, "s": 1069, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 1126, "s": 1122, "text": "C++" }, { "code": null, "e": 1131, "s": 1126, "text": "Java" }, { "code": null, "e": 1139, "s": 1131, "text": "Python3" }, { "code": null, "e": 1142, "s": 1139, "text": "C#" }, { "code": null, "e": 1153, "s": 1142, "text": "Javascript" }, { "code": "// CPP to find the number of substrings// in alphabetical order #include <bits/stdc++.h>using namespace std; // Function to find number of substringsint findSubstringCount(string str){ int result = 0; int n = str.size(); // Iterate over string length for (int i = 0; i < n - 1; i++) { // if any two chars are in alphabetic order if (str[i] + 1 == str[i + 1]) { result++; // find next char not in order while (str[i] + 1 == str[i + 1]) { i++; } } } // return the result return result;} // Driver functionint main(){ string str = \"alphabet\"; cout << findSubstringCount(str) << endl; return 0;}", "e": 1859, "s": 1153, "text": null }, { "code": "// Java to find the number of substrings// in alphabetical orderimport java.util.*;class Solution{ // Function to find number of substringsstatic int findSubstringCount(String str){ int result = 0; int n = str.length(); // Iterate over string length for (int i = 0; i < n - 1; i++) { // if any two chars are in alphabetic order if (str.charAt(i) + 1 == str.charAt(i+1)) { result++; // find next char not in order while (str.charAt(i) + 1 == str.charAt(i+1)) { i++; } } } // return the result return result;} // Driver functionpublic static void main(String args[]){ String str = \"alphabet\"; System.out.println(findSubstringCount(str)); } }//contributed by Arnab Kundu", "e": 2649, "s": 1859, "text": null }, { "code": "# Python3 to find the number of substrings# in alphabetical order # Function to find number of substringsdef findSubstringCount(str): result = 0 n = len (str) # Iterate over string length for i in range (n - 1) : # if any two chars are in alphabetic order if (ord(str[i]) + 1 == ord(str[i + 1])) : result += 1 # find next char not in order while (ord(str[i]) + 1 == ord(str[i + 1])) : i += 1 # return the result return result # Driver Codeif __name__ == \"__main__\": str = \"alphabet\" print(findSubstringCount(str)) # This code is contributed by ChitraNayal", "e": 3318, "s": 2649, "text": null }, { "code": "using System; // C# to find the number of substrings // in alphabetical order public class Solution{ // Function to find number of substrings public static int findSubstringCount(string str){ int result = 0; int n = str.Length; // Iterate over string length for (int i = 0; i < n - 1; i++) { // if any two chars are in alphabetic order if ((char)(str[i] + 1) == str[i + 1]) { result++; // find next char not in order while ((char)(str[i] + 1) == str[i + 1]) { i++; } } } // return the result return result;} // Driver function public static void Main(string[] args){ string str = \"alphabet\"; Console.WriteLine(findSubstringCount(str)); } } // This code is contributed by Shrikant13", "e": 4135, "s": 3318, "text": null }, { "code": "<script> // javascript to find the number of substrings// in alphabetical order // Function to find number of substringsfunction findSubstringCount(str){ var result = 0; var n = str.length; // Iterate over string length for (var i = 0; i < n - 1; i++) { // if any two chars are in alphabetic order if (String.fromCharCode(str[i].charCodeAt(0) + 1) == str[i + 1]) { result++; // find next char not in order while (String.fromCharCode(str[i].charCodeAt(0) + 1) === str[i + 1]) { i++; } } } // return the result return result;} // Driver functionvar str = \"alphabet\";document.write( findSubstringCount(str)); </script>", "e": 4854, "s": 4135, "text": null }, { "code": null, "e": 4856, "s": 4854, "text": "1" }, { "code": null, "e": 4869, "s": 4858, "text": "andrew1234" }, { "code": null, "e": 4881, "s": 4869, "text": "shrikanth13" }, { "code": null, "e": 4887, "s": 4881, "text": "ukasp" }, { "code": null, "e": 4901, "s": 4887, "text": "shubham_singh" }, { "code": null, "e": 4907, "s": 4901, "text": "itsok" }, { "code": null, "e": 4917, "s": 4907, "text": "substring" }, { "code": null, "e": 4925, "s": 4917, "text": "Strings" }, { "code": null, "e": 4933, "s": 4925, "text": "Strings" } ]
How to trigger HTML button after hitting enter button in textbox using JavaScript ?
05 Oct, 2021 Given an HTML document containing text area and the task is to trigger the button when the user hit Enter button. We can do it by using “keyup”, “keydown”, or “keypress” event listener on textbox depending on the need. When this event is triggered, we check if the key pressed is ENTER or not. If the key pressed is not ENTER, we do nothing. We will make an example that will append the content of the textbox in div when ENTER is pressed using all three event listeners. keyup: This event is fired when user releases a key. Syntax: textbox.addEventListner("keyup", FUNCTION); FUNCTION is the name of function we want to call when event is fired. Example: HTML <!DOCTYPE html><html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8" /> <title> How to trigger HTML button after hitting enter button in textbox using JavaScript? </title></head> <body> <label for="message">Enter Your Message:</label> <br><br> <!-- Textbox --> <input type="text" id="textbox" name="message"> <br><br> <!-- Button we want to trigger on ENTER in Textbox --> <button id="button">GeeksForGeeks</button> <!-- The div element in which we will append our data from text box --> <div id="message"></div> <script> var msg = document.getElementById("message"); var button = document.getElementById("button"); var textBox = document.getElementById("textbox"); // This event is fired when button is clicked button.addEventListener("click", function () { var str = textBox.value; console.log(str); msg.innerHTML += "<p>" + str + "</p>"; }); textBox.addEventListener("keyup", function (event) { // Checking if key pressed is ENTER or not // if the key pressed is ENTER // click listener on button is called if (event.keyCode == 13) { button.click(); } }); </script></body> </html> Output: keydown: This event is fired when user is pressing a key. Syntax: textbox.addEventListner("keydown", FUNCTION); FUNCTION is the name of the function we want to call when the event is fired. Example: HTML <!DOCTYPE html><html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8" /> <title> How to trigger HTML button after hitting enter button in textbox using JavaScript? </title></head> <body> <label for="message">Enter Your Message:</label> <br><br> <!-- Textbox --> <input type="text" id="textbox" name="message"> <br><br> <!-- Button we want to trigger on ENTER in Textbox --> <button id="button">GeeksForGeeks</button> <!-- The div element in which we will append our data from text box --> <div id="message"></div> <script> var msg = document.getElementById("message"); var button = document.getElementById("button"); var textBox = document.getElementById("textbox"); // This event is fired when button is clicked button.addEventListener("click", function () { var str = textBox.value; console.log(str); msg.innerHTML += "<p>" + str + "</p>"; }); textBox.addEventListener("keydown", function (event) { // Checking if key pressed is ENTER or not // if the key pressed is ENTER // click listener on button is called if (event.keyCode == 13) { button.click(); } }); </script></body> </html> Output: keypress: This event is fired when user is pressing a key. Syntax: textbox.addEventListner("keypress", FUNCTION); FUNCTION is the name of function we want to call when event is fired. Example: HTML <!DOCTYPE html><html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8" /> <title> How to trigger HTML button after hitting enter button in textbox using JavaScript? </title></head> <body> <label for="message">Enter Your Message:</label><br><br> <!-- Textbox --> <input type="text" id="textbox" name="message"><br><br> <!-- Button we want to trigger on ENTER in Textbox --> <button id="button">GeeksForGeeks</button> <!-- The div element in which we will append our data from text box --> <div id="message"></div> <script> var msg = document.getElementById("message"); var button = document.getElementById("button"); var textBox = document.getElementById("textbox"); // This event is fired when button is clicked button.addEventListener("click", function () { var str = textBox.value; console.log(str); msg.innerHTML += "<p>" + str + "</p>"; }); textBox.addEventListener("keypress", function (event) { // Checking if key pressed is ENTER or not // if the key pressed is ENTER // click listener on button is called if (event.keyCode == 13) { button.click(); } }); </script></body> </html> Note: Both keypress and keydown events keep repeating till the key is pressed down. Both may show similar result but keypress do not detect all keys in all browsers. Output: adnanirshad158 CSS-Misc HTML-Misc JavaScript-Misc Picked CSS HTML JavaScript Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Design a Tribute Page using HTML & CSS Types of CSS (Cascading Style Sheet) 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 ? Design a Tribute Page using HTML & CSS
[ { "code": null, "e": 28, "s": 0, "text": "\n05 Oct, 2021" }, { "code": null, "e": 500, "s": 28, "text": "Given an HTML document containing text area and the task is to trigger the button when the user hit Enter button. We can do it by using “keyup”, “keydown”, or “keypress” event listener on textbox depending on the need. When this event is triggered, we check if the key pressed is ENTER or not. If the key pressed is not ENTER, we do nothing. We will make an example that will append the content of the textbox in div when ENTER is pressed using all three event listeners." }, { "code": null, "e": 562, "s": 500, "text": "keyup: This event is fired when user releases a key. Syntax: " }, { "code": null, "e": 606, "s": 562, "text": "textbox.addEventListner(\"keyup\", FUNCTION);" }, { "code": null, "e": 676, "s": 606, "text": "FUNCTION is the name of function we want to call when event is fired." }, { "code": null, "e": 686, "s": 676, "text": "Example: " }, { "code": null, "e": 691, "s": 686, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\" xmlns=\"http://www.w3.org/1999/xhtml\"> <head> <meta charset=\"utf-8\" /> <title> How to trigger HTML button after hitting enter button in textbox using JavaScript? </title></head> <body> <label for=\"message\">Enter Your Message:</label> <br><br> <!-- Textbox --> <input type=\"text\" id=\"textbox\" name=\"message\"> <br><br> <!-- Button we want to trigger on ENTER in Textbox --> <button id=\"button\">GeeksForGeeks</button> <!-- The div element in which we will append our data from text box --> <div id=\"message\"></div> <script> var msg = document.getElementById(\"message\"); var button = document.getElementById(\"button\"); var textBox = document.getElementById(\"textbox\"); // This event is fired when button is clicked button.addEventListener(\"click\", function () { var str = textBox.value; console.log(str); msg.innerHTML += \"<p>\" + str + \"</p>\"; }); textBox.addEventListener(\"keyup\", function (event) { // Checking if key pressed is ENTER or not // if the key pressed is ENTER // click listener on button is called if (event.keyCode == 13) { button.click(); } }); </script></body> </html>", "e": 2045, "s": 691, "text": null }, { "code": null, "e": 2054, "s": 2045, "text": "Output: " }, { "code": null, "e": 2121, "s": 2054, "text": "keydown: This event is fired when user is pressing a key. Syntax: " }, { "code": null, "e": 2167, "s": 2121, "text": "textbox.addEventListner(\"keydown\", FUNCTION);" }, { "code": null, "e": 2245, "s": 2167, "text": "FUNCTION is the name of the function we want to call when the event is fired." }, { "code": null, "e": 2255, "s": 2245, "text": "Example: " }, { "code": null, "e": 2260, "s": 2255, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\" xmlns=\"http://www.w3.org/1999/xhtml\"> <head> <meta charset=\"utf-8\" /> <title> How to trigger HTML button after hitting enter button in textbox using JavaScript? </title></head> <body> <label for=\"message\">Enter Your Message:</label> <br><br> <!-- Textbox --> <input type=\"text\" id=\"textbox\" name=\"message\"> <br><br> <!-- Button we want to trigger on ENTER in Textbox --> <button id=\"button\">GeeksForGeeks</button> <!-- The div element in which we will append our data from text box --> <div id=\"message\"></div> <script> var msg = document.getElementById(\"message\"); var button = document.getElementById(\"button\"); var textBox = document.getElementById(\"textbox\"); // This event is fired when button is clicked button.addEventListener(\"click\", function () { var str = textBox.value; console.log(str); msg.innerHTML += \"<p>\" + str + \"</p>\"; }); textBox.addEventListener(\"keydown\", function (event) { // Checking if key pressed is ENTER or not // if the key pressed is ENTER // click listener on button is called if (event.keyCode == 13) { button.click(); } }); </script></body> </html>", "e": 3616, "s": 2260, "text": null }, { "code": null, "e": 3625, "s": 3616, "text": "Output: " }, { "code": null, "e": 3693, "s": 3625, "text": "keypress: This event is fired when user is pressing a key. Syntax: " }, { "code": null, "e": 3740, "s": 3693, "text": "textbox.addEventListner(\"keypress\", FUNCTION);" }, { "code": null, "e": 3810, "s": 3740, "text": "FUNCTION is the name of function we want to call when event is fired." }, { "code": null, "e": 3820, "s": 3810, "text": "Example: " }, { "code": null, "e": 3825, "s": 3820, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\" xmlns=\"http://www.w3.org/1999/xhtml\"> <head> <meta charset=\"utf-8\" /> <title> How to trigger HTML button after hitting enter button in textbox using JavaScript? </title></head> <body> <label for=\"message\">Enter Your Message:</label><br><br> <!-- Textbox --> <input type=\"text\" id=\"textbox\" name=\"message\"><br><br> <!-- Button we want to trigger on ENTER in Textbox --> <button id=\"button\">GeeksForGeeks</button> <!-- The div element in which we will append our data from text box --> <div id=\"message\"></div> <script> var msg = document.getElementById(\"message\"); var button = document.getElementById(\"button\"); var textBox = document.getElementById(\"textbox\"); // This event is fired when button is clicked button.addEventListener(\"click\", function () { var str = textBox.value; console.log(str); msg.innerHTML += \"<p>\" + str + \"</p>\"; }); textBox.addEventListener(\"keypress\", function (event) { // Checking if key pressed is ENTER or not // if the key pressed is ENTER // click listener on button is called if (event.keyCode == 13) { button.click(); } }); </script></body> </html>", "e": 5170, "s": 3825, "text": null }, { "code": null, "e": 5336, "s": 5170, "text": "Note: Both keypress and keydown events keep repeating till the key is pressed down. Both may show similar result but keypress do not detect all keys in all browsers." }, { "code": null, "e": 5345, "s": 5336, "text": "Output: " }, { "code": null, "e": 5362, "s": 5347, "text": "adnanirshad158" }, { "code": null, "e": 5371, "s": 5362, "text": "CSS-Misc" }, { "code": null, "e": 5381, "s": 5371, "text": "HTML-Misc" }, { "code": null, "e": 5397, "s": 5381, "text": "JavaScript-Misc" }, { "code": null, "e": 5404, "s": 5397, "text": "Picked" }, { "code": null, "e": 5408, "s": 5404, "text": "CSS" }, { "code": null, "e": 5413, "s": 5408, "text": "HTML" }, { "code": null, "e": 5424, "s": 5413, "text": "JavaScript" }, { "code": null, "e": 5441, "s": 5424, "text": "Web Technologies" }, { "code": null, "e": 5468, "s": 5441, "text": "Web technologies Questions" }, { "code": null, "e": 5473, "s": 5468, "text": "HTML" }, { "code": null, "e": 5571, "s": 5473, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5610, "s": 5571, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 5647, "s": 5610, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 5686, "s": 5647, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 5750, "s": 5686, "text": "How to position a div at the bottom of its container using CSS?" }, { "code": null, "e": 5811, "s": 5750, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 5835, "s": 5811, "text": "REST API (Introduction)" }, { "code": null, "e": 5888, "s": 5835, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 5948, "s": 5888, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 6009, "s": 5948, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" } ]
Print all pairs with given sum
01 Jul, 2021 Given an array of integers, and a number ‘sum’, print all pairs in the array whose sum is equal to ‘sum’. Examples : Input : arr[] = {1, 5, 7, -1, 5}, sum = 6 Output : (1, 5) (7, -1) (1, 5) Input : arr[] = {2, 5, 17, -1}, sum = 7 Output : (2, 5) A simple solution is to traverse each element and check if there’s another number in the array which can be added to it to give sum. C++ Java Python3 C# PHP Javascript // C++ implementation of simple method to// find print pairs with given sum.#include <bits/stdc++.h>using namespace std; // Returns number of pairs in arr[0..n-1]// with sum equal to 'sum'int printPairs(int arr[], int n, int sum){ int count = 0; // Initialize result // Consider all possible pairs and check // their sums for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) if (arr[i] + arr[j] == sum) cout << "(" << arr[i] << ", " << arr[j] << ")" << endl;} // Driver function to test the above functionint main(){ int arr[] = { 1, 5, 7, -1, 5 }; int n = sizeof(arr) / sizeof(arr[0]); int sum = 6; printPairs(arr, n, sum); return 0;} // Java implementation of// simple method to find// print pairs with given sum. class GFG { // Returns number of pairs // in arr[0..n-1] with sum // equal to 'sum' static void printPairs(int arr[], int n, int sum) { // int count = 0; // Consider all possible pairs // and check their sums for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) if (arr[i] + arr[j] == sum) System.out.println("(" + arr[i] + ", " + arr[j] + ")"); } // Driver Code public static void main(String[] arg) { int arr[] = { 1, 5, 7, -1, 5 }; int n = arr.length; int sum = 6; printPairs(arr, n, sum); }} // This code is contributed// by Smitha # Python 3 implementation# of simple method to find# print pairs with given sum. # Returns number of pairs# in arr[0..n-1] with sum# equal to 'sum'def printPairs(arr, n, sum): # count = 0 # Consider all possible # pairs and check their sums for i in range(0, n ): for j in range(i + 1, n ): if (arr[i] + arr[j] == sum): print("(", arr[i], ", ", arr[j], ")", sep = "") # Driver Codearr = [1, 5, 7, -1, 5]n = len(arr)sum = 6printPairs(arr, n, sum) # This code is contributed# by Smitha // C# implementation of simple// method to find print pairs// with given sum.using System; class GFG { // Returns number of pairs // in arr[0..n-1] with sum // equal to 'sum' static void printPairs(int[] arr, int n, int sum) { // int count = 0; // Consider all possible pairs // and check their sums for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) if (arr[i] + arr[j] == sum) Console.Write("(" + arr[i] + ", " + arr[j] + ")" + "\n"); } // Driver Code public static void Main() { int[] arr = { 1, 5, 7, -1, 5 }; int n = arr.Length; int sum = 6; printPairs(arr, n, sum); }} // This code is contributed// by Smitha <?php// PHP implementation of simple// method to find print pairs// with given sum. // Returns number of pairs in// arr[0..n-1] with sum equal// to 'sum'function printPairs($arr, $n, $sum){ // Initialize result $count = 0; // Consider all possible // pairs and check their sums for ($i = 0; $i < $n; $i++) for ( $j = $i + 1; $j < $n; $j++) if ($arr[$i] + $arr[$j] == $sum) echo "(", $arr[$i], ", ", $arr[$j], ")", "\n";} // Driver Code$arr = array (1, 5, 7, -1, 5);$n = sizeof($arr);$sum = 6;printPairs($arr, $n, $sum); // This code is contributed by m_kit?> <script> // JavaScript implementation of simple method to// find print pairs with given sum. // Returns number of pairs in arr[0..n-1]// with sum equal to 'sum'function printPairs(arr, n, sum){ let count = 0; // Initialize result // Consider all possible pairs and check // their sums for (let i = 0; i < n; i++) for (let j = i + 1; j < n; j++) if (arr[i] + arr[j] == sum) document.write("(" + arr[i] + ", " + arr[j] + ")" + "<br>");} // Driver function to test the above function let arr = [ 1, 5, 7, -1, 5 ]; let n = arr.length; let sum = 6; printPairs(arr, n, sum); // This code is contributed by Surbhi Tyagi </script> (1, 5) (1, 5) (7, -1) Method 2 (Use hashing). We create an empty hash table. Now we traverse through the array and check for pairs in the hash table. If a matching element is found, we print the pair number of times equal to the number of occurrences of the matching element. Note that the worst case of time complexity of this solution is O(c + n) where c is the count of pairs with a given sum. C++ Java Python3 C# Javascript // C++ implementation of simple method to// find count of pairs with given sum.#include <bits/stdc++.h>using namespace std; // Returns number of pairs in arr[0..n-1]// with sum equal to 'sum'void printPairs(int arr[], int n, int sum){ // Store counts of all elements in map m unordered_map<int, int> m; // Traverse through all elements for (int i = 0; i < n; i++) { // Search if a pair can be formed with // arr[i]. int rem = sum - arr[i]; if (m.find(rem) != m.end()) { int count = m[rem]; for (int j = 0; j < count; j++) cout << "(" << rem << ", " << arr[i] << ")" << endl; } m[arr[i]]++; }} // Driver function to test the above functionint main(){ int arr[] = { 1, 5, 7, -1, 5 }; int n = sizeof(arr) / sizeof(arr[0]); int sum = 6; printPairs(arr, n, sum); return 0;} // Java implementation of simple method to// find count of pairs with given sum.import java.util.*; class GFG{ // Returns number of pairs in arr[0..n-1]// with sum equal to 'sum'static void printPairs(int arr[], int n, int sum){ // Store counts of all elements in map m HashMap<Integer, Integer> mp = new HashMap<Integer, Integer>(); // Traverse through all elements for(int i = 0; i < n; i++) { // Search if a pair can be formed with // arr[i]. int rem = sum - arr[i]; if (mp.containsKey(rem)) { int count = mp.get(rem); for(int j = 0; j < count; j++) System.out.print("(" + rem + ", " + arr[i] + ")" + "\n"); } if (mp.containsKey(arr[i])) { mp.put(arr[i], mp.get(arr[i]) + 1); } else { mp.put(arr[i], 1); } }} // Driver codepublic static void main(String[] args){ int arr[] = { 1, 5, 7, -1, 5 }; int n = arr.length; int sum = 6; printPairs(arr, n, sum);}} // This code is contributed by Princi Singh # Python3 implementation of simple method to# find count of pairs with given sum. # Returns number of pairs in arr[0..n-1]# with sum equal to 'sum'def printPairs(arr, n, sum): # Store counts of all elements # in a dictionary mydict = dict() # Traverse through all the elements for i in range(n): # Search if a pair can be # formed with arr[i] temp = sum - arr[i] if temp in mydict: count = mydict[temp] for j in range(count): print("(", temp, ", ", arr[i], ")", sep = "", end = '\n') if arr[i] in mydict: mydict[arr[i]] += 1 else: mydict[arr[i]] = 1 # Driver codeif __name__ == '__main__': arr = [ 1, 5, 7, -1, 5 ] n = len(arr) sum = 6 printPairs(arr, n, sum) # This code is contributed by MuskanKalra1 // C# implementation of simple method to// find count of pairs with given sum.using System;using System.Collections;using System.Collections.Generic; class GFG{ // Returns number of pairs in arr[0..n-1]// with sum equal to 'sum'static void printPairs(int []arr, int n, int sum){ // Store counts of all elements in map m Dictionary<int, int> m = new Dictionary<int, int>(); // Traverse through all elements for(int i = 0; i < n; i++) { // Search if a pair can be formed with // arr[i]. int rem = sum - arr[i]; if (m.ContainsKey(rem)) { int count = m[rem]; for(int j = 0; j < count; j++) { Console.Write("(" + rem + ", " + arr[i] + ")" + "\n"); } } if (m.ContainsKey(arr[i])) { m[arr[i]]++; } else { m[arr[i]] = 1; } }} // Driver codepublic static void Main(string[] args){ int []arr = { 1, 5, 7, -1, 5 }; int n = arr.Length; int sum = 6; printPairs(arr, n, sum);}} // This code is contributed by rutvik_56 <script> // JavaScript implementation of simple method to // find count of pairs with given sum. // Returns number of pairs in arr[0..n-1] // with sum equal to 'sum' function printPairs(arr, n, sum) { // Store counts of all elements in map m var m = {}; // Traverse through all elements for (var i = 0; i < n; i++) { // Search if a pair can be formed with // arr[i]. var rem = sum - arr[i]; if (m.hasOwnProperty(rem)) { var count = m[rem]; for (var j = 0; j < count; j++) { document.write("(" + rem + ", " + arr[i] + ")" + "<br>"); } } if (m.hasOwnProperty(arr[i])) { m[arr[i]]++; } else { m[arr[i]] = 1; } } } // Driver code var arr = [1, 5, 7, -1, 5]; var n = arr.length; var sum = 6; printPairs(arr, n, sum); // This code is contributed by rdtank. </script> (1, 5) (7, -1) (1, 5) Method 3. Another method to Print all pairs with the given sum is given as follows: C++ Java Python3 C# Javascript // C++ code to implement// the above approach#include<bits/stdc++.h>using namespace std; void pairedElements(int arr[], int sum, int n){ int low = 0; int high = n - 1; while (low < high) { if (arr[low] + arr[high] == sum) { cout << "The pair is : (" << arr[low] << ", " << arr[high] << ")" << endl; } if (arr[low] + arr[high] > sum) { high--; } else { low++; } }} // Driver codeint main(){ int arr[] = {2, 3, 4, -2, 6, 8, 9, 11}; int n = sizeof(arr) / sizeof(arr[0]); sort(arr, arr + n); pairedElements(arr, 6, n);} // This code is contributed by Rajput-Ji import java.util.Arrays; /** * Created by sampat. */public class SumOfPairs { public void pairedElements(int arr[], int sum) { int low = 0; int high = arr.length - 1; while (low < high) { if (arr[low] + arr[high] == sum) { System.out.println("The pair is : (" + arr[low] + ", " + arr[high] + ")"); } if (arr[low] + arr[high] > sum) { high--; } else { low++; } } } public static void main(String[] args) { int arr[] = { 2, 3, 4, -2, 6, 8, 9, 11 }; Arrays.sort(arr); SumOfPairs sp = new SumOfPairs(); sp.pairedElements(arr, 6); }} # Python3 program for the# above approachdef pairedElements(arr, sum): low = 0; high = len(arr) - 1; while (low < high): if (arr[low] + arr[high] == sum): print("The pair is : (", arr[low], ", ", arr[high], ")"); if (arr[low] + arr[high] > sum): high -= 1; else: low += 1; # Driver codeif __name__ == '__main__': arr = [2, 3, 4, -2, 6, 8, 9, 11]; arr.sort(); pairedElements(arr, 6); # This code contributed by shikhasingrajput // C# program to find triplets in a given// array whose sum is equal to given sum.using System; public class SumOfPairs{ public void pairedElements(int []arr, int sum) { int low = 0; int high = arr.Length - 1; while (low < high) { if (arr[low] + arr[high] == sum) { Console.WriteLine("The pair is : (" + arr[low] + ", " + arr[high] + ")"); } if (arr[low] + arr[high] > sum) { high--; } else { low++; } } } // Driver code public static void Main(String[] args) { int []arr = { 2, 3, 4, -2, 6, 8, 9, 11 }; Array.Sort(arr); SumOfPairs sp = new SumOfPairs(); sp.pairedElements(arr, 6); }} // This code is contributed by Princi Singh <script> // Javascript code to implement // the above approach function pairedElements(arr, sum, n) { var low = 0; var high = n - 1; while (low < high) { if (arr[low] + arr[high] == sum) { document.write("The pair is : (" + arr[low] + ", " + arr[high] + ")<br>"); } if (arr[low] + arr[high] > sum) { high--; } else { low++; } } } // Driver code var arr = [ 2, 3, 4, -2, 6, 8, 9, 11] var n = arr.length; arr.sort(function(a,b){return a-b;}); pairedElements(arr, 6, n); </script> The pair is : (-2, 8) The pair is : (2, 4) jit_t Smitha Dinesh Semwal SampatKumar1 princi singh rutvik_56 Rajput-Ji shikhasingrajput MuskanKalra1 surbhityagi15 rrrtnx rdtank Arrays Hash Searching Arrays Searching Hash Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Multidimensional Arrays in Java Stack Data Structure (Introduction and Program) Linear Search What is Hashing | A Complete Tutorial Internal Working of HashMap in Java Hashing | Set 1 (Introduction) Longest Consecutive Subsequence Sort string of characters
[ { "code": null, "e": 52, "s": 24, "text": "\n01 Jul, 2021" }, { "code": null, "e": 158, "s": 52, "text": "Given an array of integers, and a number ‘sum’, print all pairs in the array whose sum is equal to ‘sum’." }, { "code": null, "e": 326, "s": 158, "text": "Examples :\nInput : arr[] = {1, 5, 7, -1, 5}, \n sum = 6\nOutput : (1, 5) (7, -1) (1, 5)\n\nInput : arr[] = {2, 5, 17, -1}, \n sum = 7\nOutput : (2, 5)" }, { "code": null, "e": 459, "s": 326, "text": "A simple solution is to traverse each element and check if there’s another number in the array which can be added to it to give sum." }, { "code": null, "e": 463, "s": 459, "text": "C++" }, { "code": null, "e": 468, "s": 463, "text": "Java" }, { "code": null, "e": 476, "s": 468, "text": "Python3" }, { "code": null, "e": 479, "s": 476, "text": "C#" }, { "code": null, "e": 483, "s": 479, "text": "PHP" }, { "code": null, "e": 494, "s": 483, "text": "Javascript" }, { "code": "// C++ implementation of simple method to// find print pairs with given sum.#include <bits/stdc++.h>using namespace std; // Returns number of pairs in arr[0..n-1]// with sum equal to 'sum'int printPairs(int arr[], int n, int sum){ int count = 0; // Initialize result // Consider all possible pairs and check // their sums for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) if (arr[i] + arr[j] == sum) cout << \"(\" << arr[i] << \", \" << arr[j] << \")\" << endl;} // Driver function to test the above functionint main(){ int arr[] = { 1, 5, 7, -1, 5 }; int n = sizeof(arr) / sizeof(arr[0]); int sum = 6; printPairs(arr, n, sum); return 0;}", "e": 1218, "s": 494, "text": null }, { "code": "// Java implementation of// simple method to find// print pairs with given sum. class GFG { // Returns number of pairs // in arr[0..n-1] with sum // equal to 'sum' static void printPairs(int arr[], int n, int sum) { // int count = 0; // Consider all possible pairs // and check their sums for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) if (arr[i] + arr[j] == sum) System.out.println(\"(\" + arr[i] + \", \" + arr[j] + \")\"); } // Driver Code public static void main(String[] arg) { int arr[] = { 1, 5, 7, -1, 5 }; int n = arr.length; int sum = 6; printPairs(arr, n, sum); }} // This code is contributed// by Smitha", "e": 2001, "s": 1218, "text": null }, { "code": "# Python 3 implementation# of simple method to find# print pairs with given sum. # Returns number of pairs# in arr[0..n-1] with sum# equal to 'sum'def printPairs(arr, n, sum): # count = 0 # Consider all possible # pairs and check their sums for i in range(0, n ): for j in range(i + 1, n ): if (arr[i] + arr[j] == sum): print(\"(\", arr[i], \", \", arr[j], \")\", sep = \"\") # Driver Codearr = [1, 5, 7, -1, 5]n = len(arr)sum = 6printPairs(arr, n, sum) # This code is contributed# by Smitha", "e": 2575, "s": 2001, "text": null }, { "code": "// C# implementation of simple// method to find print pairs// with given sum.using System; class GFG { // Returns number of pairs // in arr[0..n-1] with sum // equal to 'sum' static void printPairs(int[] arr, int n, int sum) { // int count = 0; // Consider all possible pairs // and check their sums for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) if (arr[i] + arr[j] == sum) Console.Write(\"(\" + arr[i] + \", \" + arr[j] + \")\" + \"\\n\"); } // Driver Code public static void Main() { int[] arr = { 1, 5, 7, -1, 5 }; int n = arr.Length; int sum = 6; printPairs(arr, n, sum); }} // This code is contributed// by Smitha", "e": 3391, "s": 2575, "text": null }, { "code": "<?php// PHP implementation of simple// method to find print pairs// with given sum. // Returns number of pairs in// arr[0..n-1] with sum equal// to 'sum'function printPairs($arr, $n, $sum){ // Initialize result $count = 0; // Consider all possible // pairs and check their sums for ($i = 0; $i < $n; $i++) for ( $j = $i + 1; $j < $n; $j++) if ($arr[$i] + $arr[$j] == $sum) echo \"(\", $arr[$i], \", \", $arr[$j], \")\", \"\\n\";} // Driver Code$arr = array (1, 5, 7, -1, 5);$n = sizeof($arr);$sum = 6;printPairs($arr, $n, $sum); // This code is contributed by m_kit?>", "e": 4025, "s": 3391, "text": null }, { "code": "<script> // JavaScript implementation of simple method to// find print pairs with given sum. // Returns number of pairs in arr[0..n-1]// with sum equal to 'sum'function printPairs(arr, n, sum){ let count = 0; // Initialize result // Consider all possible pairs and check // their sums for (let i = 0; i < n; i++) for (let j = i + 1; j < n; j++) if (arr[i] + arr[j] == sum) document.write(\"(\" + arr[i] + \", \" + arr[j] + \")\" + \"<br>\");} // Driver function to test the above function let arr = [ 1, 5, 7, -1, 5 ]; let n = arr.length; let sum = 6; printPairs(arr, n, sum); // This code is contributed by Surbhi Tyagi </script>", "e": 4728, "s": 4025, "text": null }, { "code": null, "e": 4750, "s": 4728, "text": "(1, 5)\n(1, 5)\n(7, -1)" }, { "code": null, "e": 5127, "s": 4752, "text": "Method 2 (Use hashing). We create an empty hash table. Now we traverse through the array and check for pairs in the hash table. If a matching element is found, we print the pair number of times equal to the number of occurrences of the matching element. Note that the worst case of time complexity of this solution is O(c + n) where c is the count of pairs with a given sum." }, { "code": null, "e": 5131, "s": 5127, "text": "C++" }, { "code": null, "e": 5136, "s": 5131, "text": "Java" }, { "code": null, "e": 5144, "s": 5136, "text": "Python3" }, { "code": null, "e": 5147, "s": 5144, "text": "C#" }, { "code": null, "e": 5158, "s": 5147, "text": "Javascript" }, { "code": "// C++ implementation of simple method to// find count of pairs with given sum.#include <bits/stdc++.h>using namespace std; // Returns number of pairs in arr[0..n-1]// with sum equal to 'sum'void printPairs(int arr[], int n, int sum){ // Store counts of all elements in map m unordered_map<int, int> m; // Traverse through all elements for (int i = 0; i < n; i++) { // Search if a pair can be formed with // arr[i]. int rem = sum - arr[i]; if (m.find(rem) != m.end()) { int count = m[rem]; for (int j = 0; j < count; j++) cout << \"(\" << rem << \", \" << arr[i] << \")\" << endl; } m[arr[i]]++; }} // Driver function to test the above functionint main(){ int arr[] = { 1, 5, 7, -1, 5 }; int n = sizeof(arr) / sizeof(arr[0]); int sum = 6; printPairs(arr, n, sum); return 0;}", "e": 6058, "s": 5158, "text": null }, { "code": "// Java implementation of simple method to// find count of pairs with given sum.import java.util.*; class GFG{ // Returns number of pairs in arr[0..n-1]// with sum equal to 'sum'static void printPairs(int arr[], int n, int sum){ // Store counts of all elements in map m HashMap<Integer, Integer> mp = new HashMap<Integer, Integer>(); // Traverse through all elements for(int i = 0; i < n; i++) { // Search if a pair can be formed with // arr[i]. int rem = sum - arr[i]; if (mp.containsKey(rem)) { int count = mp.get(rem); for(int j = 0; j < count; j++) System.out.print(\"(\" + rem + \", \" + arr[i] + \")\" + \"\\n\"); } if (mp.containsKey(arr[i])) { mp.put(arr[i], mp.get(arr[i]) + 1); } else { mp.put(arr[i], 1); } }} // Driver codepublic static void main(String[] args){ int arr[] = { 1, 5, 7, -1, 5 }; int n = arr.length; int sum = 6; printPairs(arr, n, sum);}} // This code is contributed by Princi Singh", "e": 7299, "s": 6058, "text": null }, { "code": "# Python3 implementation of simple method to# find count of pairs with given sum. # Returns number of pairs in arr[0..n-1]# with sum equal to 'sum'def printPairs(arr, n, sum): # Store counts of all elements # in a dictionary mydict = dict() # Traverse through all the elements for i in range(n): # Search if a pair can be # formed with arr[i] temp = sum - arr[i] if temp in mydict: count = mydict[temp] for j in range(count): print(\"(\", temp, \", \", arr[i], \")\", sep = \"\", end = '\\n') if arr[i] in mydict: mydict[arr[i]] += 1 else: mydict[arr[i]] = 1 # Driver codeif __name__ == '__main__': arr = [ 1, 5, 7, -1, 5 ] n = len(arr) sum = 6 printPairs(arr, n, sum) # This code is contributed by MuskanKalra1", "e": 8204, "s": 7299, "text": null }, { "code": "// C# implementation of simple method to// find count of pairs with given sum.using System;using System.Collections;using System.Collections.Generic; class GFG{ // Returns number of pairs in arr[0..n-1]// with sum equal to 'sum'static void printPairs(int []arr, int n, int sum){ // Store counts of all elements in map m Dictionary<int, int> m = new Dictionary<int, int>(); // Traverse through all elements for(int i = 0; i < n; i++) { // Search if a pair can be formed with // arr[i]. int rem = sum - arr[i]; if (m.ContainsKey(rem)) { int count = m[rem]; for(int j = 0; j < count; j++) { Console.Write(\"(\" + rem + \", \" + arr[i] + \")\" + \"\\n\"); } } if (m.ContainsKey(arr[i])) { m[arr[i]]++; } else { m[arr[i]] = 1; } }} // Driver codepublic static void Main(string[] args){ int []arr = { 1, 5, 7, -1, 5 }; int n = arr.Length; int sum = 6; printPairs(arr, n, sum);}} // This code is contributed by rutvik_56", "e": 9473, "s": 8204, "text": null }, { "code": "<script> // JavaScript implementation of simple method to // find count of pairs with given sum. // Returns number of pairs in arr[0..n-1] // with sum equal to 'sum' function printPairs(arr, n, sum) { // Store counts of all elements in map m var m = {}; // Traverse through all elements for (var i = 0; i < n; i++) { // Search if a pair can be formed with // arr[i]. var rem = sum - arr[i]; if (m.hasOwnProperty(rem)) { var count = m[rem]; for (var j = 0; j < count; j++) { document.write(\"(\" + rem + \", \" + arr[i] + \")\" + \"<br>\"); } } if (m.hasOwnProperty(arr[i])) { m[arr[i]]++; } else { m[arr[i]] = 1; } } } // Driver code var arr = [1, 5, 7, -1, 5]; var n = arr.length; var sum = 6; printPairs(arr, n, sum); // This code is contributed by rdtank. </script>", "e": 10485, "s": 9473, "text": null }, { "code": null, "e": 10507, "s": 10485, "text": "(1, 5)\n(7, -1)\n(1, 5)" }, { "code": null, "e": 10594, "s": 10509, "text": "Method 3. Another method to Print all pairs with the given sum is given as follows: " }, { "code": null, "e": 10598, "s": 10594, "text": "C++" }, { "code": null, "e": 10603, "s": 10598, "text": "Java" }, { "code": null, "e": 10611, "s": 10603, "text": "Python3" }, { "code": null, "e": 10614, "s": 10611, "text": "C#" }, { "code": null, "e": 10625, "s": 10614, "text": "Javascript" }, { "code": "// C++ code to implement// the above approach#include<bits/stdc++.h>using namespace std; void pairedElements(int arr[], int sum, int n){ int low = 0; int high = n - 1; while (low < high) { if (arr[low] + arr[high] == sum) { cout << \"The pair is : (\" << arr[low] << \", \" << arr[high] << \")\" << endl; } if (arr[low] + arr[high] > sum) { high--; } else { low++; } }} // Driver codeint main(){ int arr[] = {2, 3, 4, -2, 6, 8, 9, 11}; int n = sizeof(arr) / sizeof(arr[0]); sort(arr, arr + n); pairedElements(arr, 6, n);} // This code is contributed by Rajput-Ji", "e": 11296, "s": 10625, "text": null }, { "code": "import java.util.Arrays; /** * Created by sampat. */public class SumOfPairs { public void pairedElements(int arr[], int sum) { int low = 0; int high = arr.length - 1; while (low < high) { if (arr[low] + arr[high] == sum) { System.out.println(\"The pair is : (\" + arr[low] + \", \" + arr[high] + \")\"); } if (arr[low] + arr[high] > sum) { high--; } else { low++; } } } public static void main(String[] args) { int arr[] = { 2, 3, 4, -2, 6, 8, 9, 11 }; Arrays.sort(arr); SumOfPairs sp = new SumOfPairs(); sp.pairedElements(arr, 6); }}", "e": 12048, "s": 11296, "text": null }, { "code": "# Python3 program for the# above approachdef pairedElements(arr, sum): low = 0; high = len(arr) - 1; while (low < high): if (arr[low] + arr[high] == sum): print(\"The pair is : (\", arr[low], \", \", arr[high], \")\"); if (arr[low] + arr[high] > sum): high -= 1; else: low += 1; # Driver codeif __name__ == '__main__': arr = [2, 3, 4, -2, 6, 8, 9, 11]; arr.sort(); pairedElements(arr, 6); # This code contributed by shikhasingrajput", "e": 12592, "s": 12048, "text": null }, { "code": "// C# program to find triplets in a given// array whose sum is equal to given sum.using System; public class SumOfPairs{ public void pairedElements(int []arr, int sum) { int low = 0; int high = arr.Length - 1; while (low < high) { if (arr[low] + arr[high] == sum) { Console.WriteLine(\"The pair is : (\" + arr[low] + \", \" + arr[high] + \")\"); } if (arr[low] + arr[high] > sum) { high--; } else { low++; } } } // Driver code public static void Main(String[] args) { int []arr = { 2, 3, 4, -2, 6, 8, 9, 11 }; Array.Sort(arr); SumOfPairs sp = new SumOfPairs(); sp.pairedElements(arr, 6); }} // This code is contributed by Princi Singh", "e": 13484, "s": 12592, "text": null }, { "code": "<script> // Javascript code to implement // the above approach function pairedElements(arr, sum, n) { var low = 0; var high = n - 1; while (low < high) { if (arr[low] + arr[high] == sum) { document.write(\"The pair is : (\" + arr[low] + \", \" + arr[high] + \")<br>\"); } if (arr[low] + arr[high] > sum) { high--; } else { low++; } } } // Driver code var arr = [ 2, 3, 4, -2, 6, 8, 9, 11] var n = arr.length; arr.sort(function(a,b){return a-b;}); pairedElements(arr, 6, n); </script>", "e": 14270, "s": 13484, "text": null }, { "code": null, "e": 14313, "s": 14270, "text": "The pair is : (-2, 8)\nThe pair is : (2, 4)" }, { "code": null, "e": 14321, "s": 14315, "text": "jit_t" }, { "code": null, "e": 14342, "s": 14321, "text": "Smitha Dinesh Semwal" }, { "code": null, "e": 14355, "s": 14342, "text": "SampatKumar1" }, { "code": null, "e": 14368, "s": 14355, "text": "princi singh" }, { "code": null, "e": 14378, "s": 14368, "text": "rutvik_56" }, { "code": null, "e": 14388, "s": 14378, "text": "Rajput-Ji" }, { "code": null, "e": 14405, "s": 14388, "text": "shikhasingrajput" }, { "code": null, "e": 14418, "s": 14405, "text": "MuskanKalra1" }, { "code": null, "e": 14432, "s": 14418, "text": "surbhityagi15" }, { "code": null, "e": 14439, "s": 14432, "text": "rrrtnx" }, { "code": null, "e": 14446, "s": 14439, "text": "rdtank" }, { "code": null, "e": 14453, "s": 14446, "text": "Arrays" }, { "code": null, "e": 14458, "s": 14453, "text": "Hash" }, { "code": null, "e": 14468, "s": 14458, "text": "Searching" }, { "code": null, "e": 14475, "s": 14468, "text": "Arrays" }, { "code": null, "e": 14485, "s": 14475, "text": "Searching" }, { "code": null, "e": 14490, "s": 14485, "text": "Hash" }, { "code": null, "e": 14588, "s": 14490, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 14656, "s": 14588, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 14700, "s": 14656, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 14732, "s": 14700, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 14780, "s": 14732, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 14794, "s": 14780, "text": "Linear Search" }, { "code": null, "e": 14832, "s": 14794, "text": "What is Hashing | A Complete Tutorial" }, { "code": null, "e": 14868, "s": 14832, "text": "Internal Working of HashMap in Java" }, { "code": null, "e": 14899, "s": 14868, "text": "Hashing | Set 1 (Introduction)" }, { "code": null, "e": 14931, "s": 14899, "text": "Longest Consecutive Subsequence" } ]
User Management in Linux
16 Aug, 2021 A user is an entity, in a Linux operating system, that can manipulate files and perform several other operations. Each user is assigned an ID that is unique for each user in the operating system. In this post, we will learn about users and commands which are used to get information about the users. After installation of the operating system, the ID 0 is assigned to the root user and the IDs 1 to 999 (both inclusive) are assigned to the system users and hence the ids for local user begins from 1000 onwards. In a single directory, we can create 60,000 users. Now we will discuss the important commands to manage users in Linux. 1. To list out all the users in Linux, use the awk command with -F option. Here, we are accessing a file and printing only first column with the help of print $1 and awk. awk -F':' '{ print $1}' /etc/passwd 2. Using id command, you can get the ID of any username. Every user has an id assigned to it and the user is identified with the help of this id. By default, this id is also the group id of the user. id username Example: id test 3. The command to add a user. useradd command adds a new user to the directory. The user is given the ID automatically depending on which category it falls in. The username of the user will be as provided by us in the command. sudo useradd username Example: sudo useradd geeks 4. Using passwd command to assign a password to a user. After using this command we have to enter the new password for the user and then the password gets updated to the new password. passwd username Example: passwd geeks 5. Accessing a user configuration file. cat /etc/passwd This commands prints the data of the configuration file. This file contains information about the user in the format. username : x : user id : user group id : : /home/username : /bin/bash Now we will go through the commands to modify information. 6. The command to change the user ID for a user. usermod -u new_id username This command can change the user ID of a user. The user with the given username will be assigned with the new ID given in the command and the old ID will be removed. Example: sudo usermod -u 1982 test 7. Command to Modify the group ID of a user. usermod -g new_group_id username This command can change the group ID of a user and hence it can even be used to move a user to an already existing group. It will change the group ID of the user whose username is given and sets the group ID as the given new_group_id. Example: sudo usermod -g 1005 test 8. You can change the user login name using usermod command. The below command is used to change the login name of the user. The old login name of the user is changed to the new login name provided. sudo usermod -l new_login_name old_login_name Example: sudo usermod -c John_Wick John_Doe 9. The command to change the home directory. The below command change the home directory of the user whose username is given and sets the new home directory as the directory whose path is provided. usermod -d new_home_directory_path username Example: usermod -d new_home_directory test 10. You can also delete a user name. The below command deletes the user whose username is provided. Make sure that the user is not part of a group. If the user is part of a group then it will not be deleted directly, hence we will have to first remove him from the group and then we can delete him. userdel -r username Example: sudo userdel -r new_geeks gabaa406 Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n16 Aug, 2021" }, { "code": null, "e": 541, "s": 28, "text": "A user is an entity, in a Linux operating system, that can manipulate files and perform several other operations. Each user is assigned an ID that is unique for each user in the operating system. In this post, we will learn about users and commands which are used to get information about the users. After installation of the operating system, the ID 0 is assigned to the root user and the IDs 1 to 999 (both inclusive) are assigned to the system users and hence the ids for local user begins from 1000 onwards. " }, { "code": null, "e": 662, "s": 541, "text": "In a single directory, we can create 60,000 users. Now we will discuss the important commands to manage users in Linux. " }, { "code": null, "e": 834, "s": 662, "text": "1. To list out all the users in Linux, use the awk command with -F option. Here, we are accessing a file and printing only first column with the help of print $1 and awk. " }, { "code": null, "e": 870, "s": 834, "text": "awk -F':' '{ print $1}' /etc/passwd" }, { "code": null, "e": 1072, "s": 870, "text": "2. Using id command, you can get the ID of any username. Every user has an id assigned to it and the user is identified with the help of this id. By default, this id is also the group id of the user. " }, { "code": null, "e": 1084, "s": 1072, "text": "id username" }, { "code": null, "e": 1103, "s": 1084, "text": "Example: id test " }, { "code": null, "e": 1331, "s": 1103, "text": "3. The command to add a user. useradd command adds a new user to the directory. The user is given the ID automatically depending on which category it falls in. The username of the user will be as provided by us in the command. " }, { "code": null, "e": 1353, "s": 1331, "text": "sudo useradd username" }, { "code": null, "e": 1383, "s": 1353, "text": "Example: sudo useradd geeks " }, { "code": null, "e": 1569, "s": 1383, "text": "4. Using passwd command to assign a password to a user. After using this command we have to enter the new password for the user and then the password gets updated to the new password. " }, { "code": null, "e": 1585, "s": 1569, "text": "passwd username" }, { "code": null, "e": 1609, "s": 1585, "text": "Example: passwd geeks " }, { "code": null, "e": 1651, "s": 1609, "text": "5. Accessing a user configuration file. " }, { "code": null, "e": 1667, "s": 1651, "text": "cat /etc/passwd" }, { "code": null, "e": 1787, "s": 1667, "text": "This commands prints the data of the configuration file. This file contains information about the user in the format. " }, { "code": null, "e": 1858, "s": 1787, "text": "username : x : user id : user group id : : /home/username : /bin/bash " }, { "code": null, "e": 1918, "s": 1858, "text": "Now we will go through the commands to modify information. " }, { "code": null, "e": 1969, "s": 1918, "text": "6. The command to change the user ID for a user. " }, { "code": null, "e": 1997, "s": 1969, "text": "usermod -u new_id username" }, { "code": null, "e": 2164, "s": 1997, "text": "This command can change the user ID of a user. The user with the given username will be assigned with the new ID given in the command and the old ID will be removed. " }, { "code": null, "e": 2201, "s": 2164, "text": "Example: sudo usermod -u 1982 test " }, { "code": null, "e": 2248, "s": 2201, "text": "7. Command to Modify the group ID of a user. " }, { "code": null, "e": 2282, "s": 2248, "text": "usermod -g new_group_id username" }, { "code": null, "e": 2518, "s": 2282, "text": "This command can change the group ID of a user and hence it can even be used to move a user to an already existing group. It will change the group ID of the user whose username is given and sets the group ID as the given new_group_id. " }, { "code": null, "e": 2555, "s": 2518, "text": "Example: sudo usermod -g 1005 test " }, { "code": null, "e": 2756, "s": 2555, "text": "8. You can change the user login name using usermod command. The below command is used to change the login name of the user. The old login name of the user is changed to the new login name provided. " }, { "code": null, "e": 2802, "s": 2756, "text": "sudo usermod -l new_login_name old_login_name" }, { "code": null, "e": 2848, "s": 2802, "text": "Example: sudo usermod -c John_Wick John_Doe " }, { "code": null, "e": 3048, "s": 2848, "text": "9. The command to change the home directory. The below command change the home directory of the user whose username is given and sets the new home directory as the directory whose path is provided. " }, { "code": null, "e": 3092, "s": 3048, "text": "usermod -d new_home_directory_path username" }, { "code": null, "e": 3138, "s": 3092, "text": "Example: usermod -d new_home_directory test " }, { "code": null, "e": 3439, "s": 3138, "text": "10. You can also delete a user name. The below command deletes the user whose username is provided. Make sure that the user is not part of a group. If the user is part of a group then it will not be deleted directly, hence we will have to first remove him from the group and then we can delete him. " }, { "code": null, "e": 3459, "s": 3439, "text": "userdel -r username" }, { "code": null, "e": 3496, "s": 3459, "text": "Example: sudo userdel -r new_geeks " }, { "code": null, "e": 3507, "s": 3498, "text": "gabaa406" }, { "code": null, "e": 3518, "s": 3507, "text": "Linux-Unix" } ]
How To Color a Scatter Plot by a Variable in Altair?
12 Nov, 2020 Altair is a simple and easy to use statistical visualization library for python. It provides many types of visualizations ranging from simple bar charts to compound visualizations like box plots. Scatter Plot is one of the most useful visualizations in the Altair library for bivariate analysis and finding relationships between two data columns in a data set. Sometimes a simple scatter plot is not enough to gauge the relationships between the variables in a data set. A better visualization would be a plot between two quantitative variables/data columns with respect to a third variable. This third variable is almost always a nominal or categorical variable. We can color the data points in the scatter plot using this third variable. Coloring the scatter plot will help us to recognize which data point corresponds to which category of the third variable. To color to scatter plot, the user simply has to map a nominal variable from the dataset to the color encoding. Let us understand the importance of scatter plot coloring using an example: The Iris dataset is one of the most popular datasets used in Data Science and is available in most dataset libraries. The dataset documents the iris flowers across three species. The data columns available in the dataset are sepalLength, sepalWidth, petalLength, petalWidth and species. First, we will visualize this dataset using a simple scatter plot and then see what can be achieved by coloring this scatter plot. To make a simple scatter plot, we use the iris dataset from the Vega_datasets library and pass it to the Chart object and use the mark_point() method. Then, we map the x and y-axis encoding to be sepalLength and petalLength variables. The simple scatter plot using iris without coloring: Python3 # Python3 program to illustrate# How to color a Scatter Plot# using altair # Importing altair and vega_datasets libraryimport altair as altfrom vega_datasets import data # Selecting the iris datasetiris = data.iris() # Making the Scatter Plotalt.Chart(iris).mark_point().encode( # Map the sepalLength to x-axis x = 'sepalLength', # Map the petalLength to y-axis y = 'petalLength',) Output: Scatter Plot for the Iris dataset without coloring As you can see, we can infer from this scatter plot that one group of points is linearly separable from the other group but we can’t see which data points correspond to which species and what types of relationships are present. To make this plot more informative, we will color this scatter plot using the species variable. Code: Python3 # Python3 program to illustrate# How to color a Scatter Plot# using altair # Importing altair and vega_datasets libraryimport altair as altfrom vega_datasets import data # Selecting the iris datasetiris = data.iris() # Making the Scatter Plotalt.Chart(iris).mark_point().encode( # Map the sepalLength to x-axis x = 'sepalLength', # Map the petalLength to y-axis y = 'petalLength', # Coloring the Scatter Plot # Map the species to color color = 'species') Output: Scatter Plot for the Iris dataset with coloring Altair automatically generates the legend specifying which color represents which category of the color variable. On seeing the colored data points, we can infer that the setosa species has long sepals but short petals. The versicolor species have almost equal and medium-sized petals and sepals whereas the virginica species also have almost equal but large-sized petals and sepals. As you can see, we can extract more information by coloring a scatter plot. If you don’t like the colors chosen by Altair for your scatter plot, you can customize the colors. The default colors can be changed using the scale argument of the Color class, By passing the Scale class to the scale argument. The available customizations are: Custom mapping of colors to discrete values: For custom mapping, we use domain and range parameters of the Scale and pass list for values and colors resp.Color Schemes: There are many color schemes given by the Vega project. If you like dark colors, you can use the ‘dark2’ scheme and if there are more than 10 categories you can use the ‘category20’ scheme. Custom mapping of colors to discrete values: For custom mapping, we use domain and range parameters of the Scale and pass list for values and colors resp. Color Schemes: There are many color schemes given by the Vega project. If you like dark colors, you can use the ‘dark2’ scheme and if there are more than 10 categories you can use the ‘category20’ scheme. Example 1: Custom mapping of colors to discrete values: Python3 # Python3 program to illustrate# How to do custom mapping# of colors to discrete values# for scatter plot coloring# using altair # Importing altair and vega_datasets libraryimport altair as altfrom vega_datasets import data # Selecting the cars datasetcars = data.cars() # Making two lists for# values and colors resp.dom = ['Europe', 'Japan', 'USA']rng = ['red', 'green', 'black'] # Making the Scatter Plotalt.Chart(cars).mark_point().encode( # Map Miles_per_Gallon to x-axis x='Miles_per_Gallon', # Map the Horsepower to y-axis y='Horsepower', # Coloring the Scatter Plot # using Origin variable and # custom colors color=alt.Color('Origin', scale=alt. Scale(domain=dom, range=rng))) Output: Scatter Plot for the cars dataset using custom mapping of colors and values Example 2(Color Schemes): Python3 # Python3 program to illustrate# How to select color schemes# for scatter plot coloring# using altair # Importing altair and vega_datasets libraryimport altair as altfrom vega_datasets import data # Selecting the cars datasetcars = data.cars() # Making the Scatter Plotalt.Chart(cars).mark_point().encode( # Map Miles_per_Gallon to x-axis x='Miles_per_Gallon', # Map the Horsepower to y-axis y='Horsepower', # Coloring the Scatter Plot # using Origin variable and # color scheme color = alt.Color('Origin', scale=alt. Scale(scheme = 'dark2'))) Output: Scatter Plot for the cars dataset using color scheme Python-Altair Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n12 Nov, 2020" }, { "code": null, "e": 389, "s": 28, "text": "Altair is a simple and easy to use statistical visualization library for python. It provides many types of visualizations ranging from simple bar charts to compound visualizations like box plots. Scatter Plot is one of the most useful visualizations in the Altair library for bivariate analysis and finding relationships between two data columns in a data set." }, { "code": null, "e": 890, "s": 389, "text": "Sometimes a simple scatter plot is not enough to gauge the relationships between the variables in a data set. A better visualization would be a plot between two quantitative variables/data columns with respect to a third variable. This third variable is almost always a nominal or categorical variable. We can color the data points in the scatter plot using this third variable. Coloring the scatter plot will help us to recognize which data point corresponds to which category of the third variable." }, { "code": null, "e": 1002, "s": 890, "text": "To color to scatter plot, the user simply has to map a nominal variable from the dataset to the color encoding." }, { "code": null, "e": 1078, "s": 1002, "text": "Let us understand the importance of scatter plot coloring using an example:" }, { "code": null, "e": 1496, "s": 1078, "text": "The Iris dataset is one of the most popular datasets used in Data Science and is available in most dataset libraries. The dataset documents the iris flowers across three species. The data columns available in the dataset are sepalLength, sepalWidth, petalLength, petalWidth and species. First, we will visualize this dataset using a simple scatter plot and then see what can be achieved by coloring this scatter plot." }, { "code": null, "e": 1731, "s": 1496, "text": "To make a simple scatter plot, we use the iris dataset from the Vega_datasets library and pass it to the Chart object and use the mark_point() method. Then, we map the x and y-axis encoding to be sepalLength and petalLength variables." }, { "code": null, "e": 1784, "s": 1731, "text": "The simple scatter plot using iris without coloring:" }, { "code": null, "e": 1792, "s": 1784, "text": "Python3" }, { "code": "# Python3 program to illustrate# How to color a Scatter Plot# using altair # Importing altair and vega_datasets libraryimport altair as altfrom vega_datasets import data # Selecting the iris datasetiris = data.iris() # Making the Scatter Plotalt.Chart(iris).mark_point().encode( # Map the sepalLength to x-axis x = 'sepalLength', # Map the petalLength to y-axis y = 'petalLength',)", "e": 2185, "s": 1792, "text": null }, { "code": null, "e": 2193, "s": 2185, "text": "Output:" }, { "code": null, "e": 2245, "s": 2193, "text": "Scatter Plot for the Iris dataset without coloring" }, { "code": null, "e": 2569, "s": 2245, "text": "As you can see, we can infer from this scatter plot that one group of points is linearly separable from the other group but we can’t see which data points correspond to which species and what types of relationships are present. To make this plot more informative, we will color this scatter plot using the species variable." }, { "code": null, "e": 2575, "s": 2569, "text": "Code:" }, { "code": null, "e": 2583, "s": 2575, "text": "Python3" }, { "code": "# Python3 program to illustrate# How to color a Scatter Plot# using altair # Importing altair and vega_datasets libraryimport altair as altfrom vega_datasets import data # Selecting the iris datasetiris = data.iris() # Making the Scatter Plotalt.Chart(iris).mark_point().encode( # Map the sepalLength to x-axis x = 'sepalLength', # Map the petalLength to y-axis y = 'petalLength', # Coloring the Scatter Plot # Map the species to color color = 'species')", "e": 3054, "s": 2583, "text": null }, { "code": null, "e": 3062, "s": 3054, "text": "Output:" }, { "code": null, "e": 3111, "s": 3062, "text": "Scatter Plot for the Iris dataset with coloring" }, { "code": null, "e": 3495, "s": 3111, "text": "Altair automatically generates the legend specifying which color represents which category of the color variable. On seeing the colored data points, we can infer that the setosa species has long sepals but short petals. The versicolor species have almost equal and medium-sized petals and sepals whereas the virginica species also have almost equal but large-sized petals and sepals." }, { "code": null, "e": 3571, "s": 3495, "text": "As you can see, we can extract more information by coloring a scatter plot." }, { "code": null, "e": 3833, "s": 3571, "text": "If you don’t like the colors chosen by Altair for your scatter plot, you can customize the colors. The default colors can be changed using the scale argument of the Color class, By passing the Scale class to the scale argument. The available customizations are:" }, { "code": null, "e": 4192, "s": 3833, "text": "Custom mapping of colors to discrete values: For custom mapping, we use domain and range parameters of the Scale and pass list for values and colors resp.Color Schemes: There are many color schemes given by the Vega project. If you like dark colors, you can use the ‘dark2’ scheme and if there are more than 10 categories you can use the ‘category20’ scheme." }, { "code": null, "e": 4347, "s": 4192, "text": "Custom mapping of colors to discrete values: For custom mapping, we use domain and range parameters of the Scale and pass list for values and colors resp." }, { "code": null, "e": 4552, "s": 4347, "text": "Color Schemes: There are many color schemes given by the Vega project. If you like dark colors, you can use the ‘dark2’ scheme and if there are more than 10 categories you can use the ‘category20’ scheme." }, { "code": null, "e": 4608, "s": 4552, "text": "Example 1: Custom mapping of colors to discrete values:" }, { "code": null, "e": 4616, "s": 4608, "text": "Python3" }, { "code": "# Python3 program to illustrate# How to do custom mapping# of colors to discrete values# for scatter plot coloring# using altair # Importing altair and vega_datasets libraryimport altair as altfrom vega_datasets import data # Selecting the cars datasetcars = data.cars() # Making two lists for# values and colors resp.dom = ['Europe', 'Japan', 'USA']rng = ['red', 'green', 'black'] # Making the Scatter Plotalt.Chart(cars).mark_point().encode( # Map Miles_per_Gallon to x-axis x='Miles_per_Gallon', # Map the Horsepower to y-axis y='Horsepower', # Coloring the Scatter Plot # using Origin variable and # custom colors color=alt.Color('Origin', scale=alt. Scale(domain=dom, range=rng)))", "e": 5365, "s": 4616, "text": null }, { "code": null, "e": 5373, "s": 5365, "text": "Output:" }, { "code": null, "e": 5449, "s": 5373, "text": "Scatter Plot for the cars dataset using custom mapping of colors and values" }, { "code": null, "e": 5475, "s": 5449, "text": "Example 2(Color Schemes):" }, { "code": null, "e": 5483, "s": 5475, "text": "Python3" }, { "code": "# Python3 program to illustrate# How to select color schemes# for scatter plot coloring# using altair # Importing altair and vega_datasets libraryimport altair as altfrom vega_datasets import data # Selecting the cars datasetcars = data.cars() # Making the Scatter Plotalt.Chart(cars).mark_point().encode( # Map Miles_per_Gallon to x-axis x='Miles_per_Gallon', # Map the Horsepower to y-axis y='Horsepower', # Coloring the Scatter Plot # using Origin variable and # color scheme color = alt.Color('Origin', scale=alt. Scale(scheme = 'dark2')))", "e": 6091, "s": 5483, "text": null }, { "code": null, "e": 6099, "s": 6091, "text": "Output:" }, { "code": null, "e": 6153, "s": 6099, "text": "Scatter Plot for the cars dataset using color scheme" }, { "code": null, "e": 6167, "s": 6153, "text": "Python-Altair" }, { "code": null, "e": 6174, "s": 6167, "text": "Python" } ]
Python OpenCV – getRotationMatrix2D() Function
10 Oct, 2021 cv2.getRotationMatrix2D() function is used to make the transformation matrix M which will be used for rotating a image. Syntax: cv2.getRotationMatrix2D(center, angle, scale) Parameters: center: Center of rotation angle(θ): Angle of Rotation. Angle is positive for anti-clockwise and negative for clockwise. scale: scaling factor which scales the image Return: 2×3 Rotation Matrix M M = where, This is a type of affine transformation. An affine transformation is transformation which preserves lines and parallelism. These transformation matrix are taken by warpaffine() function as parameter and the rotated image will be returned. Image Used: Example 1: Python3 import cv2 # Reading the imageimage = cv2.imread('image.jpeg') # Extracting height and width from # image shapeheight, width = image.shape[:2] # get the center coordinates of the# image to create the 2D rotation# matrixcenter = (width/2, height/2) # using cv2.getRotationMatrix2D() # to get the rotation matrixrotate_matrix = cv2.getRotationMatrix2D(center=center, angle=90, scale=1) # rotate the image using cv2.warpAffine # 90 degree anticlockwiserotated_image = cv2.warpAffine( src=image, M=rotate_matrix, dsize=(width, height)) cv2.imshow("rotated image:", rotated_image)cv2.imwrite('rotated_image.jpg', rotated_image) Output- Example 2: Python3 import cv2 # Reading the imageimage = cv2.imread('image.jpeg') # Extracting height and width from # image shapeheight, width = image.shape[:2] # get the center coordinates of the # image to create the 2D rotation matrixcenter = (width/2, height/2) # using cv2.getRotationMatrix2D() to get# the rotation matrixrotate_matrix = cv2.getRotationMatrix2D(center=center, angle=-90, scale=1) # rotate the image using cv2.warpAffine 90 # degree clockwiserotated_image = cv2.warpAffine( src=image, M=rotate_matrix, dsize=(width, height)) cv2.imshow("rotated image:",rotated_image)cv2.imwrite('rotated_image.jpg', rotated_image) Output- Python3 import cv2 # Reading the imageimage = cv2.imread('image.jpeg') # Extracting height and width from image shapeheight, width = image.shape[:2] # get the center coordinates of the image to # create the 2D rotation matrixcenter = (width/2, height/2) # using cv2.getRotationMatrix2D() to get # the rotation matrixrotate_matrix = cv2.getRotationMatrix2D(center=center, angle=180, scale=1) # rotate the image using cv2.warpAffine 180 # degree anticlockwiserotated_image = cv2.warpAffine( src=image, M=rotate_matrix, dsize=(width, height)) cv2.imshow("rotated image:", rotated_image)cv2.imwrite('rotated_image.jpg', rotated_image) Output- Example 4: Python3 import cv2 # Reading the imageimage = cv2.imread('image.jpeg') # Extracting height and width from image shapeheight, width = image.shape[:2] # get the center coordinates of the image to# create the 2D rotation matrixcenter = (width/2, height/2) # using cv2.getRotationMatrix2D() to get the# rotation matrixrotate_matrix = cv2.getRotationMatrix2D(center=center, angle=-180, scale=1) # rotate the image using cv2.warpAffine 180# degree clockwiserotated_image = cv2.warpAffine( src=image, M=rotate_matrix, dsize=(width, height)) cv2.imshow("rotated image:", rotated_image)cv2.imwrite('rotated_image.jpg', rotated_image) Output – Picked Python-OpenCV Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Python OOPs Concepts Iterate over a list in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n10 Oct, 2021" }, { "code": null, "e": 148, "s": 28, "text": "cv2.getRotationMatrix2D() function is used to make the transformation matrix M which will be used for rotating a image." }, { "code": null, "e": 157, "s": 148, "text": "Syntax: " }, { "code": null, "e": 203, "s": 157, "text": "cv2.getRotationMatrix2D(center, angle, scale)" }, { "code": null, "e": 216, "s": 203, "text": "Parameters: " }, { "code": null, "e": 243, "s": 216, "text": "center: Center of rotation" }, { "code": null, "e": 337, "s": 243, "text": "angle(θ): Angle of Rotation. Angle is positive for anti-clockwise and negative for clockwise." }, { "code": null, "e": 382, "s": 337, "text": "scale: scaling factor which scales the image" }, { "code": null, "e": 412, "s": 382, "text": "Return: 2×3 Rotation Matrix M" }, { "code": null, "e": 417, "s": 412, "text": "M = " }, { "code": null, "e": 424, "s": 417, "text": "where," }, { "code": null, "e": 663, "s": 424, "text": "This is a type of affine transformation. An affine transformation is transformation which preserves lines and parallelism. These transformation matrix are taken by warpaffine() function as parameter and the rotated image will be returned." }, { "code": null, "e": 675, "s": 663, "text": "Image Used:" }, { "code": null, "e": 686, "s": 675, "text": "Example 1:" }, { "code": null, "e": 694, "s": 686, "text": "Python3" }, { "code": "import cv2 # Reading the imageimage = cv2.imread('image.jpeg') # Extracting height and width from # image shapeheight, width = image.shape[:2] # get the center coordinates of the# image to create the 2D rotation# matrixcenter = (width/2, height/2) # using cv2.getRotationMatrix2D() # to get the rotation matrixrotate_matrix = cv2.getRotationMatrix2D(center=center, angle=90, scale=1) # rotate the image using cv2.warpAffine # 90 degree anticlockwiserotated_image = cv2.warpAffine( src=image, M=rotate_matrix, dsize=(width, height)) cv2.imshow(\"rotated image:\", rotated_image)cv2.imwrite('rotated_image.jpg', rotated_image)", "e": 1326, "s": 694, "text": null }, { "code": null, "e": 1334, "s": 1326, "text": "Output-" }, { "code": null, "e": 1345, "s": 1334, "text": "Example 2:" }, { "code": null, "e": 1353, "s": 1345, "text": "Python3" }, { "code": "import cv2 # Reading the imageimage = cv2.imread('image.jpeg') # Extracting height and width from # image shapeheight, width = image.shape[:2] # get the center coordinates of the # image to create the 2D rotation matrixcenter = (width/2, height/2) # using cv2.getRotationMatrix2D() to get# the rotation matrixrotate_matrix = cv2.getRotationMatrix2D(center=center, angle=-90, scale=1) # rotate the image using cv2.warpAffine 90 # degree clockwiserotated_image = cv2.warpAffine( src=image, M=rotate_matrix, dsize=(width, height)) cv2.imshow(\"rotated image:\",rotated_image)cv2.imwrite('rotated_image.jpg', rotated_image)", "e": 1980, "s": 1353, "text": null }, { "code": null, "e": 1988, "s": 1980, "text": "Output-" }, { "code": null, "e": 1996, "s": 1988, "text": "Python3" }, { "code": "import cv2 # Reading the imageimage = cv2.imread('image.jpeg') # Extracting height and width from image shapeheight, width = image.shape[:2] # get the center coordinates of the image to # create the 2D rotation matrixcenter = (width/2, height/2) # using cv2.getRotationMatrix2D() to get # the rotation matrixrotate_matrix = cv2.getRotationMatrix2D(center=center, angle=180, scale=1) # rotate the image using cv2.warpAffine 180 # degree anticlockwiserotated_image = cv2.warpAffine( src=image, M=rotate_matrix, dsize=(width, height)) cv2.imshow(\"rotated image:\", rotated_image)cv2.imwrite('rotated_image.jpg', rotated_image)", "e": 2628, "s": 1996, "text": null }, { "code": null, "e": 2636, "s": 2628, "text": "Output-" }, { "code": null, "e": 2647, "s": 2636, "text": "Example 4:" }, { "code": null, "e": 2655, "s": 2647, "text": "Python3" }, { "code": "import cv2 # Reading the imageimage = cv2.imread('image.jpeg') # Extracting height and width from image shapeheight, width = image.shape[:2] # get the center coordinates of the image to# create the 2D rotation matrixcenter = (width/2, height/2) # using cv2.getRotationMatrix2D() to get the# rotation matrixrotate_matrix = cv2.getRotationMatrix2D(center=center, angle=-180, scale=1) # rotate the image using cv2.warpAffine 180# degree clockwiserotated_image = cv2.warpAffine( src=image, M=rotate_matrix, dsize=(width, height)) cv2.imshow(\"rotated image:\", rotated_image)cv2.imwrite('rotated_image.jpg', rotated_image)", "e": 3281, "s": 2655, "text": null }, { "code": null, "e": 3291, "s": 3281, "text": "Output – " }, { "code": null, "e": 3298, "s": 3291, "text": "Picked" }, { "code": null, "e": 3312, "s": 3298, "text": "Python-OpenCV" }, { "code": null, "e": 3319, "s": 3312, "text": "Python" }, { "code": null, "e": 3417, "s": 3319, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3435, "s": 3417, "text": "Python Dictionary" }, { "code": null, "e": 3477, "s": 3435, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 3499, "s": 3477, "text": "Enumerate() in Python" }, { "code": null, "e": 3534, "s": 3499, "text": "Read a file line by line in Python" }, { "code": null, "e": 3560, "s": 3534, "text": "Python String | replace()" }, { "code": null, "e": 3592, "s": 3560, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3621, "s": 3592, "text": "*args and **kwargs in Python" }, { "code": null, "e": 3648, "s": 3621, "text": "Python Classes and Objects" }, { "code": null, "e": 3669, "s": 3648, "text": "Python OOPs Concepts" } ]
Debugging in Python with Pdb
28 Feb, 2022 The PDB module in Python gives us gigantic highlights for compelling debugging of Python code. This incorporates: Pausing of the program Looking at the execution of each line of code Checking the values of variables This module is already installed with installing of python. So, we only need to import it into our code to use its functionality. Before that we must know some concepts which are mentioned below: To import we simply use import pdb in our code.For debugging, we will use pdb.set_trace() method. Now, in Python 3.7 breakpoint() method is also available for this.We run this on Python idle terminal (you can use any ide terminal to run). To import we simply use import pdb in our code. For debugging, we will use pdb.set_trace() method. Now, in Python 3.7 breakpoint() method is also available for this. We run this on Python idle terminal (you can use any ide terminal to run). Let’s begin with a simple example consisting of some lines of code. Example: Python3 # importing pdbimport pdb # make a simple function to debugdef fxn(n): for i in range(n): print("Hello! ", i+1) # starting point to debugpdb.set_trace()fxn(5) Output: Here, we can see that when the function call is done then pdb executes and ask for the next command. We can use some commands here like c -> continue execution q -> quit the debugger/execution n -> step to next line within the same function s -> step to next line in this function or a called function To know more about different commands you can type help and get the required information. Now, we will execute our program further with the help of the n command. In a similar way, we can use the breakpoint() method (which doesn’t need to import pdb). Python3 # a simple functiondef fxn(n): for i in range(n): print("Hello! ", i+1) # using breakpointbreakpoint()fxn(5) Output: 1. Printing Variables or expressions When utilizing the print order p, you’re passing an articulation to be assessed by Python. On the off chance that you pass a variable name, pdb prints its present worth. Notwithstanding, you can do considerably more to examine the condition of your running application. An application of PDB debugging in the recursion to check variables In this example, we will define a recursive function with pdb trace and check the values of variables at each recursive call. To the print the value of variable, we will use a simple print keyword with the variable name. Python3 # importing pdbimport pdb # define recursive functiondef rec_fxn(r): if r > 0: # set trace pdb.set_trace() rec_fxn(r//2) else: print("recursion stops") return # set trace at startpdb.set_trace()rec_fxn(5) Output: An Example to check expressions This example is similar to the above example, that prints the values of expressions after their evaluation. Python3 # importing pdbimport pdb # simple functiondef fxn(n): l=[] for i in range(n): l.append(i) # set trace pdb.set_trace() return fxn(5) Output: 2. Moving in code by steps This is the most important feature provided by pdb. The two main commands are used for this which are given below: n -> step to next line within the same function s -> step to next line in this function or a called function Let’s understand the working of these with the help of an example. Python3 # importing pdbimport pdb # simple functiondef fxn(n): l = [] for i in range(n): l.append(i) return # set tracepdb.set_trace()fxn(5) Output Using n: Output Using s: 3. Using Breakpoints This feature helps us to create breakpoints dynamically at a particular line in the source code. Here, in this example, we are creating breakpoint using command b which given below: b(reak) [ ([filename:]lineno | function) [, condition] ] Without argument, list all breaks. With a line number argument, set a break at this line in the current file. With a function name, set a break at the first executable line of that function. If a second argument is present, it is a string specifying an expression that must evaluate to true before the breakpoint is honored. The line number may be prefixed with a filename and a colon, to specify a breakpoint in another file (probably one that hasn’t been loaded yet). The file is searched for on sys.path; the .py suffix may be omitted. Python3 # importing pdbimport pdb # simple functiondef fxn(n): l = [] for i in range(n): l.append(i) print(l) return # set tracepdb.set_trace()fxn(5) Output: 4. Execute code until the specified line Use unt to proceed with execution like c, however, stop at the following line more noteworthy than the current line. Now and then unt is more helpful and faster to utilize and is actually what you need. unt(il) [lineno] Without argument, continue execution until the line with a number greater than the current one is reached. With a line number, continue execution until a line with a number greater or equal to that is reached. In both cases, also stop when the current frame returns. Python3 # importing pdbimport pdb # simple functiondef fxn(n): # set trace pdb.set_trace() l = [] for i in range(n): l.append(i) print(l) return fxn(5) Output: 5. List the code Listing Source code is another feature that can be used to track the code with a line number as a list. For this ll command is used. longlist | ll -> List the whole source code for the current function or frame. Let’s understand the working of longlist with the help of an example. Python3 # importing pdbimport pdb # simple functiondef fxn(n): l=[] for i in range(n): l.append(i) return # set tracepdb.set_trace()fxn(5) Output: 6. Displaying Expressions Like printing articulations with p and pp, you can utilize the order show [expression] to advise pdb to consequently show the estimation of an articulation, on the off chance that it changed, when execution stops. Utilize the order undisplay [expression] to clear a showcase articulation. display [expression] Display the value of the expression if it changed, each time execution stops in the current frame. Without expression, list all display expressions for the current frame. undisplay [expression] Do not display the expression any more in the current frame. Without expression, clear all display expressions for the current frame. Python3 # importing pdbimport pdb # simple functiondef fxn(n): l = [] for i in range(n): l.append(i) # set trace pdb.set_trace() print(l) return fxn(5) Output: 7. Frames up-down Here, we can play with each trace as a frame, and we can also move from one frame to another. w(here) Print a stack trace, with the most recent frame at the bottom. An arrow indicates the “current frame”, which determines the context of most commands. ‘bt’ is an alias for this command. u(p) [count] Move the current frame count (default one) levels up in the stack trace (to an older frame). d(own) [count] Move the current frame count (default one) levels down in the stack trace (to a newer frame). Python3 # importing pdbimport pdb # simple functiondef fxn(i): print(i) return # set tracepdb.set_trace()for i in range(5): fxn(i) Output: germanshephered48 python-modules Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Python | os.path.join() method How to drop one or multiple columns in Pandas Dataframe Introduction To PYTHON How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | datetime.timedelta() function Python | Get unique values from a list
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Feb, 2022" }, { "code": null, "e": 144, "s": 28, "text": "The PDB module in Python gives us gigantic highlights for compelling debugging of Python code. This incorporates: " }, { "code": null, "e": 167, "s": 144, "text": "Pausing of the program" }, { "code": null, "e": 213, "s": 167, "text": "Looking at the execution of each line of code" }, { "code": null, "e": 246, "s": 213, "text": "Checking the values of variables" }, { "code": null, "e": 442, "s": 246, "text": "This module is already installed with installing of python. So, we only need to import it into our code to use its functionality. Before that we must know some concepts which are mentioned below:" }, { "code": null, "e": 681, "s": 442, "text": "To import we simply use import pdb in our code.For debugging, we will use pdb.set_trace() method. Now, in Python 3.7 breakpoint() method is also available for this.We run this on Python idle terminal (you can use any ide terminal to run)." }, { "code": null, "e": 729, "s": 681, "text": "To import we simply use import pdb in our code." }, { "code": null, "e": 847, "s": 729, "text": "For debugging, we will use pdb.set_trace() method. Now, in Python 3.7 breakpoint() method is also available for this." }, { "code": null, "e": 922, "s": 847, "text": "We run this on Python idle terminal (you can use any ide terminal to run)." }, { "code": null, "e": 991, "s": 922, "text": "Let’s begin with a simple example consisting of some lines of code. " }, { "code": null, "e": 1000, "s": 991, "text": "Example:" }, { "code": null, "e": 1008, "s": 1000, "text": "Python3" }, { "code": "# importing pdbimport pdb # make a simple function to debugdef fxn(n): for i in range(n): print(\"Hello! \", i+1) # starting point to debugpdb.set_trace()fxn(5)", "e": 1181, "s": 1008, "text": null }, { "code": null, "e": 1189, "s": 1181, "text": "Output:" }, { "code": null, "e": 1326, "s": 1189, "text": "Here, we can see that when the function call is done then pdb executes and ask for the next command. We can use some commands here like " }, { "code": null, "e": 1350, "s": 1326, "text": "c -> continue execution" }, { "code": null, "e": 1383, "s": 1350, "text": "q -> quit the debugger/execution" }, { "code": null, "e": 1431, "s": 1383, "text": "n -> step to next line within the same function" }, { "code": null, "e": 1492, "s": 1431, "text": "s -> step to next line in this function or a called function" }, { "code": null, "e": 1582, "s": 1492, "text": "To know more about different commands you can type help and get the required information." }, { "code": null, "e": 1655, "s": 1582, "text": "Now, we will execute our program further with the help of the n command." }, { "code": null, "e": 1744, "s": 1655, "text": "In a similar way, we can use the breakpoint() method (which doesn’t need to import pdb)." }, { "code": null, "e": 1752, "s": 1744, "text": "Python3" }, { "code": "# a simple functiondef fxn(n): for i in range(n): print(\"Hello! \", i+1) # using breakpointbreakpoint()fxn(5)", "e": 1874, "s": 1752, "text": null }, { "code": null, "e": 1882, "s": 1874, "text": "Output:" }, { "code": null, "e": 1919, "s": 1882, "text": "1. Printing Variables or expressions" }, { "code": null, "e": 2189, "s": 1919, "text": "When utilizing the print order p, you’re passing an articulation to be assessed by Python. On the off chance that you pass a variable name, pdb prints its present worth. Notwithstanding, you can do considerably more to examine the condition of your running application." }, { "code": null, "e": 2257, "s": 2189, "text": "An application of PDB debugging in the recursion to check variables" }, { "code": null, "e": 2478, "s": 2257, "text": "In this example, we will define a recursive function with pdb trace and check the values of variables at each recursive call. To the print the value of variable, we will use a simple print keyword with the variable name." }, { "code": null, "e": 2486, "s": 2478, "text": "Python3" }, { "code": "# importing pdbimport pdb # define recursive functiondef rec_fxn(r): if r > 0: # set trace pdb.set_trace() rec_fxn(r//2) else: print(\"recursion stops\") return # set trace at startpdb.set_trace()rec_fxn(5)", "e": 2732, "s": 2486, "text": null }, { "code": null, "e": 2740, "s": 2732, "text": "Output:" }, { "code": null, "e": 2772, "s": 2740, "text": "An Example to check expressions" }, { "code": null, "e": 2880, "s": 2772, "text": "This example is similar to the above example, that prints the values of expressions after their evaluation." }, { "code": null, "e": 2888, "s": 2880, "text": "Python3" }, { "code": "# importing pdbimport pdb # simple functiondef fxn(n): l=[] for i in range(n): l.append(i) # set trace pdb.set_trace() return fxn(5)", "e": 3047, "s": 2888, "text": null }, { "code": null, "e": 3055, "s": 3047, "text": "Output:" }, { "code": null, "e": 3082, "s": 3055, "text": "2. Moving in code by steps" }, { "code": null, "e": 3197, "s": 3082, "text": "This is the most important feature provided by pdb. The two main commands are used for this which are given below:" }, { "code": null, "e": 3245, "s": 3197, "text": "n -> step to next line within the same function" }, { "code": null, "e": 3306, "s": 3245, "text": "s -> step to next line in this function or a called function" }, { "code": null, "e": 3373, "s": 3306, "text": "Let’s understand the working of these with the help of an example." }, { "code": null, "e": 3381, "s": 3373, "text": "Python3" }, { "code": "# importing pdbimport pdb # simple functiondef fxn(n): l = [] for i in range(n): l.append(i) return # set tracepdb.set_trace()fxn(5)", "e": 3534, "s": 3381, "text": null }, { "code": null, "e": 3550, "s": 3534, "text": "Output Using n:" }, { "code": null, "e": 3566, "s": 3550, "text": "Output Using s:" }, { "code": null, "e": 3587, "s": 3566, "text": "3. Using Breakpoints" }, { "code": null, "e": 3769, "s": 3587, "text": "This feature helps us to create breakpoints dynamically at a particular line in the source code. Here, in this example, we are creating breakpoint using command b which given below:" }, { "code": null, "e": 3869, "s": 3769, "text": "b(reak) [ ([filename:]lineno | function) [, condition] ]\n Without argument, list all breaks." }, { "code": null, "e": 4161, "s": 3869, "text": "With a line number argument, set a break at this line in the current file. With a function name, set a break at the first executable line of that function. If a second argument is present, it is a string specifying an expression that must evaluate to true before the breakpoint is honored." }, { "code": null, "e": 4376, "s": 4161, "text": "The line number may be prefixed with a filename and a colon, to specify a breakpoint in another file (probably one that hasn’t been loaded yet). The file is searched for on sys.path; the .py suffix may be omitted." }, { "code": null, "e": 4384, "s": 4376, "text": "Python3" }, { "code": "# importing pdbimport pdb # simple functiondef fxn(n): l = [] for i in range(n): l.append(i) print(l) return # set tracepdb.set_trace()fxn(5)", "e": 4555, "s": 4384, "text": null }, { "code": null, "e": 4563, "s": 4555, "text": "Output:" }, { "code": null, "e": 4604, "s": 4563, "text": "4. Execute code until the specified line" }, { "code": null, "e": 4807, "s": 4604, "text": "Use unt to proceed with execution like c, however, stop at the following line more noteworthy than the current line. Now and then unt is more helpful and faster to utilize and is actually what you need." }, { "code": null, "e": 4824, "s": 4807, "text": "unt(il) [lineno]" }, { "code": null, "e": 5093, "s": 4824, "text": "Without argument, continue execution until the line with a number greater than the current one is reached. With a line number, continue execution until a line with a number greater or equal to that is reached. In both cases, also stop when the current frame returns." }, { "code": null, "e": 5101, "s": 5093, "text": "Python3" }, { "code": "# importing pdbimport pdb # simple functiondef fxn(n): # set trace pdb.set_trace() l = [] for i in range(n): l.append(i) print(l) return fxn(5)", "e": 5284, "s": 5101, "text": null }, { "code": null, "e": 5292, "s": 5284, "text": "Output:" }, { "code": null, "e": 5309, "s": 5292, "text": "5. List the code" }, { "code": null, "e": 5442, "s": 5309, "text": "Listing Source code is another feature that can be used to track the code with a line number as a list. For this ll command is used." }, { "code": null, "e": 5521, "s": 5442, "text": "longlist | ll -> List the whole source code for the current function or frame." }, { "code": null, "e": 5591, "s": 5521, "text": "Let’s understand the working of longlist with the help of an example." }, { "code": null, "e": 5599, "s": 5591, "text": "Python3" }, { "code": "# importing pdbimport pdb # simple functiondef fxn(n): l=[] for i in range(n): l.append(i) return # set tracepdb.set_trace()fxn(5)", "e": 5750, "s": 5599, "text": null }, { "code": null, "e": 5758, "s": 5750, "text": "Output:" }, { "code": null, "e": 5784, "s": 5758, "text": "6. Displaying Expressions" }, { "code": null, "e": 6073, "s": 5784, "text": "Like printing articulations with p and pp, you can utilize the order show [expression] to advise pdb to consequently show the estimation of an articulation, on the off chance that it changed, when execution stops. Utilize the order undisplay [expression] to clear a showcase articulation." }, { "code": null, "e": 6094, "s": 6073, "text": "display [expression]" }, { "code": null, "e": 6265, "s": 6094, "text": "Display the value of the expression if it changed, each time execution stops in the current frame. Without expression, list all display expressions for the current frame." }, { "code": null, "e": 6288, "s": 6265, "text": "undisplay [expression]" }, { "code": null, "e": 6422, "s": 6288, "text": "Do not display the expression any more in the current frame. Without expression, clear all display expressions for the current frame." }, { "code": null, "e": 6430, "s": 6422, "text": "Python3" }, { "code": "# importing pdbimport pdb # simple functiondef fxn(n): l = [] for i in range(n): l.append(i) # set trace pdb.set_trace() print(l) return fxn(5)", "e": 6615, "s": 6430, "text": null }, { "code": null, "e": 6623, "s": 6615, "text": "Output:" }, { "code": null, "e": 6641, "s": 6623, "text": "7. Frames up-down" }, { "code": null, "e": 6735, "s": 6641, "text": "Here, we can play with each trace as a frame, and we can also move from one frame to another." }, { "code": null, "e": 6743, "s": 6735, "text": "w(here)" }, { "code": null, "e": 6929, "s": 6743, "text": "Print a stack trace, with the most recent frame at the bottom. An arrow indicates the “current frame”, which determines the context of most commands. ‘bt’ is an alias for this command." }, { "code": null, "e": 6942, "s": 6929, "text": "u(p) [count]" }, { "code": null, "e": 7035, "s": 6942, "text": "Move the current frame count (default one) levels up in the stack trace (to an older frame)." }, { "code": null, "e": 7050, "s": 7035, "text": "d(own) [count]" }, { "code": null, "e": 7144, "s": 7050, "text": "Move the current frame count (default one) levels down in the stack trace (to a newer frame)." }, { "code": null, "e": 7152, "s": 7144, "text": "Python3" }, { "code": "# importing pdbimport pdb # simple functiondef fxn(i): print(i) return # set tracepdb.set_trace()for i in range(5): fxn(i)", "e": 7286, "s": 7152, "text": null }, { "code": null, "e": 7294, "s": 7286, "text": "Output:" }, { "code": null, "e": 7312, "s": 7294, "text": "germanshephered48" }, { "code": null, "e": 7327, "s": 7312, "text": "python-modules" }, { "code": null, "e": 7334, "s": 7327, "text": "Python" }, { "code": null, "e": 7432, "s": 7334, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7464, "s": 7432, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 7491, "s": 7464, "text": "Python Classes and Objects" }, { "code": null, "e": 7512, "s": 7491, "text": "Python OOPs Concepts" }, { "code": null, "e": 7543, "s": 7512, "text": "Python | os.path.join() method" }, { "code": null, "e": 7599, "s": 7543, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 7622, "s": 7599, "text": "Introduction To PYTHON" }, { "code": null, "e": 7664, "s": 7622, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 7706, "s": 7664, "text": "Check if element exists in list in Python" }, { "code": null, "e": 7745, "s": 7706, "text": "Python | datetime.timedelta() function" } ]
Mongoose Query() Function
10 Sep, 2020 The Query constructor is used for building the queries. So the user does not need to instantiate a Query directly. The `query` is an instance of `Query`. Syntax: Query() Parameters: This function has optional parameters like model, condition, collection and options. Return Value: This function returns Query object. Installation of mongoose module: You can visit the link to Install mongoose module. You can install this package by using this command. npm install mongoose After installing the mongoose module, you can check your mongoose version in command prompt using the command. npm version mongoose After that, you can just create a folder and add a file for example, index.js as shown below. Example 1: Filename: index.js javascript const express = require('express');const mongoose = require('mongoose');const app = express() // Database connectionmongoose.connect('mongodb://127.0.0.1:27017/geeksforgeeks', { useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true}); // User modelconst User = mongoose.model('User', { name: { type: String }, age: { type: Number }}); const query = new mongoose.Query();console.log(query); app.listen(3000, function(error ){ if(error) console.log(error) console.log("Server listening on PORT 3000")}) Steps to run the program: The project structure will look like this: Run index.js file using below command: node index.js Output: Query { _mongooseOptions: {}, _transforms: [], _hooks: Kareem { _pres: Map {}, _posts: Map {} }, _executionCount: 0, op: undefined, options: {}, _conditions: {}, _fields: undefined, _update: undefined, _path: undefined, _distinct: undefined, _collection: undefined, _traceFunction: undefined, '$useProjection': true } Server listening on PORT 3000 Example 2: Filename: index.js javascript const mongoose = require('mongoose'); // Database connectionmongoose.connect('mongodb://127.0.0.1:27017/geeksforgeeks', { useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true}); // User modelconst User = mongoose.model('User', { name: { type: String }, age: { type: Number }}); const query = new mongoose.Query();query.collection(User.collection);console.log(query); Steps to run the program: The project structure will look like this: Run index.js file using below command: node index.js Output: Query { _mongooseOptions: {}, _transforms: [], _hooks: Kareem { _pres: Map {}, _posts: Map {} }, _executionCount: 0, op: undefined, options: {}, _conditions: {}, _fields: undefined, _update: undefined, _path: undefined, _distinct: undefined, _collection: NodeCollection { collection: NativeCollection { collection: null, Promise: [Function: Promise], _closed: false, opts: [Object], name: 'users', collectionName: 'users', conn: [NativeConnection], queue: [], buffer: true, emitter: [EventEmitter] }, collectionName: 'users' }, _traceFunction: undefined, '$useProjection': true } Reference: https://mongoosejs.com/docs/api/query.html Mongoose Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between promise and async await in Node.js JWT Authentication with Node.js Installation of Node.js on Windows Node.js forEach() function How to use an ES6 import in Node.js? 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 ? Differences between Functional Components and Class Components in React
[ { "code": null, "e": 28, "s": 0, "text": "\n10 Sep, 2020" }, { "code": null, "e": 183, "s": 28, "text": "The Query constructor is used for building the queries. So the user does not need to instantiate a Query directly. The `query` is an instance of `Query`. " }, { "code": null, "e": 192, "s": 183, "text": "Syntax: " }, { "code": null, "e": 201, "s": 192, "text": "Query()\n" }, { "code": null, "e": 299, "s": 201, "text": "Parameters: This function has optional parameters like model, condition, collection and options. " }, { "code": null, "e": 350, "s": 299, "text": "Return Value: This function returns Query object. " }, { "code": null, "e": 384, "s": 350, "text": "Installation of mongoose module: " }, { "code": null, "e": 488, "s": 384, "text": "You can visit the link to Install mongoose module. You can install this package by using this command. " }, { "code": null, "e": 510, "s": 488, "text": "npm install mongoose\n" }, { "code": null, "e": 622, "s": 510, "text": "After installing the mongoose module, you can check your mongoose version in command prompt using the command. " }, { "code": null, "e": 644, "s": 622, "text": "npm version mongoose\n" }, { "code": null, "e": 738, "s": 644, "text": "After that, you can just create a folder and add a file for example, index.js as shown below." }, { "code": null, "e": 770, "s": 738, "text": "Example 1: Filename: index.js " }, { "code": null, "e": 781, "s": 770, "text": "javascript" }, { "code": "const express = require('express');const mongoose = require('mongoose');const app = express() // Database connectionmongoose.connect('mongodb://127.0.0.1:27017/geeksforgeeks', { useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true}); // User modelconst User = mongoose.model('User', { name: { type: String }, age: { type: Number }}); const query = new mongoose.Query();console.log(query); app.listen(3000, function(error ){ if(error) console.log(error) console.log(\"Server listening on PORT 3000\")})", "e": 1324, "s": 781, "text": null }, { "code": null, "e": 1351, "s": 1324, "text": "Steps to run the program: " }, { "code": null, "e": 1395, "s": 1351, "text": "The project structure will look like this: " }, { "code": null, "e": 1435, "s": 1395, "text": "Run index.js file using below command: " }, { "code": null, "e": 1450, "s": 1435, "text": "node index.js\n" }, { "code": null, "e": 1459, "s": 1450, "text": "Output: " }, { "code": null, "e": 1837, "s": 1459, "text": "Query {\n _mongooseOptions: {},\n _transforms: [],\n _hooks: Kareem { _pres: Map {}, _posts: Map {} },\n _executionCount: 0,\n op: undefined,\n options: {},\n _conditions: {},\n _fields: undefined,\n _update: undefined,\n _path: undefined,\n _distinct: undefined,\n _collection: undefined,\n _traceFunction: undefined,\n '$useProjection': true\n}\nServer listening on PORT 3000\n\n" }, { "code": null, "e": 1868, "s": 1837, "text": "Example 2: Filename: index.js " }, { "code": null, "e": 1879, "s": 1868, "text": "javascript" }, { "code": "const mongoose = require('mongoose'); // Database connectionmongoose.connect('mongodb://127.0.0.1:27017/geeksforgeeks', { useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true}); // User modelconst User = mongoose.model('User', { name: { type: String }, age: { type: Number }}); const query = new mongoose.Query();query.collection(User.collection);console.log(query);", "e": 2282, "s": 1879, "text": null }, { "code": null, "e": 2309, "s": 2282, "text": "Steps to run the program: " }, { "code": null, "e": 2353, "s": 2309, "text": "The project structure will look like this: " }, { "code": null, "e": 2393, "s": 2353, "text": "Run index.js file using below command: " }, { "code": null, "e": 2408, "s": 2393, "text": "node index.js\n" }, { "code": null, "e": 2417, "s": 2408, "text": "Output: " }, { "code": null, "e": 3100, "s": 2417, "text": "Query {\n _mongooseOptions: {},\n _transforms: [],\n _hooks: Kareem { _pres: Map {}, _posts: Map {} },\n _executionCount: 0,\n op: undefined,\n options: {},\n _conditions: {},\n _fields: undefined,\n _update: undefined,\n _path: undefined,\n _distinct: undefined,\n _collection: NodeCollection {\n collection: NativeCollection {\n collection: null,\n Promise: [Function: Promise],\n _closed: false,\n opts: [Object],\n name: 'users',\n collectionName: 'users',\n conn: [NativeConnection],\n queue: [],\n buffer: true,\n emitter: [EventEmitter]\n },\n collectionName: 'users'\n },\n _traceFunction: undefined,\n '$useProjection': true\n}\n" }, { "code": null, "e": 3155, "s": 3100, "text": "Reference: https://mongoosejs.com/docs/api/query.html " }, { "code": null, "e": 3164, "s": 3155, "text": "Mongoose" }, { "code": null, "e": 3172, "s": 3164, "text": "Node.js" }, { "code": null, "e": 3189, "s": 3172, "text": "Web Technologies" }, { "code": null, "e": 3287, "s": 3189, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3341, "s": 3287, "text": "Difference between promise and async await in Node.js" }, { "code": null, "e": 3373, "s": 3341, "text": "JWT Authentication with Node.js" }, { "code": null, "e": 3408, "s": 3373, "text": "Installation of Node.js on Windows" }, { "code": null, "e": 3435, "s": 3408, "text": "Node.js forEach() function" }, { "code": null, "e": 3472, "s": 3435, "text": "How to use an ES6 import in Node.js?" }, { "code": null, "e": 3534, "s": 3472, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 3595, "s": 3534, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3645, "s": 3595, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 3688, "s": 3645, "text": "How to fetch data from an API in ReactJS ?" } ]
Solidity - Basic Syntax
A Solidity source files can contain an any number of contract definitions, import directives and pragma directives. Let's start with a simple source file of Solidity. Following is an example of a Solidity file − pragma solidity >=0.4.0 <0.6.0; contract SimpleStorage { uint storedData; function set(uint x) public { storedData = x; } function get() public view returns (uint) { return storedData; } } The first line is a pragma directive which tells that the source code is written for Solidity version 0.4.0 or anything newer that does not break functionality up to, but not including, version 0.6.0. A pragma directive is always local to a source file and if you import another file, the pragma from that file will not automatically apply to the importing file. So a pragma for a file which will not compile earlier than version 0.4.0 and it will also not work on a compiler starting from version 0.5.0 will be written as follows − pragma solidity ^0.4.0; Here the second condition is added by using ^. A Solidity contract is a collection of code (its functions) and data (its state) that resides at a specific address on the Ethereumblockchain. The line uintstoredData declares a state variable called storedData of type uint and the functions set and get can be used to modify or retrieve the value of the variable. Though above example does not have an import statement but Solidity supports import statements that are very similar to those available in JavaScript. The following statement imports all global symbols from "filename". import "filename"; The following example creates a new global symbol symbolName whose members are all the global symbols from "filename". import * as symbolName from "filename"; To import a file x from the same directory as the current file, use import "./x" as x;. If you use import "x" as x; instead, a different file could be referenced in a global "include directory". Following are the reserved keywords in Solidity −
[ { "code": null, "e": 2805, "s": 2689, "text": "A Solidity source files can contain an any number of contract definitions, import directives and pragma directives." }, { "code": null, "e": 2901, "s": 2805, "text": "Let's start with a simple source file of Solidity. Following is an example of a Solidity file −" }, { "code": null, "e": 3117, "s": 2901, "text": "pragma solidity >=0.4.0 <0.6.0;\ncontract SimpleStorage {\n uint storedData;\n function set(uint x) public {\n storedData = x;\n }\n function get() public view returns (uint) {\n return storedData;\n }\n}" }, { "code": null, "e": 3318, "s": 3117, "text": "The first line is a pragma directive which tells that the source code is written for Solidity version 0.4.0 or anything newer that does not break functionality up to, but not including, version 0.6.0." }, { "code": null, "e": 3480, "s": 3318, "text": "A pragma directive is always local to a source file and if you import another file, the pragma from that file will not automatically apply to the importing file." }, { "code": null, "e": 3650, "s": 3480, "text": "So a pragma for a file which will not compile earlier than version 0.4.0 and it will also not work on a compiler starting from version 0.5.0 will be written as follows −" }, { "code": null, "e": 3674, "s": 3650, "text": "pragma solidity ^0.4.0;" }, { "code": null, "e": 3721, "s": 3674, "text": "Here the second condition is added by using ^." }, { "code": null, "e": 3864, "s": 3721, "text": "A Solidity contract is a collection of code (its functions) and data (its state) that resides at a specific address on the Ethereumblockchain." }, { "code": null, "e": 4036, "s": 3864, "text": "The line uintstoredData declares a state variable called storedData of type uint and the functions set and get can be used to modify or retrieve the value of the variable." }, { "code": null, "e": 4187, "s": 4036, "text": "Though above example does not have an import statement but Solidity supports import statements that are very similar to those available in JavaScript." }, { "code": null, "e": 4255, "s": 4187, "text": "The following statement imports all global symbols from \"filename\"." }, { "code": null, "e": 4275, "s": 4255, "text": "import \"filename\";\n" }, { "code": null, "e": 4394, "s": 4275, "text": "The following example creates a new global symbol symbolName whose members are all the global symbols from \"filename\"." }, { "code": null, "e": 4435, "s": 4394, "text": "import * as symbolName from \"filename\";\n" }, { "code": null, "e": 4630, "s": 4435, "text": "To import a file x from the same directory as the current file, use import \"./x\" as x;. If you use import \"x\" as x; instead, a different file could be referenced in a global \"include directory\"." } ]
Square of large number represented as String
12 May, 2021 Given a very large number, the task is to write a program to compute its square. Examples: Input: 9999 Output: 99980001 9999*9999 = 99980001 Input: 45454545 Output: 2066115661157025 45454545*45454545 = 2066115661157025 Naive Approach: A naive approach is to calculate the squares my multiplying the number with itself. But in C++, if the input is a large number, the resultant square will overflow. Efficient Approach: An efficient approach is to store the number as strings, and perform multiplication of two large numbers. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to multiply two numbers// represented as strings.#include <bits/stdc++.h>using namespace std; // Multiplies str1 and str2, and prints result.string multiply(string num1, string num2){ int n1 = num1.size(); int n2 = num2.size(); if (n1 == 0 || n2 == 0) return "0"; // will keep the result number in vector // in reverse order vector<int> result(n1 + n2, 0); // Below two indexes are used to find positions // in result. int i_n1 = 0; int i_n2 = 0; // Go from right to left in num1 for (int i = n1 - 1; i >= 0; i--) { int carry = 0; int n1 = num1[i] - '0'; // To shift position to left after every // multiplication of a digit in num2 i_n2 = 0; // Go from right to left in num2 for (int j = n2 - 1; j >= 0; j--) { // Take current digit of second number int n2 = num2[j] - '0'; // Multiply with current digit of first number // and add result to previously stored result // at current position. int sum = n1 * n2 + result[i_n1 + i_n2] + carry; // Carry for next iteration carry = sum / 10; // Store result result[i_n1 + i_n2] = sum % 10; i_n2++; } // store carry in next cell if (carry > 0) result[i_n1 + i_n2] += carry; // To shift position to left after every // multiplication of a digit in num1. i_n1++; } // ignore '0's from the right int i = result.size() - 1; while (i >= 0 && result[i] == 0) i--; // If all were '0's - means either both or // one of num1 or num2 were '0' if (i == -1) return "0"; // generate the result string string s = ""; while (i >= 0) s += std::to_string(result[i--]); return s;} // Driver codeint main(){ string str1 = "454545454545454545"; cout << multiply(str1, str1); return 0;} // Java program to multiply two numbers// represented as strings. class GFG{ // Multiplies str1 and str2, and prints result. public static String multiply(String num1, String num2) { int n1 = num1.length(); int n2 = num2.length(); if (n1 == 0 || n2 == 0) return "0"; // will keep the result number in vector // in reverse order int[] result = new int[n1 + n2]; // Below two indexes are used to find positions // in result. int i_n1 = 0; int i_n2 = 0; // Go from right to left in num1 for (int i = n1 - 1; i >= 0; i--) { int carry = 0; int n_1 = num1.charAt(i) - '0'; // To shift position to left after every // multiplication of a digit in num2 i_n2 = 0; // Go from right to left in num2 for (int j = n2 - 1; j >= 0; j--) { // Take current digit of second number int n_2 = num2.charAt(j) - '0'; // Multiply with current digit of first number // and add result to previously stored result // at current position. int sum = n_1 * n_2 + result[i_n1 + i_n2] + carry; // Carry for next iteration carry = sum / 10; // Store result result[i_n1 + i_n2] = sum % 10; i_n2++; } // store carry in next cell if (carry > 0) result[i_n1 + i_n2] += carry; // To shift position to left after every // multiplication of a digit in num1. i_n1++; } // ignore '0's from the right int i = result.length - 1; while (i >= 0 && result[i] == 0) i--; // If all were '0's - means either both or // one of num1 or num2 were '0' if (i == -1) return "0"; // generate the result string String s = ""; while (i >= 0) s += Integer.toString(result[i--]); return s; } // Driver code public static void main(String[] args) { String str1 = "454545454545454545"; System.out.println(multiply(str1, str1)); }} // This code is contributed by// sanjeev2552 # Python3 program to multiply two numbers# represented as strings. # Multiplies str1 and str2, and prints result.def multiply(num1, num2): n1 = len(num1) n2 = len(num2) if (n1 == 0 or n2 == 0): return "0" # Will keep the result number in vector # in reverse order result = [0] * (n1 + n2) # Below two indexes are used to # find positions in result. i_n1 = 0 i_n2 = 0 # Go from right to left in num1 for i in range(n1 - 1, -1, -1): carry = 0 n_1 = ord(num1[i]) - ord('0') # To shift position to left after every # multiplication of a digit in num2 i_n2 = 0 # Go from right to left in num2 for j in range(n2 - 1, -1, -1): # Take current digit of second number n_2 = ord(num2[j]) - ord('0') # Multiply with current digit of first number # and add result to previously stored result # at current position. sum = n_1 * n_2 + result[i_n1 + i_n2] + carry # Carry for next iteration carry = sum // 10 # Store result result[i_n1 + i_n2] = sum % 10 i_n2 += 1 # Store carry in next cell if (carry > 0): result[i_n1 + i_n2] += carry # To shift position to left after every # multiplication of a digit in num1. i_n1 += 1 # Ignore '0's from the right i = len(result) - 1 while (i >= 0 and result[i] == 0): i -= 1 # If all were '0's - means either both or # one of num1 or num2 were '0' if (i == -1): return "0" # Generate the result string s = "" while (i >= 0): s += str(result[i]) i -= 1 return s # Driver codeif __name__ == "__main__": str1 = "454545454545454545" print(multiply(str1, str1)) # This code is contributed by chitranayal // C# program to multiply two numbers// represented as strings.using System;using System.Collections.Generic; class GFG{ // Multiplies str1 and str2, // and prints result. public static String multiply(String num1, String num2) { int n1 = num1.Length; int n2 = num2.Length; if (n1 == 0 || n2 == 0) return "0"; // will keep the result number in vector // in reverse order int[] result = new int[n1 + n2]; // Below two indexes are used to // find positions in result. int i_n1 = 0; int i_n2 = 0; int i = 0; // Go from right to left in num1 for (i = n1 - 1; i >= 0; i--) { int carry = 0; int n_1 = num1[i] - '0'; // To shift position to left after every // multiplication of a digit in num2 i_n2 = 0; // Go from right to left in num2 for (int j = n2 - 1; j >= 0; j--) { // Take current digit of second number int n_2 = num2[j] - '0'; // Multiply with current digit of first number // and add result to previously stored result // at current position. int sum = n_1 * n_2 + result[i_n1 + i_n2] + carry; // Carry for next iteration carry = sum / 10; // Store result result[i_n1 + i_n2] = sum % 10; i_n2++; } // store carry in next cell if (carry > 0) result[i_n1 + i_n2] += carry; // To shift position to left after every // multiplication of a digit in num1. i_n1++; } // ignore '0's from the right i = result.Length - 1; while (i >= 0 && result[i] == 0) i--; // If all were '0's - means either both or // one of num1 or num2 were '0' if (i == -1) return "0"; // generate the result string String s = ""; while (i >= 0) s += (result[i--]).ToString(); return s; } // Driver code public static void Main(String[] args) { String str1 = "454545454545454545"; Console.WriteLine(multiply(str1, str1)); }} // This code is contributed by Princi Singh <script>// Javascript program to multiply two numbers// represented as strings. // Multiplies str1 and str2, and prints result. function multiply(num1,num2) { let n1 = num1.length; let n2 = num2.length; if (n1 == 0 || n2 == 0) return "0"; // will keep the result number in vector // in reverse order let result = new Array(n1 + n2); for(let i=0;i<result.length;i++) { result[i]=0; } // Below two indexes are used to find positions // in result. let i_n1 = 0; let i_n2 = 0; // Go from right to left in num1 for (let i = n1 - 1; i >= 0; i--) { let carry = 0; let n_1 = num1[i].charCodeAt(0) - '0'.charCodeAt(0); // To shift position to left after every // multiplication of a digit in num2 i_n2 = 0; // Go from right to left in num2 for (let j = n2 - 1; j >= 0; j--) { // Take current digit of second number let n_2 = num2[j].charCodeAt(0) - '0'.charCodeAt(0); // Multiply with current digit of first number // and add result to previously stored result // at current position. let sum = n_1 * n_2 + result[i_n1 + i_n2] + carry; // Carry for next iteration carry = Math.floor(sum / 10); // Store result result[i_n1 + i_n2] = sum % 10; i_n2++; } // store carry in next cell if (carry > 0) result[i_n1 + i_n2] += carry; // To shift position to left after every // multiplication of a digit in num1. i_n1++; } // ignore '0's from the right let i = result.length - 1; while (i >= 0 && result[i] == 0) i--; // If all were '0's - means either both or // one of num1 or num2 were '0' if (i == -1) return "0"; // generate the result string let s = ""; while (i >= 0) s += (result[i--]).toString(); return s; } // Driver code let str1 = "454545454545454545"; document.write(multiply(str1, str1)); // This code is contributed by avanitrachhadiya2155</script> 206611570247933883884297520661157025 sanjeev2552 princi singh ukasp avanitrachhadiya2155 math Arrays C++ Programs Strings Arrays Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n12 May, 2021" }, { "code": null, "e": 136, "s": 54, "text": "Given a very large number, the task is to write a program to compute its square. " }, { "code": null, "e": 148, "s": 136, "text": "Examples: " }, { "code": null, "e": 198, "s": 148, "text": "Input: 9999 Output: 99980001 9999*9999 = 99980001" }, { "code": null, "e": 276, "s": 198, "text": "Input: 45454545 Output: 2066115661157025 45454545*45454545 = 2066115661157025" }, { "code": null, "e": 457, "s": 276, "text": "Naive Approach: A naive approach is to calculate the squares my multiplying the number with itself. But in C++, if the input is a large number, the resultant square will overflow. " }, { "code": null, "e": 584, "s": 457, "text": "Efficient Approach: An efficient approach is to store the number as strings, and perform multiplication of two large numbers. " }, { "code": null, "e": 637, "s": 584, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 641, "s": 637, "text": "C++" }, { "code": null, "e": 646, "s": 641, "text": "Java" }, { "code": null, "e": 654, "s": 646, "text": "Python3" }, { "code": null, "e": 657, "s": 654, "text": "C#" }, { "code": null, "e": 668, "s": 657, "text": "Javascript" }, { "code": "// C++ program to multiply two numbers// represented as strings.#include <bits/stdc++.h>using namespace std; // Multiplies str1 and str2, and prints result.string multiply(string num1, string num2){ int n1 = num1.size(); int n2 = num2.size(); if (n1 == 0 || n2 == 0) return \"0\"; // will keep the result number in vector // in reverse order vector<int> result(n1 + n2, 0); // Below two indexes are used to find positions // in result. int i_n1 = 0; int i_n2 = 0; // Go from right to left in num1 for (int i = n1 - 1; i >= 0; i--) { int carry = 0; int n1 = num1[i] - '0'; // To shift position to left after every // multiplication of a digit in num2 i_n2 = 0; // Go from right to left in num2 for (int j = n2 - 1; j >= 0; j--) { // Take current digit of second number int n2 = num2[j] - '0'; // Multiply with current digit of first number // and add result to previously stored result // at current position. int sum = n1 * n2 + result[i_n1 + i_n2] + carry; // Carry for next iteration carry = sum / 10; // Store result result[i_n1 + i_n2] = sum % 10; i_n2++; } // store carry in next cell if (carry > 0) result[i_n1 + i_n2] += carry; // To shift position to left after every // multiplication of a digit in num1. i_n1++; } // ignore '0's from the right int i = result.size() - 1; while (i >= 0 && result[i] == 0) i--; // If all were '0's - means either both or // one of num1 or num2 were '0' if (i == -1) return \"0\"; // generate the result string string s = \"\"; while (i >= 0) s += std::to_string(result[i--]); return s;} // Driver codeint main(){ string str1 = \"454545454545454545\"; cout << multiply(str1, str1); return 0;}", "e": 2646, "s": 668, "text": null }, { "code": "// Java program to multiply two numbers// represented as strings. class GFG{ // Multiplies str1 and str2, and prints result. public static String multiply(String num1, String num2) { int n1 = num1.length(); int n2 = num2.length(); if (n1 == 0 || n2 == 0) return \"0\"; // will keep the result number in vector // in reverse order int[] result = new int[n1 + n2]; // Below two indexes are used to find positions // in result. int i_n1 = 0; int i_n2 = 0; // Go from right to left in num1 for (int i = n1 - 1; i >= 0; i--) { int carry = 0; int n_1 = num1.charAt(i) - '0'; // To shift position to left after every // multiplication of a digit in num2 i_n2 = 0; // Go from right to left in num2 for (int j = n2 - 1; j >= 0; j--) { // Take current digit of second number int n_2 = num2.charAt(j) - '0'; // Multiply with current digit of first number // and add result to previously stored result // at current position. int sum = n_1 * n_2 + result[i_n1 + i_n2] + carry; // Carry for next iteration carry = sum / 10; // Store result result[i_n1 + i_n2] = sum % 10; i_n2++; } // store carry in next cell if (carry > 0) result[i_n1 + i_n2] += carry; // To shift position to left after every // multiplication of a digit in num1. i_n1++; } // ignore '0's from the right int i = result.length - 1; while (i >= 0 && result[i] == 0) i--; // If all were '0's - means either both or // one of num1 or num2 were '0' if (i == -1) return \"0\"; // generate the result string String s = \"\"; while (i >= 0) s += Integer.toString(result[i--]); return s; } // Driver code public static void main(String[] args) { String str1 = \"454545454545454545\"; System.out.println(multiply(str1, str1)); }} // This code is contributed by// sanjeev2552", "e": 4963, "s": 2646, "text": null }, { "code": "# Python3 program to multiply two numbers# represented as strings. # Multiplies str1 and str2, and prints result.def multiply(num1, num2): n1 = len(num1) n2 = len(num2) if (n1 == 0 or n2 == 0): return \"0\" # Will keep the result number in vector # in reverse order result = [0] * (n1 + n2) # Below two indexes are used to # find positions in result. i_n1 = 0 i_n2 = 0 # Go from right to left in num1 for i in range(n1 - 1, -1, -1): carry = 0 n_1 = ord(num1[i]) - ord('0') # To shift position to left after every # multiplication of a digit in num2 i_n2 = 0 # Go from right to left in num2 for j in range(n2 - 1, -1, -1): # Take current digit of second number n_2 = ord(num2[j]) - ord('0') # Multiply with current digit of first number # and add result to previously stored result # at current position. sum = n_1 * n_2 + result[i_n1 + i_n2] + carry # Carry for next iteration carry = sum // 10 # Store result result[i_n1 + i_n2] = sum % 10 i_n2 += 1 # Store carry in next cell if (carry > 0): result[i_n1 + i_n2] += carry # To shift position to left after every # multiplication of a digit in num1. i_n1 += 1 # Ignore '0's from the right i = len(result) - 1 while (i >= 0 and result[i] == 0): i -= 1 # If all were '0's - means either both or # one of num1 or num2 were '0' if (i == -1): return \"0\" # Generate the result string s = \"\" while (i >= 0): s += str(result[i]) i -= 1 return s # Driver codeif __name__ == \"__main__\": str1 = \"454545454545454545\" print(multiply(str1, str1)) # This code is contributed by chitranayal", "e": 6863, "s": 4963, "text": null }, { "code": "// C# program to multiply two numbers// represented as strings.using System;using System.Collections.Generic; class GFG{ // Multiplies str1 and str2, // and prints result. public static String multiply(String num1, String num2) { int n1 = num1.Length; int n2 = num2.Length; if (n1 == 0 || n2 == 0) return \"0\"; // will keep the result number in vector // in reverse order int[] result = new int[n1 + n2]; // Below two indexes are used to // find positions in result. int i_n1 = 0; int i_n2 = 0; int i = 0; // Go from right to left in num1 for (i = n1 - 1; i >= 0; i--) { int carry = 0; int n_1 = num1[i] - '0'; // To shift position to left after every // multiplication of a digit in num2 i_n2 = 0; // Go from right to left in num2 for (int j = n2 - 1; j >= 0; j--) { // Take current digit of second number int n_2 = num2[j] - '0'; // Multiply with current digit of first number // and add result to previously stored result // at current position. int sum = n_1 * n_2 + result[i_n1 + i_n2] + carry; // Carry for next iteration carry = sum / 10; // Store result result[i_n1 + i_n2] = sum % 10; i_n2++; } // store carry in next cell if (carry > 0) result[i_n1 + i_n2] += carry; // To shift position to left after every // multiplication of a digit in num1. i_n1++; } // ignore '0's from the right i = result.Length - 1; while (i >= 0 && result[i] == 0) i--; // If all were '0's - means either both or // one of num1 or num2 were '0' if (i == -1) return \"0\"; // generate the result string String s = \"\"; while (i >= 0) s += (result[i--]).ToString(); return s; } // Driver code public static void Main(String[] args) { String str1 = \"454545454545454545\"; Console.WriteLine(multiply(str1, str1)); }} // This code is contributed by Princi Singh", "e": 9284, "s": 6863, "text": null }, { "code": "<script>// Javascript program to multiply two numbers// represented as strings. // Multiplies str1 and str2, and prints result. function multiply(num1,num2) { let n1 = num1.length; let n2 = num2.length; if (n1 == 0 || n2 == 0) return \"0\"; // will keep the result number in vector // in reverse order let result = new Array(n1 + n2); for(let i=0;i<result.length;i++) { result[i]=0; } // Below two indexes are used to find positions // in result. let i_n1 = 0; let i_n2 = 0; // Go from right to left in num1 for (let i = n1 - 1; i >= 0; i--) { let carry = 0; let n_1 = num1[i].charCodeAt(0) - '0'.charCodeAt(0); // To shift position to left after every // multiplication of a digit in num2 i_n2 = 0; // Go from right to left in num2 for (let j = n2 - 1; j >= 0; j--) { // Take current digit of second number let n_2 = num2[j].charCodeAt(0) - '0'.charCodeAt(0); // Multiply with current digit of first number // and add result to previously stored result // at current position. let sum = n_1 * n_2 + result[i_n1 + i_n2] + carry; // Carry for next iteration carry = Math.floor(sum / 10); // Store result result[i_n1 + i_n2] = sum % 10; i_n2++; } // store carry in next cell if (carry > 0) result[i_n1 + i_n2] += carry; // To shift position to left after every // multiplication of a digit in num1. i_n1++; } // ignore '0's from the right let i = result.length - 1; while (i >= 0 && result[i] == 0) i--; // If all were '0's - means either both or // one of num1 or num2 were '0' if (i == -1) return \"0\"; // generate the result string let s = \"\"; while (i >= 0) s += (result[i--]).toString(); return s; } // Driver code let str1 = \"454545454545454545\"; document.write(multiply(str1, str1)); // This code is contributed by avanitrachhadiya2155</script>", "e": 11676, "s": 9284, "text": null }, { "code": null, "e": 11713, "s": 11676, "text": "206611570247933883884297520661157025" }, { "code": null, "e": 11727, "s": 11715, "text": "sanjeev2552" }, { "code": null, "e": 11740, "s": 11727, "text": "princi singh" }, { "code": null, "e": 11746, "s": 11740, "text": "ukasp" }, { "code": null, "e": 11767, "s": 11746, "text": "avanitrachhadiya2155" }, { "code": null, "e": 11772, "s": 11767, "text": "math" }, { "code": null, "e": 11779, "s": 11772, "text": "Arrays" }, { "code": null, "e": 11792, "s": 11779, "text": "C++ Programs" }, { "code": null, "e": 11800, "s": 11792, "text": "Strings" }, { "code": null, "e": 11807, "s": 11800, "text": "Arrays" }, { "code": null, "e": 11815, "s": 11807, "text": "Strings" } ]
JavaScript Date getFullYear() Method
12 Oct, 2021 Below is the example of Date getFullYear() method. Example: javascript <script> // Here a date has been assigned // while creating Date object var dateobj = new Date('October 15, 1996 05:35:32'); // year from above date object is // being fetched using getFullYear(). var B = dateobj.getFullYear(); // Printing year document.write(B);</script> Output: 1996 The date.getFullYear() method is used to fetch the year from a given Date object.Syntax: DateObj.getFullYear() Parameter: This function does not accept any parameters.Return Values: It returns the year for the given date.More codes for the above method are as follows: Program 1: If nothing as parameter is given to the Date() constructor, then the getFullYear() function returns current year. javascript <script> // Creating Date Object var dateobj = new Date(); // year from above object // is being fetched using getFullYear(). var B = dateobj.getFullYear(); // Printing current year document.write(B);</script> Output: 2018 Program 2: The date of the month must lie between 1 to 31 because a month cannot have more than 31 days. That is why it returns NaN i.e, not a number because the date for the month does not exist. Hence, Year will not exist when the date of the month is set as 45 or any number which does not lie between 1 to 31. javascript <script> // Here a date has been assigned // while creating Date object var dateobj = new Date('October 45, 1996 05:35:32'); // year from above date object is // being fetched using getFullYear(). var B = dateobj.getFullYear(); // Printing year document.write(B);</script> Output: NaN Program 3: It has applications such as getting current year.It is used in websites to validate the age of the user. javascript <script> // Creating Date Object var dateobj = new Date(); // Year from above object // is being fetched using getFullYear() var B = dateobj.getFullYear(); // Printing current year document.write(B);</script> Output: 2018 Supported Browsers: The browsers supported by JavaScript Date getFullYear() method are listed below: Google Chrome 1 and above Edge 12 and above Firefox 1 and above Internet Explorer 4 and above Opera 4 and above Safari 1 and above RahulRanjan4 ysachin2314 javascript-date JavaScript-Methods JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n12 Oct, 2021" }, { "code": null, "e": 81, "s": 28, "text": "Below is the example of Date getFullYear() method. " }, { "code": null, "e": 92, "s": 81, "text": "Example: " }, { "code": null, "e": 103, "s": 92, "text": "javascript" }, { "code": "<script> // Here a date has been assigned // while creating Date object var dateobj = new Date('October 15, 1996 05:35:32'); // year from above date object is // being fetched using getFullYear(). var B = dateobj.getFullYear(); // Printing year document.write(B);</script>", "e": 386, "s": 103, "text": null }, { "code": null, "e": 396, "s": 386, "text": "Output: " }, { "code": null, "e": 401, "s": 396, "text": "1996" }, { "code": null, "e": 492, "s": 401, "text": "The date.getFullYear() method is used to fetch the year from a given Date object.Syntax: " }, { "code": null, "e": 514, "s": 492, "text": "DateObj.getFullYear()" }, { "code": null, "e": 799, "s": 514, "text": "Parameter: This function does not accept any parameters.Return Values: It returns the year for the given date.More codes for the above method are as follows: Program 1: If nothing as parameter is given to the Date() constructor, then the getFullYear() function returns current year. " }, { "code": null, "e": 810, "s": 799, "text": "javascript" }, { "code": "<script> // Creating Date Object var dateobj = new Date(); // year from above object // is being fetched using getFullYear(). var B = dateobj.getFullYear(); // Printing current year document.write(B);</script>", "e": 1031, "s": 810, "text": null }, { "code": null, "e": 1041, "s": 1031, "text": "Output: " }, { "code": null, "e": 1046, "s": 1041, "text": "2018" }, { "code": null, "e": 1361, "s": 1046, "text": "Program 2: The date of the month must lie between 1 to 31 because a month cannot have more than 31 days. That is why it returns NaN i.e, not a number because the date for the month does not exist. Hence, Year will not exist when the date of the month is set as 45 or any number which does not lie between 1 to 31. " }, { "code": null, "e": 1372, "s": 1361, "text": "javascript" }, { "code": "<script> // Here a date has been assigned // while creating Date object var dateobj = new Date('October 45, 1996 05:35:32'); // year from above date object is // being fetched using getFullYear(). var B = dateobj.getFullYear(); // Printing year document.write(B);</script>", "e": 1655, "s": 1372, "text": null }, { "code": null, "e": 1665, "s": 1655, "text": "Output: " }, { "code": null, "e": 1669, "s": 1665, "text": "NaN" }, { "code": null, "e": 1787, "s": 1669, "text": "Program 3: It has applications such as getting current year.It is used in websites to validate the age of the user. " }, { "code": null, "e": 1798, "s": 1787, "text": "javascript" }, { "code": "<script> // Creating Date Object var dateobj = new Date(); // Year from above object // is being fetched using getFullYear() var B = dateobj.getFullYear(); // Printing current year document.write(B);</script>", "e": 2016, "s": 1798, "text": null }, { "code": null, "e": 2026, "s": 2016, "text": "Output: " }, { "code": null, "e": 2031, "s": 2026, "text": "2018" }, { "code": null, "e": 2134, "s": 2031, "text": "Supported Browsers: The browsers supported by JavaScript Date getFullYear() method are listed below: " }, { "code": null, "e": 2160, "s": 2134, "text": "Google Chrome 1 and above" }, { "code": null, "e": 2178, "s": 2160, "text": "Edge 12 and above" }, { "code": null, "e": 2198, "s": 2178, "text": "Firefox 1 and above" }, { "code": null, "e": 2228, "s": 2198, "text": "Internet Explorer 4 and above" }, { "code": null, "e": 2246, "s": 2228, "text": "Opera 4 and above" }, { "code": null, "e": 2265, "s": 2246, "text": "Safari 1 and above" }, { "code": null, "e": 2280, "s": 2267, "text": "RahulRanjan4" }, { "code": null, "e": 2292, "s": 2280, "text": "ysachin2314" }, { "code": null, "e": 2308, "s": 2292, "text": "javascript-date" }, { "code": null, "e": 2327, "s": 2308, "text": "JavaScript-Methods" }, { "code": null, "e": 2338, "s": 2327, "text": "JavaScript" }, { "code": null, "e": 2355, "s": 2338, "text": "Web Technologies" } ]
How to empty an array in JavaScript?
There are a couple of ways to empty an array in javascript. Let's suppose take an array var array1 = [1,2,3,4,5,6,7]; var array1 = [1,2,3,4,5,6,7]; var array1 = []; var array1 = []; The code above will set the number array to a new empty array. This is recommended when you don't have any references to the original array 'array1'. You should be careful with this way of empty the array, because if you have referenced this array from another variable, then the original reference array will remain unchanged. <html> <body> <script> var array1 = [1,2,3,4,5,6,7]; // Created array var anotherArray = array1; // Referenced array1 by another variable array1 = []; // Empty the array document.write(anotherArray); // Output [1,2,3,4,5,6,7] </script> </body> </html> var array1.length = 0; var array1.length = 0; The line of code above will make the length of original array to 0 there by emptying the array. <html> <body> <script> var array1 = [1,2,3,4,5,6,7]; // Created array var anotherArray = array1; // Referenced array1 by another variable array1.length = 0; // Empty the array by setting length to 0 console.log(anotherArray); // Output [] </script> </body> </html> array1.splice(0, array1.length); array1.splice(0, array1.length); The above line of code also works perfectly. This way of code will update all the references of the original array. <html> <body> <script> var array1 = [1,2,3,4,5,6,7]; // Created array var anotherArray = array1; // Referenced array1 by another variable array1.splice(0, array1.length); // Empty the array by setting length to 0 console.log(anotherArray); // Output [] </script> </body> </html>
[ { "code": null, "e": 1122, "s": 1062, "text": "There are a couple of ways to empty an array in javascript." }, { "code": null, "e": 1150, "s": 1122, "text": "Let's suppose take an array" }, { "code": null, "e": 1180, "s": 1150, "text": "var array1 = [1,2,3,4,5,6,7];" }, { "code": null, "e": 1210, "s": 1180, "text": "var array1 = [1,2,3,4,5,6,7];" }, { "code": null, "e": 1227, "s": 1210, "text": "var array1 = [];" }, { "code": null, "e": 1244, "s": 1227, "text": "var array1 = [];" }, { "code": null, "e": 1572, "s": 1244, "text": "The code above will set the number array to a new empty array. This is recommended when you don't have any references to the original array 'array1'. You should be careful with this way of empty the array, because if you have referenced this array from another variable, then the original reference array will remain unchanged." }, { "code": null, "e": 1860, "s": 1572, "text": "<html>\n<body>\n<script>\n var array1 = [1,2,3,4,5,6,7]; // Created array\n var anotherArray = array1; // Referenced array1 by another variable\n array1 = []; // Empty the array\n document.write(anotherArray); // Output [1,2,3,4,5,6,7]\n</script>\n</body>\n</html>" }, { "code": null, "e": 1883, "s": 1860, "text": "var array1.length = 0;" }, { "code": null, "e": 1906, "s": 1883, "text": "var array1.length = 0;" }, { "code": null, "e": 2002, "s": 1906, "text": "The line of code above will make the length of original array to 0 there by emptying the array." }, { "code": null, "e": 2279, "s": 2002, "text": "<html>\n<body>\n<script>\n var array1 = [1,2,3,4,5,6,7]; // Created array\n var anotherArray = array1; // Referenced array1 by another variable\n array1.length = 0; // Empty the array by setting length to 0\n console.log(anotherArray); // Output []\n</script>\n</body>\n</html>" }, { "code": null, "e": 2312, "s": 2279, "text": "array1.splice(0, array1.length);" }, { "code": null, "e": 2345, "s": 2312, "text": "array1.splice(0, array1.length);" }, { "code": null, "e": 2461, "s": 2345, "text": "The above line of code also works perfectly. This way of code will update all the references of the original array." }, { "code": null, "e": 2752, "s": 2461, "text": "<html>\n<body>\n<script>\n var array1 = [1,2,3,4,5,6,7]; // Created array\n var anotherArray = array1; // Referenced array1 by another variable\n array1.splice(0, array1.length); // Empty the array by setting length to 0\n console.log(anotherArray); // Output []\n</script>\n</body>\n</html>" } ]
Create TFRecords Dataset and use it to train an ML model | by Raghav Sharma | Towards Data Science
Hi Geeks, Hope you are well and safe. In this story, you will learn about : 1. What are TFRecords?2. How to save data as tfrecords files?3. Extract TFRecord data.4. How to use a dataset from tfrecord for training a model? PS — If you are here just to get the code. Take it from here and enjoy! The TFRecord is a Tensorflow format that is used for storing a sequence of binary records. Other than sequential data, TFrecord can also be used for storing images and 1D vectors. In this article we will see how to store and read data of the following type : (i) Integer.(int64, uint8, etc.)(ii) Floats.(iii) Strings.(iv) Images.TFRecord can only be read and written in a sequential manner. So, It is generally be used for sequential models like RNN, LSTM, etc. But that does not mean we can use it for sequential learning only. To store any data to tfrecords, we first need to create TensorFlow examples. These TensorFlow examples can be created using tf.train.examples functions. This function will create an example object which contains some features inside it. The code is as follows- example = tf.train.Example(features = tf.train.Features(feature = { })) What should be there in the feature? These features contain our images, data and also contain the filename of that data. If someone is working with a supervised algorithm, the corresponding labels of an image will also be there in features. So, a typical code for creating features will be — NOTE- images and corresponding labels have been saved in byte format. Once we have creates an example of an image, we need to write it into a trfrecord file. These can be done using tfrecord writer. tfrecord_file_name in the below code is the file name of tfrecord in which we want to store the images. TensorFlow will create these files automatically. writer = tf.python_io.TFRecordWriter(tfrecord_file_name)writer.write(example.SerializeToString()) Code for storing images Reading tfrecord file is simpler if you know the correct way to write them. The process is just the same. First, we need to create a dictionary of features that we have used to write the rfrecord file. Then we will create a dataset object using tf.train.TFRecordDataset function. Once the dataset object has been created we will map that dataset object to our desired dataset using the code given below. In the above piece of code, the function _extract_fn maps the dataset into a list of our desired things (filename, image, labels, image_shape). To do this, we first parse the examples that we have made during the generation of tfrecords. After parsing we will need to decode the parsed examples to the images by using the tf.io.decode_raw() function. To use data extracted from tfrecord for training a model, we will be creating an iterator on the dataset object. iterator = tf.compat.v1.data.make_initializable_iterator(batch_dataset) After creating this iterator, we will loop into this iterator so that we can train the model on every image extracted from this iterator. Function extract_image do that for every image present in tfrecord by using iterator.get_next(). Refer to the code below for this function. Hope you have got an idea about tfrecord now and how we can utilize them for training a model.
[ { "code": null, "e": 181, "s": 171, "text": "Hi Geeks," }, { "code": null, "e": 209, "s": 181, "text": "Hope you are well and safe." }, { "code": null, "e": 393, "s": 209, "text": "In this story, you will learn about : 1. What are TFRecords?2. How to save data as tfrecords files?3. Extract TFRecord data.4. How to use a dataset from tfrecord for training a model?" }, { "code": null, "e": 465, "s": 393, "text": "PS — If you are here just to get the code. Take it from here and enjoy!" }, { "code": null, "e": 994, "s": 465, "text": "The TFRecord is a Tensorflow format that is used for storing a sequence of binary records. Other than sequential data, TFrecord can also be used for storing images and 1D vectors. In this article we will see how to store and read data of the following type : (i) Integer.(int64, uint8, etc.)(ii) Floats.(iii) Strings.(iv) Images.TFRecord can only be read and written in a sequential manner. So, It is generally be used for sequential models like RNN, LSTM, etc. But that does not mean we can use it for sequential learning only." }, { "code": null, "e": 1255, "s": 994, "text": "To store any data to tfrecords, we first need to create TensorFlow examples. These TensorFlow examples can be created using tf.train.examples functions. This function will create an example object which contains some features inside it. The code is as follows-" }, { "code": null, "e": 1334, "s": 1255, "text": "example = tf.train.Example(features = tf.train.Features(feature = { }))" }, { "code": null, "e": 1371, "s": 1334, "text": "What should be there in the feature?" }, { "code": null, "e": 1626, "s": 1371, "text": "These features contain our images, data and also contain the filename of that data. If someone is working with a supervised algorithm, the corresponding labels of an image will also be there in features. So, a typical code for creating features will be —" }, { "code": null, "e": 1696, "s": 1626, "text": "NOTE- images and corresponding labels have been saved in byte format." }, { "code": null, "e": 1979, "s": 1696, "text": "Once we have creates an example of an image, we need to write it into a trfrecord file. These can be done using tfrecord writer. tfrecord_file_name in the below code is the file name of tfrecord in which we want to store the images. TensorFlow will create these files automatically." }, { "code": null, "e": 2077, "s": 1979, "text": "writer = tf.python_io.TFRecordWriter(tfrecord_file_name)writer.write(example.SerializeToString())" }, { "code": null, "e": 2101, "s": 2077, "text": "Code for storing images" }, { "code": null, "e": 2381, "s": 2101, "text": "Reading tfrecord file is simpler if you know the correct way to write them. The process is just the same. First, we need to create a dictionary of features that we have used to write the rfrecord file. Then we will create a dataset object using tf.train.TFRecordDataset function." }, { "code": null, "e": 2505, "s": 2381, "text": "Once the dataset object has been created we will map that dataset object to our desired dataset using the code given below." }, { "code": null, "e": 2856, "s": 2505, "text": "In the above piece of code, the function _extract_fn maps the dataset into a list of our desired things (filename, image, labels, image_shape). To do this, we first parse the examples that we have made during the generation of tfrecords. After parsing we will need to decode the parsed examples to the images by using the tf.io.decode_raw() function." }, { "code": null, "e": 2969, "s": 2856, "text": "To use data extracted from tfrecord for training a model, we will be creating an iterator on the dataset object." }, { "code": null, "e": 3041, "s": 2969, "text": "iterator = tf.compat.v1.data.make_initializable_iterator(batch_dataset)" }, { "code": null, "e": 3319, "s": 3041, "text": "After creating this iterator, we will loop into this iterator so that we can train the model on every image extracted from this iterator. Function extract_image do that for every image present in tfrecord by using iterator.get_next(). Refer to the code below for this function." } ]
Finding n-th number made of prime digits (2, 3, 5 and 7) only - GeeksforGeeks
11 Mar, 2022 Given a number ‘n’, we need to find the nth number whose each digit is a prime number i.e 2, 3, 5, 7....In other words you have to find nth number of this sequence. 2, 3, 5, 5, 22, 23...... Given that the nth number such found will be less then equal to 10^18 Examples : Input : 10 Output : 33 2, 3, 5, 7, 22, 23, 25, 27, 32, 33 Input : 21 Output : 222 There are four prime digits 2, 3, 5 and 7. First observation is that the number of numbers of x length and made of prime digits are because for each position you have 4 choices so total number is 4^x. So total count of such numbers whose length is = 1 to len (i.e. 2 or 3 or more) will be 4*((4len – 1)/3). (This is sum of G.P with first term 4 and common ratio 4)The algorithm is mainly divided in two steps. We find the number of digits in n-th number using above observation. We start from len = 0 and keep incrementing it while value of it is smaller than 4*((4len – 1)/3).Now we know number of digits in n-th number. We also know the count of numbers with with (len-1) digits. Let this count be ‘prev_count’. Now we one by one find digits in our result. First fix 2 at i-th place (assuming all the places upto i-1 are already filled), we have 4^(len – i) numbers possible and to check if 2 is the right candidate or not check if count of numbers after putting 2 is greater than or equal to n or not. If it is true then 2 is the right candidate if this is not true this means if we fix 2 at ith place only prev_count + 4^(len-i) numbers can be covered. So increase prev_count by 4^(len-i) and repeat this step for 3 check if 3 fits at ith place or not .If not go for 5. If 5 also does not fit, go for 7. It is guaranteed that 7 will fit it if 2, 3 and 5 do not fit, because we are sure that the length of nth such number is len only. We find the number of digits in n-th number using above observation. We start from len = 0 and keep incrementing it while value of it is smaller than 4*((4len – 1)/3). Now we know number of digits in n-th number. We also know the count of numbers with with (len-1) digits. Let this count be ‘prev_count’. Now we one by one find digits in our result. First fix 2 at i-th place (assuming all the places upto i-1 are already filled), we have 4^(len – i) numbers possible and to check if 2 is the right candidate or not check if count of numbers after putting 2 is greater than or equal to n or not. If it is true then 2 is the right candidate if this is not true this means if we fix 2 at ith place only prev_count + 4^(len-i) numbers can be covered. So increase prev_count by 4^(len-i) and repeat this step for 3 check if 3 fits at ith place or not .If not go for 5. If 5 also does not fit, go for 7. It is guaranteed that 7 will fit it if 2, 3 and 5 do not fit, because we are sure that the length of nth such number is len only. Below is implementation of above steps. C++ Java Python3 C# PHP Javascript // C++ implementation for finding nth number// made of prime digits only#include <bits/stdc++.h>using namespace std; // Prints n-th number where each digit is a// prime numbervoid nthprimedigitsnumber(long long n){ // Finding the length of n-th number long long len = 1; // Count of numbers with len-1 digits long long prev_count = 0; while (true) { // Count of numbers with i digits long long curr_count = prev_count + pow(4, len); // if i is the length of such number // then n<4*(4^(i-1)-1)/3 and n>= 4*(4 ^ i-1)/3 // if a valid i is found break the loop if (prev_count < n && curr_count >= n) break; // check for i + 1 len++; prev_count = curr_count; } // Till now we have covered 'prev_count' numbers // Finding ith digit at ith place for (int i = 1; i <= len; i++) { // j = 1 means 2 j = 2 means ...j = 4 means 7 for (long long j = 1; j <= 4; j++) { // if prev_count + 4 ^ (len-i) is less // than n, increase prev_count by 4^(x-i) if (prev_count + pow(4, len - i) < n) prev_count += pow(4, len - i); // else print the ith digit and break else { if (j == 1) cout << "2"; else if (j == 2) cout << "3"; else if (j == 3) cout << "5"; else if (j == 4) cout << "7"; break; } } } cout << endl;} // Driver functionint main(){ nthprimedigitsnumber(10); nthprimedigitsnumber(21); return 0;} // Java implementation for finding nth number// made of prime digits only import static java.lang.Math.pow; class Test { // Prints n-th number where each digit is a // prime number static void nthprimedigitsnumber(long n) { // Finding the length of n-th number long len = 1; // Count of numbers with len-1 digits long prev_count = 0; while (true) { // Count of numbers with i digits long curr_count = (long)(prev_count + pow(4, len)); // if i is the length of such number // then n<4*(4^(i-1)-1)/3 and n>= 4*(4 ^ i-1)/3 // if a valid i is found break the loop if (prev_count < n && curr_count >= n) break; // check for i + 1 len++; prev_count = curr_count; } // Till now we have covered 'prev_count' numbers // Finding ith digit at ith place for (int i = 1; i <= len; i++) { // j = 1 means 2 j = 2 means ...j = 4 means 7 for (long j = 1; j <= 4; j++) { // if prev_count + 4 ^ (len-i) is less // than n, increase prev_count by 4^(x-i) if (prev_count + pow(4, len - i) < n) prev_count += pow(4, len - i); // else print the ith digit and break else { if (j == 1) System.out.print("2"); else if (j == 2) System.out.print("3"); else if (j == 3) System.out.print("5"); else if (j == 4) System.out.print("7"); break; } } } System.out.println(); } // Driver method public static void main(String args[]) { nthprimedigitsnumber(10); nthprimedigitsnumber(21); }} # Python3 implementation for# finding nth number made of# prime digits onlyimport math # Prints n-th number where# each digit is a prime numberdef nthprimedigitsnumber(n): # Finding the length # of n-th number len = 1; # Count of numbers # with len-1 digits prev_count = 0; while(1): # Count of numbers # with i digits curr_count = (prev_count + math.pow(4, len)); # if i is the length of such # number then n<4*(4^(i-1)-1)/3 # and n>= 4*(4 ^ i-1)/3 if a valid # i is found break the loop if (prev_count < n and curr_count >= n): break; # check for i + 1 len += 1; prev_count = curr_count; # Till now we have covered # 'prev_count' numbers # Finding ith digit at ith place for i in range (1, len + 1): # j = 1 means 2 j = 2 # means ...j = 4 means 7 for j in range(1, 5): # if prev_count + 4 ^ (len-i) # is less than n, increase # prev_count by 4^(x-i) if (prev_count + pow(4, len - i) < n): prev_count += pow(4, len - i); # else print the ith # digit and break else: if (j == 1): print("2", end = ""); else if (j == 2): print("3", end = ""); else if (j == 3): print("5", end = ""); else if (j == 4): print("7", end = ""); break; print(); # Driver Codenthprimedigitsnumber(10);nthprimedigitsnumber(21); # This code is contributed by mits // C# implementation for finding nth// number made of prime digits onlyusing System; public class GFG { // Prints n-th number where each // digit is a prime number static void nthprimedigitsnumber(long n) { // Finding the length of n-th number long len = 1; // Count of numbers with len-1 digits long prev_count = 0; while (true) { // Count of numbers with i digits long curr_count = (long)(prev_count + Math.Pow(4, len)); // if i is the length of such number // then n<4*(4^(i-1)-1)/3 and n>= 4*(4 ^ i-1)/3 // if a valid i is found break the loop if (prev_count < n && curr_count >= n) break; // check for i + 1 len++; prev_count = curr_count; } // Till now we have covered 'prev_count' numbers // Finding ith digit at ith place for (int i = 1; i <= len; i++) { // j = 1 means 2 j = 2 means ...j = 4 means 7 for (long j = 1; j <= 4; j++) { // if prev_count + 4 ^ (len-i) is less // than n, increase prev_count by 4^(x-i) if (prev_count + Math.Pow(4, len - i) < n) prev_count += (long)Math.Pow(4, len - i); // else print the ith digit and break else { if (j == 1) Console.Write("2"); else if (j == 2) Console.Write("3"); else if (j == 3) Console.Write("5"); else if (j == 4) Console.Write("7"); break; } } } Console.WriteLine(); } // Driver method public static void Main() { nthprimedigitsnumber(10); nthprimedigitsnumber(21); }} // This code is contributed by Sam007 <?php// PHP implementation for finding// nth number made of prime digits only // Prints n-th number where// each digit is a prime numberfunction nthprimedigitsnumber($n){ // Finding the length // of n-th number $len = 1; // Count of numbers // with len-1 digits $prev_count = 0; while (true) { // Count of numbers // with i digits $curr_count = $prev_count + pow(4, $len); // if i is the length of such // number then n<4*(4^(i-1)-1)/3 // and n>= 4*(4 ^ i-1)/3 if a valid // i is found break the loop if ($prev_count < $n && $curr_count >= $n) break; // check for i + 1 $len++; $prev_count = $curr_count; } // Till now we have covered // 'prev_count' numbers // Finding ith digit at ith place for ($i = 1; $i <= $len; $i++) { // j = 1 means 2 j = 2 // means ...j = 4 means 7 for ($j = 1; $j <= 4; $j++) { // if prev_count + 4 ^ (len-i) // is less than n, increase // prev_count by 4^(x-i) if ($prev_count + pow(4, $len - $i) < $n) $prev_count += pow(4, $len - $i); // else print the ith // digit and break else { if ($j == 1) echo "2"; else if ($j == 2) echo "3"; else if ($j == 3) echo "5"; else if ($j == 4) echo "7"; break; } } } echo "\n";} // Driver Codenthprimedigitsnumber(10);nthprimedigitsnumber(21); // This code is contributed by ajit?> <script> // javascript implementation for finding nth number// made of prime digits only // Prints n-th number where each digit is a// prime numberfunction nthprimedigitsnumber(n){ // Finding the length of n-th number var len = 1; // Count of numbers with len-1 digits var prev_count = 0; while (true) { // Count of numbers with i digits var curr_count = (prev_count + Math.pow(4, len)); // if i is the length of such number // then n<4*(4^(i-1)-1)/3 and n>= 4*(4 ^ i-1)/3 // if a valid i is found break the loop if (prev_count < n && curr_count >= n) break; // check for i + 1 len++; prev_count = curr_count; } // Till now we have covered 'prev_count' numbers // Finding ith digit at ith place for (var i = 1; i <= len; i++) { // j = 1 means 2 j = 2 means ...j = 4 means 7 for (var j = 1; j <= 4; j++) { // if prev_count + 4 ^ (len-i) is less // than n, increase prev_count by 4^(x-i) if (prev_count + Math.pow(4, len - i) < n) prev_count += Math.pow(4, len - i); // else print the ith digit and break else { if (j == 1) document.write("2"); else if (j == 2) document.write("3"); else if (j == 3) document.write("5"); else if (j == 4) document.write("7"); break; } } } document.write('<br>');} // Driver methodnthprimedigitsnumber(10);nthprimedigitsnumber(21); // This code is contributed by Amit Katiyar</script> Output : 33 222 Alternate Solution (Works in O(Log n) In this post, a O(log n) solution is discussed which is based on below pattern in numbers. The numbers can be seen "" / | | \ 2 3 5 7 / | | \ / | | \ / | | \ / | | \ 22 23 25 27 32 33 35 37 52 53 55 57 72 73 75 77 /||\/||\/||\/||\ /||\/||\/||\/||\ /||\/||\/||\/||\ /||\/||\/||\/||\ We can notice following : 1st. 5th, 9th. 13th, ..... numbers have 2 as last digit. 2nd. 6th, 10th. 14th, ..... numbers have 3 as last digit. 3nd. 7th, 11th. 15th, ..... numbers have 5 as last digit. 4th. 8th, 12th. 16th, ..... numbers have 7 as last digit. C++ Java Python3 C# PHP Javascript // CPP program to find n-th number with// prime digits 2, 3 and 7#include <algorithm>#include <iostream>#include <string>using namespace std; string nthprimedigitsnumber(int number){ int rem; string num; while (number) { // remainder for check element position rem = number % 4; switch (rem) { // if number is 1st position in tree case 1: num.push_back('2'); break; // if number is 2nd position in tree case 2: num.push_back('3'); break; // if number is 3rd position in tree case 3: num.push_back('5'); break; // if number is 4th position in tree case 0: num.push_back('7'); break; } if (number % 4 == 0) number--; number = number / 4; } reverse(num.begin(), num.end()); return num;} // Driver codeint main(){ int number = 21; cout << nthprimedigitsnumber(10) << "\n"; cout << nthprimedigitsnumber(21) << "\n"; return 0;} // Java program to find n-th number with// prime digits 2, 3 and 7import java.util.*;class GFG{static String nthprimedigitsnumber(int number){ int rem; String num=""; while (number>0) { // remainder for check element position rem = number % 4; switch (rem) { // if number is 1st position in tree case 1: num+='2'; break; // if number is 2nd position in tree case 2: num+='3'; break; // if number is 3rd position in tree case 3: num+='5'; break; // if number is 4th position in tree case 0: num+='7'; break; } if (number % 4 == 0) number--; number = number / 4; } return new StringBuilder(num).reverse().toString();} // Driver codepublic static void main(String[] args){ int number = 21; System.out.println(nthprimedigitsnumber(10)); System.out.println(nthprimedigitsnumber(21));}}// This code is contributed by mits # Python3 program to find n-th number# with prime digits 2, 3 and 7def nthprimedigitsnumber(number): num = ""; while (number > 0): # remainder for check element position rem = number % 4; # if number is 1st position in tree if (rem == 1): num += '2'; # if number is 2nd position in tree if (rem == 2): num += '3'; # if number is 3rd position in tree if (rem == 3): num += '5'; # if number is 4th position in tree if (rem == 0): num += '7'; if (number % 4 == 0): number = number - 1 number = number // 4; return num[::-1]; # Driver codenumber = 21;print(nthprimedigitsnumber(10));print(nthprimedigitsnumber(number)); # This code is contributed by mits // C# program to find n-th number with// prime digits 2, 3 and 7using System;class GFG{static string nthprimedigitsnumber(int number){ int rem; string num=""; while (number>0) { // remainder for check element position rem = number % 4; switch (rem) { // if number is 1st position in tree case 1: num+='2'; break; // if number is 2nd position in tree case 2: num+='3'; break; // if number is 3rd position in tree case 3: num+='5'; break; // if number is 4th position in tree case 0: num+='7'; break; } if (number % 4 == 0) number--; number = number / 4; } char[] st = num.ToCharArray(); Array.Reverse(st); return new string(st);} // Driver codestatic void Main(){ int number = 21; Console.WriteLine(nthprimedigitsnumber(10)); Console.WriteLine(nthprimedigitsnumber(number));}}// This code is contributed by mits <?php// PHP program to find n-th number with// prime digits 2, 3 and 7 function nthprimedigitsnumber($number){ $num = ""; while ($number > 0) { // remainder for check element position $rem = $number % 4; switch ($rem) { // if number is 1st position in tree case 1: $num .= '2'; break; // if number is 2nd position in tree case 2: $num .= '3'; break; // if number is 3rd position in tree case 3: $num .= '5'; break; // if number is 4th position in tree case 0: $num .= '7'; break; } if ($number % 4 == 0) $number--; $number = (int)($number / 4); } return strrev($num);} // Driver code$number = 21;print(nthprimedigitsnumber(10) . "\n");print(nthprimedigitsnumber($number)); // This code is contributed by mits <script> // Javascript program to find n-th number with prime digits 2, 3 and 7 function nthprimedigitsnumber(number) { let rem; let num=""; while (number>0) { // remainder for check element position rem = number % 4; switch (rem) { // if number is 1st position in tree case 1: num+='2'; break; // if number is 2nd position in tree case 2: num+='3'; break; // if number is 3rd position in tree case 3: num+='5'; break; // if number is 4th position in tree case 0: num+='7'; break; } if (number % 4 == 0) number--; number = parseInt(number / 4, 10); } let st = num.split(''); st.reverse(); return (st.join("")); } let number = 21; document.write(nthprimedigitsnumber(10) + "</br>"); document.write(nthprimedigitsnumber(number)); </script> Output : 33 222 This article is contributed by Ayush Jha and Devanshu agarwal. 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. Sam007 jit_t Mithun Kumar Abhishek_Vashisht one96 suresh07 amit143katiyar arorakashish0911 simmytarika5 Prime Number Arrays Mathematical Arrays Mathematical Prime Number 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 Linear Search Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Linked List vs Array Program for Fibonacci numbers Write a program to print all permutations of a given string C++ Data Types Set in C++ Standard Template Library (STL) Coin Change | DP-7
[ { "code": null, "e": 24397, "s": 24369, "text": "\n11 Mar, 2022" }, { "code": null, "e": 24670, "s": 24397, "text": "Given a number ‘n’, we need to find the nth number whose each digit is a prime number i.e 2, 3, 5, 7....In other words you have to find nth number of this sequence. 2, 3, 5, 5, 22, 23...... Given that the nth number such found will be less then equal to 10^18 Examples : " }, { "code": null, "e": 24774, "s": 24670, "text": "Input : 10\nOutput : 33\n 2, 3, 5, 7, 22, 23, 25, \n 27, 32, 33\n\nInput : 21\nOutput : 222" }, { "code": null, "e": 25188, "s": 24776, "text": "There are four prime digits 2, 3, 5 and 7. First observation is that the number of numbers of x length and made of prime digits are because for each position you have 4 choices so total number is 4^x. So total count of such numbers whose length is = 1 to len (i.e. 2 or 3 or more) will be 4*((4len – 1)/3). (This is sum of G.P with first term 4 and common ratio 4)The algorithm is mainly divided in two steps. " }, { "code": null, "e": 26216, "s": 25188, "text": "We find the number of digits in n-th number using above observation. We start from len = 0 and keep incrementing it while value of it is smaller than 4*((4len – 1)/3).Now we know number of digits in n-th number. We also know the count of numbers with with (len-1) digits. Let this count be ‘prev_count’. Now we one by one find digits in our result. First fix 2 at i-th place (assuming all the places upto i-1 are already filled), we have 4^(len – i) numbers possible and to check if 2 is the right candidate or not check if count of numbers after putting 2 is greater than or equal to n or not. If it is true then 2 is the right candidate if this is not true this means if we fix 2 at ith place only prev_count + 4^(len-i) numbers can be covered. So increase prev_count by 4^(len-i) and repeat this step for 3 check if 3 fits at ith place or not .If not go for 5. If 5 also does not fit, go for 7. It is guaranteed that 7 will fit it if 2, 3 and 5 do not fit, because we are sure that the length of nth such number is len only." }, { "code": null, "e": 26384, "s": 26216, "text": "We find the number of digits in n-th number using above observation. We start from len = 0 and keep incrementing it while value of it is smaller than 4*((4len – 1)/3)." }, { "code": null, "e": 27245, "s": 26384, "text": "Now we know number of digits in n-th number. We also know the count of numbers with with (len-1) digits. Let this count be ‘prev_count’. Now we one by one find digits in our result. First fix 2 at i-th place (assuming all the places upto i-1 are already filled), we have 4^(len – i) numbers possible and to check if 2 is the right candidate or not check if count of numbers after putting 2 is greater than or equal to n or not. If it is true then 2 is the right candidate if this is not true this means if we fix 2 at ith place only prev_count + 4^(len-i) numbers can be covered. So increase prev_count by 4^(len-i) and repeat this step for 3 check if 3 fits at ith place or not .If not go for 5. If 5 also does not fit, go for 7. It is guaranteed that 7 will fit it if 2, 3 and 5 do not fit, because we are sure that the length of nth such number is len only." }, { "code": null, "e": 27287, "s": 27245, "text": "Below is implementation of above steps. " }, { "code": null, "e": 27291, "s": 27287, "text": "C++" }, { "code": null, "e": 27296, "s": 27291, "text": "Java" }, { "code": null, "e": 27304, "s": 27296, "text": "Python3" }, { "code": null, "e": 27307, "s": 27304, "text": "C#" }, { "code": null, "e": 27311, "s": 27307, "text": "PHP" }, { "code": null, "e": 27322, "s": 27311, "text": "Javascript" }, { "code": "// C++ implementation for finding nth number// made of prime digits only#include <bits/stdc++.h>using namespace std; // Prints n-th number where each digit is a// prime numbervoid nthprimedigitsnumber(long long n){ // Finding the length of n-th number long long len = 1; // Count of numbers with len-1 digits long long prev_count = 0; while (true) { // Count of numbers with i digits long long curr_count = prev_count + pow(4, len); // if i is the length of such number // then n<4*(4^(i-1)-1)/3 and n>= 4*(4 ^ i-1)/3 // if a valid i is found break the loop if (prev_count < n && curr_count >= n) break; // check for i + 1 len++; prev_count = curr_count; } // Till now we have covered 'prev_count' numbers // Finding ith digit at ith place for (int i = 1; i <= len; i++) { // j = 1 means 2 j = 2 means ...j = 4 means 7 for (long long j = 1; j <= 4; j++) { // if prev_count + 4 ^ (len-i) is less // than n, increase prev_count by 4^(x-i) if (prev_count + pow(4, len - i) < n) prev_count += pow(4, len - i); // else print the ith digit and break else { if (j == 1) cout << \"2\"; else if (j == 2) cout << \"3\"; else if (j == 3) cout << \"5\"; else if (j == 4) cout << \"7\"; break; } } } cout << endl;} // Driver functionint main(){ nthprimedigitsnumber(10); nthprimedigitsnumber(21); return 0;}", "e": 28985, "s": 27322, "text": null }, { "code": "// Java implementation for finding nth number// made of prime digits only import static java.lang.Math.pow; class Test { // Prints n-th number where each digit is a // prime number static void nthprimedigitsnumber(long n) { // Finding the length of n-th number long len = 1; // Count of numbers with len-1 digits long prev_count = 0; while (true) { // Count of numbers with i digits long curr_count = (long)(prev_count + pow(4, len)); // if i is the length of such number // then n<4*(4^(i-1)-1)/3 and n>= 4*(4 ^ i-1)/3 // if a valid i is found break the loop if (prev_count < n && curr_count >= n) break; // check for i + 1 len++; prev_count = curr_count; } // Till now we have covered 'prev_count' numbers // Finding ith digit at ith place for (int i = 1; i <= len; i++) { // j = 1 means 2 j = 2 means ...j = 4 means 7 for (long j = 1; j <= 4; j++) { // if prev_count + 4 ^ (len-i) is less // than n, increase prev_count by 4^(x-i) if (prev_count + pow(4, len - i) < n) prev_count += pow(4, len - i); // else print the ith digit and break else { if (j == 1) System.out.print(\"2\"); else if (j == 2) System.out.print(\"3\"); else if (j == 3) System.out.print(\"5\"); else if (j == 4) System.out.print(\"7\"); break; } } } System.out.println(); } // Driver method public static void main(String args[]) { nthprimedigitsnumber(10); nthprimedigitsnumber(21); }}", "e": 30908, "s": 28985, "text": null }, { "code": "# Python3 implementation for# finding nth number made of# prime digits onlyimport math # Prints n-th number where# each digit is a prime numberdef nthprimedigitsnumber(n): # Finding the length # of n-th number len = 1; # Count of numbers # with len-1 digits prev_count = 0; while(1): # Count of numbers # with i digits curr_count = (prev_count + math.pow(4, len)); # if i is the length of such # number then n<4*(4^(i-1)-1)/3 # and n>= 4*(4 ^ i-1)/3 if a valid # i is found break the loop if (prev_count < n and curr_count >= n): break; # check for i + 1 len += 1; prev_count = curr_count; # Till now we have covered # 'prev_count' numbers # Finding ith digit at ith place for i in range (1, len + 1): # j = 1 means 2 j = 2 # means ...j = 4 means 7 for j in range(1, 5): # if prev_count + 4 ^ (len-i) # is less than n, increase # prev_count by 4^(x-i) if (prev_count + pow(4, len - i) < n): prev_count += pow(4, len - i); # else print the ith # digit and break else: if (j == 1): print(\"2\", end = \"\"); else if (j == 2): print(\"3\", end = \"\"); else if (j == 3): print(\"5\", end = \"\"); else if (j == 4): print(\"7\", end = \"\"); break; print(); # Driver Codenthprimedigitsnumber(10);nthprimedigitsnumber(21); # This code is contributed by mits", "e": 32608, "s": 30908, "text": null }, { "code": "// C# implementation for finding nth// number made of prime digits onlyusing System; public class GFG { // Prints n-th number where each // digit is a prime number static void nthprimedigitsnumber(long n) { // Finding the length of n-th number long len = 1; // Count of numbers with len-1 digits long prev_count = 0; while (true) { // Count of numbers with i digits long curr_count = (long)(prev_count + Math.Pow(4, len)); // if i is the length of such number // then n<4*(4^(i-1)-1)/3 and n>= 4*(4 ^ i-1)/3 // if a valid i is found break the loop if (prev_count < n && curr_count >= n) break; // check for i + 1 len++; prev_count = curr_count; } // Till now we have covered 'prev_count' numbers // Finding ith digit at ith place for (int i = 1; i <= len; i++) { // j = 1 means 2 j = 2 means ...j = 4 means 7 for (long j = 1; j <= 4; j++) { // if prev_count + 4 ^ (len-i) is less // than n, increase prev_count by 4^(x-i) if (prev_count + Math.Pow(4, len - i) < n) prev_count += (long)Math.Pow(4, len - i); // else print the ith digit and break else { if (j == 1) Console.Write(\"2\"); else if (j == 2) Console.Write(\"3\"); else if (j == 3) Console.Write(\"5\"); else if (j == 4) Console.Write(\"7\"); break; } } } Console.WriteLine(); } // Driver method public static void Main() { nthprimedigitsnumber(10); nthprimedigitsnumber(21); }} // This code is contributed by Sam007", "e": 34624, "s": 32608, "text": null }, { "code": "<?php// PHP implementation for finding// nth number made of prime digits only // Prints n-th number where// each digit is a prime numberfunction nthprimedigitsnumber($n){ // Finding the length // of n-th number $len = 1; // Count of numbers // with len-1 digits $prev_count = 0; while (true) { // Count of numbers // with i digits $curr_count = $prev_count + pow(4, $len); // if i is the length of such // number then n<4*(4^(i-1)-1)/3 // and n>= 4*(4 ^ i-1)/3 if a valid // i is found break the loop if ($prev_count < $n && $curr_count >= $n) break; // check for i + 1 $len++; $prev_count = $curr_count; } // Till now we have covered // 'prev_count' numbers // Finding ith digit at ith place for ($i = 1; $i <= $len; $i++) { // j = 1 means 2 j = 2 // means ...j = 4 means 7 for ($j = 1; $j <= 4; $j++) { // if prev_count + 4 ^ (len-i) // is less than n, increase // prev_count by 4^(x-i) if ($prev_count + pow(4, $len - $i) < $n) $prev_count += pow(4, $len - $i); // else print the ith // digit and break else { if ($j == 1) echo \"2\"; else if ($j == 2) echo \"3\"; else if ($j == 3) echo \"5\"; else if ($j == 4) echo \"7\"; break; } } } echo \"\\n\";} // Driver Codenthprimedigitsnumber(10);nthprimedigitsnumber(21); // This code is contributed by ajit?>", "e": 36364, "s": 34624, "text": null }, { "code": "<script> // javascript implementation for finding nth number// made of prime digits only // Prints n-th number where each digit is a// prime numberfunction nthprimedigitsnumber(n){ // Finding the length of n-th number var len = 1; // Count of numbers with len-1 digits var prev_count = 0; while (true) { // Count of numbers with i digits var curr_count = (prev_count + Math.pow(4, len)); // if i is the length of such number // then n<4*(4^(i-1)-1)/3 and n>= 4*(4 ^ i-1)/3 // if a valid i is found break the loop if (prev_count < n && curr_count >= n) break; // check for i + 1 len++; prev_count = curr_count; } // Till now we have covered 'prev_count' numbers // Finding ith digit at ith place for (var i = 1; i <= len; i++) { // j = 1 means 2 j = 2 means ...j = 4 means 7 for (var j = 1; j <= 4; j++) { // if prev_count + 4 ^ (len-i) is less // than n, increase prev_count by 4^(x-i) if (prev_count + Math.pow(4, len - i) < n) prev_count += Math.pow(4, len - i); // else print the ith digit and break else { if (j == 1) document.write(\"2\"); else if (j == 2) document.write(\"3\"); else if (j == 3) document.write(\"5\"); else if (j == 4) document.write(\"7\"); break; } } } document.write('<br>');} // Driver methodnthprimedigitsnumber(10);nthprimedigitsnumber(21); // This code is contributed by Amit Katiyar</script>", "e": 38047, "s": 36364, "text": null }, { "code": null, "e": 38058, "s": 38047, "text": "Output : " }, { "code": null, "e": 38065, "s": 38058, "text": "33\n222" }, { "code": null, "e": 38104, "s": 38065, "text": "Alternate Solution (Works in O(Log n) " }, { "code": null, "e": 38859, "s": 38104, "text": "In this post, a O(log n) solution is discussed \nwhich is based on below pattern in numbers. The \nnumbers can be seen\n \"\"\n / | | \\\n 2 3 5 7\n / | | \\ / | | \\ / | | \\ / | | \\ \n22 23 25 27 32 33 35 37 52 53 55 57 72 73 75 77\n/||\\/||\\/||\\/||\\ /||\\/||\\/||\\/||\\ /||\\/||\\/||\\/||\\ /||\\/||\\/||\\/||\\\n\nWe can notice following :\n1st. 5th, 9th. 13th, ..... numbers have 2 as last digit.\n2nd. 6th, 10th. 14th, ..... numbers have 3 as last digit.\n3nd. 7th, 11th. 15th, ..... numbers have 5 as last digit.\n4th. 8th, 12th. 16th, ..... numbers have 7 as last digit." }, { "code": null, "e": 38865, "s": 38861, "text": "C++" }, { "code": null, "e": 38870, "s": 38865, "text": "Java" }, { "code": null, "e": 38878, "s": 38870, "text": "Python3" }, { "code": null, "e": 38881, "s": 38878, "text": "C#" }, { "code": null, "e": 38885, "s": 38881, "text": "PHP" }, { "code": null, "e": 38896, "s": 38885, "text": "Javascript" }, { "code": "// CPP program to find n-th number with// prime digits 2, 3 and 7#include <algorithm>#include <iostream>#include <string>using namespace std; string nthprimedigitsnumber(int number){ int rem; string num; while (number) { // remainder for check element position rem = number % 4; switch (rem) { // if number is 1st position in tree case 1: num.push_back('2'); break; // if number is 2nd position in tree case 2: num.push_back('3'); break; // if number is 3rd position in tree case 3: num.push_back('5'); break; // if number is 4th position in tree case 0: num.push_back('7'); break; } if (number % 4 == 0) number--; number = number / 4; } reverse(num.begin(), num.end()); return num;} // Driver codeint main(){ int number = 21; cout << nthprimedigitsnumber(10) << \"\\n\"; cout << nthprimedigitsnumber(21) << \"\\n\"; return 0;}", "e": 39950, "s": 38896, "text": null }, { "code": "// Java program to find n-th number with// prime digits 2, 3 and 7import java.util.*;class GFG{static String nthprimedigitsnumber(int number){ int rem; String num=\"\"; while (number>0) { // remainder for check element position rem = number % 4; switch (rem) { // if number is 1st position in tree case 1: num+='2'; break; // if number is 2nd position in tree case 2: num+='3'; break; // if number is 3rd position in tree case 3: num+='5'; break; // if number is 4th position in tree case 0: num+='7'; break; } if (number % 4 == 0) number--; number = number / 4; } return new StringBuilder(num).reverse().toString();} // Driver codepublic static void main(String[] args){ int number = 21; System.out.println(nthprimedigitsnumber(10)); System.out.println(nthprimedigitsnumber(21));}}// This code is contributed by mits", "e": 40996, "s": 39950, "text": null }, { "code": "# Python3 program to find n-th number# with prime digits 2, 3 and 7def nthprimedigitsnumber(number): num = \"\"; while (number > 0): # remainder for check element position rem = number % 4; # if number is 1st position in tree if (rem == 1): num += '2'; # if number is 2nd position in tree if (rem == 2): num += '3'; # if number is 3rd position in tree if (rem == 3): num += '5'; # if number is 4th position in tree if (rem == 0): num += '7'; if (number % 4 == 0): number = number - 1 number = number // 4; return num[::-1]; # Driver codenumber = 21;print(nthprimedigitsnumber(10));print(nthprimedigitsnumber(number)); # This code is contributed by mits", "e": 41820, "s": 40996, "text": null }, { "code": "// C# program to find n-th number with// prime digits 2, 3 and 7using System;class GFG{static string nthprimedigitsnumber(int number){ int rem; string num=\"\"; while (number>0) { // remainder for check element position rem = number % 4; switch (rem) { // if number is 1st position in tree case 1: num+='2'; break; // if number is 2nd position in tree case 2: num+='3'; break; // if number is 3rd position in tree case 3: num+='5'; break; // if number is 4th position in tree case 0: num+='7'; break; } if (number % 4 == 0) number--; number = number / 4; } char[] st = num.ToCharArray(); Array.Reverse(st); return new string(st);} // Driver codestatic void Main(){ int number = 21; Console.WriteLine(nthprimedigitsnumber(10)); Console.WriteLine(nthprimedigitsnumber(number));}}// This code is contributed by mits", "e": 42862, "s": 41820, "text": null }, { "code": "<?php// PHP program to find n-th number with// prime digits 2, 3 and 7 function nthprimedigitsnumber($number){ $num = \"\"; while ($number > 0) { // remainder for check element position $rem = $number % 4; switch ($rem) { // if number is 1st position in tree case 1: $num .= '2'; break; // if number is 2nd position in tree case 2: $num .= '3'; break; // if number is 3rd position in tree case 3: $num .= '5'; break; // if number is 4th position in tree case 0: $num .= '7'; break; } if ($number % 4 == 0) $number--; $number = (int)($number / 4); } return strrev($num);} // Driver code$number = 21;print(nthprimedigitsnumber(10) . \"\\n\");print(nthprimedigitsnumber($number)); // This code is contributed by mits", "e": 43871, "s": 42862, "text": null }, { "code": "<script> // Javascript program to find n-th number with prime digits 2, 3 and 7 function nthprimedigitsnumber(number) { let rem; let num=\"\"; while (number>0) { // remainder for check element position rem = number % 4; switch (rem) { // if number is 1st position in tree case 1: num+='2'; break; // if number is 2nd position in tree case 2: num+='3'; break; // if number is 3rd position in tree case 3: num+='5'; break; // if number is 4th position in tree case 0: num+='7'; break; } if (number % 4 == 0) number--; number = parseInt(number / 4, 10); } let st = num.split(''); st.reverse(); return (st.join(\"\")); } let number = 21; document.write(nthprimedigitsnumber(10) + \"</br>\"); document.write(nthprimedigitsnumber(number)); </script>", "e": 44982, "s": 43871, "text": null }, { "code": null, "e": 44993, "s": 44982, "text": "Output : " }, { "code": null, "e": 45000, "s": 44993, "text": "33\n222" }, { "code": null, "e": 45439, "s": 45000, "text": "This article is contributed by Ayush Jha and Devanshu agarwal. 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": 45446, "s": 45439, "text": "Sam007" }, { "code": null, "e": 45452, "s": 45446, "text": "jit_t" }, { "code": null, "e": 45465, "s": 45452, "text": "Mithun Kumar" }, { "code": null, "e": 45483, "s": 45465, "text": "Abhishek_Vashisht" }, { "code": null, "e": 45489, "s": 45483, "text": "one96" }, { "code": null, "e": 45498, "s": 45489, "text": "suresh07" }, { "code": null, "e": 45513, "s": 45498, "text": "amit143katiyar" }, { "code": null, "e": 45530, "s": 45513, "text": "arorakashish0911" }, { "code": null, "e": 45543, "s": 45530, "text": "simmytarika5" }, { "code": null, "e": 45556, "s": 45543, "text": "Prime Number" }, { "code": null, "e": 45563, "s": 45556, "text": "Arrays" }, { "code": null, "e": 45576, "s": 45563, "text": "Mathematical" }, { "code": null, "e": 45583, "s": 45576, "text": "Arrays" }, { "code": null, "e": 45596, "s": 45583, "text": "Mathematical" }, { "code": null, "e": 45609, "s": 45596, "text": "Prime Number" }, { "code": null, "e": 45707, "s": 45609, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 45716, "s": 45707, "text": "Comments" }, { "code": null, "e": 45729, "s": 45716, "text": "Old Comments" }, { "code": null, "e": 45752, "s": 45729, "text": "Introduction to Arrays" }, { "code": null, "e": 45784, "s": 45752, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 45798, "s": 45784, "text": "Linear Search" }, { "code": null, "e": 45883, "s": 45798, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 45904, "s": 45883, "text": "Linked List vs Array" }, { "code": null, "e": 45934, "s": 45904, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 45994, "s": 45934, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 46009, "s": 45994, "text": "C++ Data Types" }, { "code": null, "e": 46052, "s": 46009, "text": "Set in C++ Standard Template Library (STL)" } ]
How to Export MySQL Tables to a file from command line - onlinetutorialspoint
PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC EXCEPTIONS COLLECTIONS SWING JDBC JAVA 8 SPRING SPRING BOOT HIBERNATE PYTHON PHP JQUERY PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws Here we will see how to Export MySQL tables to a file from command line. mysqldump command helps us to export MySQL tables to a file. $ mysqldump -u [mysql_user] -p database_name > [file_path]fimename.sql $ mysqldump -u root -p otp > schema.sql It asks you to enter the MySQL password, after successful authentication, it will export all the tables schema and data of otp database to a schema.sql file. If you wanted to export only table schemas without data so that you can use –no-data option. $ mysqldump -u root -p --no-data otp > schema.sql It is also possible to export table data without table schema, using –no-create-info option. $ mysqldump -u root -p --no-create-info otp > schema.sql We can ship the selected tables into a file. $ mysqldump -u root -p otp t1,t2,t3.. > schema.sql $ mysqldump -u root -p otp department,employee > schema3.sql We can even overlook some of the tables while exporting entire schema into a single file using –ignore-table. $ mysqldump -u root -p --ignore-table=otp.employee otp > schema.sql The above command exports all the database tables except the employee table under the otp database into the schema.sql file. You can invoke mysqldump locally against a remote server, for this the only thing you have to know remote server host address. $ mysqldump -h hostname_of_the_server -u root -p otp > schema.sql mysqldump reference Happy Learning 🙂 Insert an Image using JDBC in Mysql DB Java 8 Read File Line By Line Example How to install Maven on windows 7 command line Install Mysql on Windows 10 Step by Step JDBC Connection with Properties file Java How to create Jar File ? count number of lines characters and words in a file Java How to Read CSV File in Python Hibernate 4 Example with Annotations Mysql How to Convert Python List Of Objects to CSV File How to connect MySQL Database in Eclipse MySQL Create Table Syntax Example MySQL Unique Constraint Syntax Example Spring Boot JdbcTemplate CRUD Operations Mysql Spring Boot Security MySQL Database Integration Example Insert an Image using JDBC in Mysql DB Java 8 Read File Line By Line Example How to install Maven on windows 7 command line Install Mysql on Windows 10 Step by Step JDBC Connection with Properties file Java How to create Jar File ? count number of lines characters and words in a file Java How to Read CSV File in Python Hibernate 4 Example with Annotations Mysql How to Convert Python List Of Objects to CSV File How to connect MySQL Database in Eclipse MySQL Create Table Syntax Example MySQL Unique Constraint Syntax Example Spring Boot JdbcTemplate CRUD Operations Mysql Spring Boot Security MySQL Database Integration Example Δ Install Java on Mac OS Install AWS CLI on Windows Install Minikube on Windows Install Docker Toolbox on Windows Install SOAPUI on Windows Install Gradle on Windows Install RabbitMQ on Windows Install PuTTY on windows Install Mysql on Windows Install Hibernate Tools in Eclipse Install Elasticsearch on Windows Install Maven on Windows Install Maven on Ubuntu Install Maven on Windows Command Add OJDBC jar to Maven Repository Install Ant on Windows Install RabbitMQ on Windows Install Apache Kafka on Ubuntu Install Apache Kafka on Windows
[ { "code": null, "e": 158, "s": 123, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 172, "s": 158, "text": "Java Examples" }, { "code": null, "e": 183, "s": 172, "text": "C Examples" }, { "code": null, "e": 195, "s": 183, "text": "C Tutorials" }, { "code": null, "e": 199, "s": 195, "text": "aws" }, { "code": null, "e": 234, "s": 199, "text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC" }, { "code": null, "e": 245, "s": 234, "text": "EXCEPTIONS" }, { "code": null, "e": 257, "s": 245, "text": "COLLECTIONS" }, { "code": null, "e": 263, "s": 257, "text": "SWING" }, { "code": null, "e": 268, "s": 263, "text": "JDBC" }, { "code": null, "e": 275, "s": 268, "text": "JAVA 8" }, { "code": null, "e": 282, "s": 275, "text": "SPRING" }, { "code": null, "e": 294, "s": 282, "text": "SPRING BOOT" }, { "code": null, "e": 304, "s": 294, "text": "HIBERNATE" }, { "code": null, "e": 311, "s": 304, "text": "PYTHON" }, { "code": null, "e": 315, "s": 311, "text": "PHP" }, { "code": null, "e": 322, "s": 315, "text": "JQUERY" }, { "code": null, "e": 357, "s": 322, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 371, "s": 357, "text": "Java Examples" }, { "code": null, "e": 382, "s": 371, "text": "C Examples" }, { "code": null, "e": 394, "s": 382, "text": "C Tutorials" }, { "code": null, "e": 398, "s": 394, "text": "aws" }, { "code": null, "e": 471, "s": 398, "text": "Here we will see how to Export MySQL tables to a file from command line." }, { "code": null, "e": 532, "s": 471, "text": "mysqldump command helps us to export MySQL tables to a file." }, { "code": null, "e": 603, "s": 532, "text": "$ mysqldump -u [mysql_user] -p database_name > [file_path]fimename.sql" }, { "code": null, "e": 643, "s": 603, "text": "$ mysqldump -u root -p otp > schema.sql" }, { "code": null, "e": 801, "s": 643, "text": "It asks you to enter the MySQL password, after successful authentication, it will export all the tables schema and data of otp database to a schema.sql file." }, { "code": null, "e": 894, "s": 801, "text": "If you wanted to export only table schemas without data so that you can use –no-data option." }, { "code": null, "e": 944, "s": 894, "text": "$ mysqldump -u root -p --no-data otp > schema.sql" }, { "code": null, "e": 1037, "s": 944, "text": "It is also possible to export table data without table schema, using –no-create-info option." }, { "code": null, "e": 1094, "s": 1037, "text": "$ mysqldump -u root -p --no-create-info otp > schema.sql" }, { "code": null, "e": 1139, "s": 1094, "text": "We can ship the selected tables into a file." }, { "code": null, "e": 1190, "s": 1139, "text": "$ mysqldump -u root -p otp t1,t2,t3.. > schema.sql" }, { "code": null, "e": 1251, "s": 1190, "text": "$ mysqldump -u root -p otp department,employee > schema3.sql" }, { "code": null, "e": 1362, "s": 1251, "text": "We can even overlook some of the tables while exporting entire schema into a single file using –ignore-table." }, { "code": null, "e": 1430, "s": 1362, "text": "$ mysqldump -u root -p --ignore-table=otp.employee otp > schema.sql" }, { "code": null, "e": 1555, "s": 1430, "text": "The above command exports all the database tables except the employee table under the otp database into the schema.sql file." }, { "code": null, "e": 1682, "s": 1555, "text": "You can invoke mysqldump locally against a remote server, for this the only thing you have to know remote server host address." }, { "code": null, "e": 1748, "s": 1682, "text": "$ mysqldump -h hostname_of_the_server -u root -p otp > schema.sql" }, { "code": null, "e": 1768, "s": 1748, "text": "mysqldump reference" }, { "code": null, "e": 1785, "s": 1768, "text": "Happy Learning 🙂" }, { "code": null, "e": 2418, "s": 1785, "text": "\nInsert an Image using JDBC in Mysql DB\nJava 8 Read File Line By Line Example\nHow to install Maven on windows 7 command line\nInstall Mysql on Windows 10 Step by Step\nJDBC Connection with Properties file\nJava How to create Jar File ?\ncount number of lines characters and words in a file Java\nHow to Read CSV File in Python\nHibernate 4 Example with Annotations Mysql\nHow to Convert Python List Of Objects to CSV File\nHow to connect MySQL Database in Eclipse\nMySQL Create Table Syntax Example\nMySQL Unique Constraint Syntax Example\nSpring Boot JdbcTemplate CRUD Operations Mysql\nSpring Boot Security MySQL Database Integration Example\n" }, { "code": null, "e": 2457, "s": 2418, "text": "Insert an Image using JDBC in Mysql DB" }, { "code": null, "e": 2495, "s": 2457, "text": "Java 8 Read File Line By Line Example" }, { "code": null, "e": 2542, "s": 2495, "text": "How to install Maven on windows 7 command line" }, { "code": null, "e": 2583, "s": 2542, "text": "Install Mysql on Windows 10 Step by Step" }, { "code": null, "e": 2620, "s": 2583, "text": "JDBC Connection with Properties file" }, { "code": null, "e": 2650, "s": 2620, "text": "Java How to create Jar File ?" }, { "code": null, "e": 2708, "s": 2650, "text": "count number of lines characters and words in a file Java" }, { "code": null, "e": 2739, "s": 2708, "text": "How to Read CSV File in Python" }, { "code": null, "e": 2782, "s": 2739, "text": "Hibernate 4 Example with Annotations Mysql" }, { "code": null, "e": 2832, "s": 2782, "text": "How to Convert Python List Of Objects to CSV File" }, { "code": null, "e": 2873, "s": 2832, "text": "How to connect MySQL Database in Eclipse" }, { "code": null, "e": 2907, "s": 2873, "text": "MySQL Create Table Syntax Example" }, { "code": null, "e": 2946, "s": 2907, "text": "MySQL Unique Constraint Syntax Example" }, { "code": null, "e": 2993, "s": 2946, "text": "Spring Boot JdbcTemplate CRUD Operations Mysql" }, { "code": null, "e": 3049, "s": 2993, "text": "Spring Boot Security MySQL Database Integration Example" }, { "code": null, "e": 3055, "s": 3053, "text": "Δ" }, { "code": null, "e": 3079, "s": 3055, "text": " Install Java on Mac OS" }, { "code": null, "e": 3107, "s": 3079, "text": " Install AWS CLI on Windows" }, { "code": null, "e": 3136, "s": 3107, "text": " Install Minikube on Windows" }, { "code": null, "e": 3171, "s": 3136, "text": " Install Docker Toolbox on Windows" }, { "code": null, "e": 3198, "s": 3171, "text": " Install SOAPUI on Windows" }, { "code": null, "e": 3225, "s": 3198, "text": " Install Gradle on Windows" }, { "code": null, "e": 3254, "s": 3225, "text": " Install RabbitMQ on Windows" }, { "code": null, "e": 3280, "s": 3254, "text": " Install PuTTY on windows" }, { "code": null, "e": 3306, "s": 3280, "text": " Install Mysql on Windows" }, { "code": null, "e": 3342, "s": 3306, "text": " Install Hibernate Tools in Eclipse" }, { "code": null, "e": 3376, "s": 3342, "text": " Install Elasticsearch on Windows" }, { "code": null, "e": 3402, "s": 3376, "text": " Install Maven on Windows" }, { "code": null, "e": 3427, "s": 3402, "text": " Install Maven on Ubuntu" }, { "code": null, "e": 3461, "s": 3427, "text": " Install Maven on Windows Command" }, { "code": null, "e": 3496, "s": 3461, "text": " Add OJDBC jar to Maven Repository" }, { "code": null, "e": 3520, "s": 3496, "text": " Install Ant on Windows" }, { "code": null, "e": 3549, "s": 3520, "text": " Install RabbitMQ on Windows" }, { "code": null, "e": 3581, "s": 3549, "text": " Install Apache Kafka on Ubuntu" } ]
Number of ways to cut a stick of length N into K pieces - GeeksforGeeks
03 Dec, 2021 Given a stick of size N, find the number of ways in which it can be cut into K pieces such that length of every piece is greater than 0. Examples : Input : N = 5 K = 2 Output : 4 Input : N = 15 K = 5 Output : 1001 Solving this question is equivalent to solving the mathematics equation x1 + x2 + ..... + xK = N We can solve this by using the bars and stars method in Combinatorics, from which we obtain the fact that the number of positive integral solutions to this equation is (N – 1)C(K – 1), where NCK is N! / ((N – K) ! * (K!)), where ! stands for factorial.In C++ and Java, for large values of factorials, there might be overflow errors. In that case we can introduce a large prime number such as 107 + 7 to mod the answer. We can calculate nCr % p by using Lucas Theorem. However, python can handle large values without overflow. C++ Java Python3 C# PHP Javascript // C++ program to calculate the number of ways// to divide a stick of length n into k pieces#include <bits/stdc++.h>using namespace std; // function to generate nCk or nChoosekunsigned long long nCr(unsigned long long n, unsigned long long r){ if (n < r) return 0; // Reduces to the form n! / n! if (r == 0) return 1; // nCr has been simplified to this form by // expanding numerator and denominator to // the form n(n - 1)(n - 2)...(n - r + 1) // ----------------------------- // (r!) // in the above equation, (n - r)! is cancelled // out in the numerator and denominator unsigned long long numerator = 1; for (int i = n; i > n - r; i--) numerator = (numerator * i); unsigned long long denominator = 1; for (int i = 1; i < r + 1; i++) denominator = (denominator * i); return (numerator / denominator);} // Returns number of ways to cut// a rod of length N into K pieces.unsigned long long countWays(unsigned long long N, unsigned long long K){ return nCr(N - 1, K - 1);} // Driver codeint main(){ unsigned long long N = 5; unsigned long long K = 2; cout << countWays(N, K); return 0;} // Java program to find the number of ways in which// a stick of length n can be divided into K piecesimport java.io.*;import java.util.*; class GFG{ // function to generate nCk or nChoosek public static int nCr(int n, int r) { if (n < r) return 0; // Reduces to the form n! / n! if (r == 0) return 1; // nCr has been simplified to this form by // expanding numerator and denominator to // the form n(n - 1)(n - 2)...(n - r + 1) // ----------------------------- // (r!) // in the above equation, (n-r)! is cancelled // out in the numerator and denominator int numerator = 1; for (int i = n ; i > n - r ; i--) numerator = (numerator * i); int denominator = 1; for (int i = 1 ; i < r + 1 ; i++) denominator = (denominator * i); return (numerator / denominator); } // Returns number of ways to cut // a rod of length N into K pieces public static int countWays(int N, int K) { return nCr(N - 1, K - 1); } public static void main(String[] args) { int N = 5; int K = 2; System.out.println(countWays(N, K)); }} # Python program to find the number# of ways in which a stick of length# n can be divided into K pieces # function to generate nCk or nChoosekdef nCr(n, r): if (n < r): return 0 # reduces to the form n! / n! if (r == 0): return 1 # nCr has been simplified to this form by # expanding numerator and denominator to # the form n(n - 1)(n - 2)...(n - r + 1) # ----------------------------- # (r!) # in the above equation, (n-r)! is cancelled # out in the numerator and denominator numerator = 1 for i in range(n, n - r, -1): numerator = numerator * i denominator = 1 for i in range(1, r + 1): denominator = denominator * i return (numerator // denominator) # Returns number of ways to cut# a rod of length N into K pieces.def countWays(N, K) : return nCr(N - 1, K - 1); # Driver codeN = 5K = 2print(countWays(N, K)) // C# program to find the number of// ways in which a stick of length n// can be divided into K piecesusing System; class GFG{ // function to generate nCk or nChoosek public static int nCr(int n, int r) { if (n < r) return 0; // Reduces to the form n! / n! if (r == 0) return 1; // nCr has been simplified to this form by // expanding numerator and denominator to // the form n(n - 1)(n - 2)...(n - r + 1) // ----------------------------- // (r!) // in the above equation, (n-r)! is cancelled // out in the numerator and denominator int numerator = 1; for (int i = n; i > n - r; i--) numerator = (numerator * i); int denominator = 1; for (int i = 1; i < r + 1; i++) denominator = (denominator * i); return (numerator / denominator); } // Returns number of ways to cut // a rod of length N into K pieces public static int countWays(int N, int K) { return nCr(N - 1, K - 1); } public static void Main() { int N = 5; int K = 2; Console.Write(countWays(N, K)); }} // This code is contributed by nitin mittal. <?php// PHP program to calculate the// number of ways to divide a// stick of length n into k pieces // function to generate nCk or nChoosekfunction nCr($n, $r){ if ($n < $r) return 0; // Reduces to the form n! / n! if ($r == 0) return 1; // nCr has been simplified to this form by // expanding numerator and denominator to // the form n(n - 1)(n - 2)...(n - r + 1) // ----------------------------- // (r!) // in the above equation, (n - r)! is cancelled // out in the numerator and denominator $numerator = 1; for ($i = $n; $i > $n - $r; $i--) $numerator = ($numerator * $i); $denominator = 1; for ($i = 1; $i < $r + 1; $i++) $denominator = ($denominator * $i); return (floor($numerator / $denominator));} // Returns number of ways to cut// a rod of length N into K pieces.function countWays($N, $K){ return nCr($N - 1, $K - 1);} // Driver code$N = 5;$K = 2;echo countWays($N, $K);return 0; // This code is contributed by nitin mittal.?> <script>//Javascript Implementation// to calculate the number of ways// to divide a stick of length n into k pieces // function to generate nCk or nChoosekfunction nCr(n,r){ if (n < r) return 0; // Reduces to the form n! / n! if (r == 0) return 1; // nCr has been simplified to this form by // expanding numerator and denominator to // the form n(n - 1)(n - 2)...(n - r + 1) // ----------------------------- // (r!) // in the above equation, (n - r)! is cancelled // out in the numerator and denominator var numerator = 1; for (var i = n; i > n - r; i--) numerator = (numerator * i); var denominator = 1; for (var i = 1; i < r + 1; i++) denominator = (denominator * i); return Math.floor(numerator / denominator);} // Returns number of ways to cut// a rod of length N into K pieces.function countWays(N,K){ return nCr(N - 1, K - 1);} // Driver codevar N = 5;var K = 2;document.write(countWays(N, K)); // This code is contributed by shubhamsingh10</script> Output : 4 Exercise : Extend the above problem with 0 length pieces allowed. Hint : The number of solutions can similarly be found by writing each xi as yi – 1, and we get an equation y1 + y2 + ..... + yK = N + K. The number of solutions to this equation is (N + K – 1)C(K – 1)This article is contributed by Deepak Srivatsav. 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 Akanksha_Rai SHUBHAMSINGH10 simmytarika5 Combinatorial Combinatorial Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Find the Number of Permutations that satisfy the given condition in an array Split array into subarrays at minimum cost by minimizing count of repeating elements in each subarray Ways to sum to N using Natural Numbers up to K with repetitions allowed Largest substring with same Characters Combinations with repetitions Generate all possible combinations of at most X characters from a given array Combinations from n arrays picking one element from each array Given number of matches played, find number of teams in tournament Combinations in a String of Digits Number of Simple Graph with N Vertices and M Edges
[ { "code": null, "e": 25087, "s": 25059, "text": "\n03 Dec, 2021" }, { "code": null, "e": 25224, "s": 25087, "text": "Given a stick of size N, find the number of ways in which it can be cut into K pieces such that length of every piece is greater than 0." }, { "code": null, "e": 25236, "s": 25224, "text": "Examples : " }, { "code": null, "e": 25275, "s": 25236, "text": "Input : N = 5\n K = 2\nOutput : 4" }, { "code": null, "e": 25318, "s": 25275, "text": "Input : N = 15\n K = 5\nOutput : 1001" }, { "code": null, "e": 25941, "s": 25318, "text": "Solving this question is equivalent to solving the mathematics equation x1 + x2 + ..... + xK = N We can solve this by using the bars and stars method in Combinatorics, from which we obtain the fact that the number of positive integral solutions to this equation is (N – 1)C(K – 1), where NCK is N! / ((N – K) ! * (K!)), where ! stands for factorial.In C++ and Java, for large values of factorials, there might be overflow errors. In that case we can introduce a large prime number such as 107 + 7 to mod the answer. We can calculate nCr % p by using Lucas Theorem. However, python can handle large values without overflow." }, { "code": null, "e": 25945, "s": 25941, "text": "C++" }, { "code": null, "e": 25950, "s": 25945, "text": "Java" }, { "code": null, "e": 25958, "s": 25950, "text": "Python3" }, { "code": null, "e": 25961, "s": 25958, "text": "C#" }, { "code": null, "e": 25965, "s": 25961, "text": "PHP" }, { "code": null, "e": 25976, "s": 25965, "text": "Javascript" }, { "code": "// C++ program to calculate the number of ways// to divide a stick of length n into k pieces#include <bits/stdc++.h>using namespace std; // function to generate nCk or nChoosekunsigned long long nCr(unsigned long long n, unsigned long long r){ if (n < r) return 0; // Reduces to the form n! / n! if (r == 0) return 1; // nCr has been simplified to this form by // expanding numerator and denominator to // the form n(n - 1)(n - 2)...(n - r + 1) // ----------------------------- // (r!) // in the above equation, (n - r)! is cancelled // out in the numerator and denominator unsigned long long numerator = 1; for (int i = n; i > n - r; i--) numerator = (numerator * i); unsigned long long denominator = 1; for (int i = 1; i < r + 1; i++) denominator = (denominator * i); return (numerator / denominator);} // Returns number of ways to cut// a rod of length N into K pieces.unsigned long long countWays(unsigned long long N, unsigned long long K){ return nCr(N - 1, K - 1);} // Driver codeint main(){ unsigned long long N = 5; unsigned long long K = 2; cout << countWays(N, K); return 0;}", "e": 27244, "s": 25976, "text": null }, { "code": "// Java program to find the number of ways in which// a stick of length n can be divided into K piecesimport java.io.*;import java.util.*; class GFG{ // function to generate nCk or nChoosek public static int nCr(int n, int r) { if (n < r) return 0; // Reduces to the form n! / n! if (r == 0) return 1; // nCr has been simplified to this form by // expanding numerator and denominator to // the form n(n - 1)(n - 2)...(n - r + 1) // ----------------------------- // (r!) // in the above equation, (n-r)! is cancelled // out in the numerator and denominator int numerator = 1; for (int i = n ; i > n - r ; i--) numerator = (numerator * i); int denominator = 1; for (int i = 1 ; i < r + 1 ; i++) denominator = (denominator * i); return (numerator / denominator); } // Returns number of ways to cut // a rod of length N into K pieces public static int countWays(int N, int K) { return nCr(N - 1, K - 1); } public static void main(String[] args) { int N = 5; int K = 2; System.out.println(countWays(N, K)); }}", "e": 28507, "s": 27244, "text": null }, { "code": "# Python program to find the number# of ways in which a stick of length# n can be divided into K pieces # function to generate nCk or nChoosekdef nCr(n, r): if (n < r): return 0 # reduces to the form n! / n! if (r == 0): return 1 # nCr has been simplified to this form by # expanding numerator and denominator to # the form n(n - 1)(n - 2)...(n - r + 1) # ----------------------------- # (r!) # in the above equation, (n-r)! is cancelled # out in the numerator and denominator numerator = 1 for i in range(n, n - r, -1): numerator = numerator * i denominator = 1 for i in range(1, r + 1): denominator = denominator * i return (numerator // denominator) # Returns number of ways to cut# a rod of length N into K pieces.def countWays(N, K) : return nCr(N - 1, K - 1); # Driver codeN = 5K = 2print(countWays(N, K))", "e": 29442, "s": 28507, "text": null }, { "code": "// C# program to find the number of// ways in which a stick of length n// can be divided into K piecesusing System; class GFG{ // function to generate nCk or nChoosek public static int nCr(int n, int r) { if (n < r) return 0; // Reduces to the form n! / n! if (r == 0) return 1; // nCr has been simplified to this form by // expanding numerator and denominator to // the form n(n - 1)(n - 2)...(n - r + 1) // ----------------------------- // (r!) // in the above equation, (n-r)! is cancelled // out in the numerator and denominator int numerator = 1; for (int i = n; i > n - r; i--) numerator = (numerator * i); int denominator = 1; for (int i = 1; i < r + 1; i++) denominator = (denominator * i); return (numerator / denominator); } // Returns number of ways to cut // a rod of length N into K pieces public static int countWays(int N, int K) { return nCr(N - 1, K - 1); } public static void Main() { int N = 5; int K = 2; Console.Write(countWays(N, K)); }} // This code is contributed by nitin mittal.", "e": 30710, "s": 29442, "text": null }, { "code": "<?php// PHP program to calculate the// number of ways to divide a// stick of length n into k pieces // function to generate nCk or nChoosekfunction nCr($n, $r){ if ($n < $r) return 0; // Reduces to the form n! / n! if ($r == 0) return 1; // nCr has been simplified to this form by // expanding numerator and denominator to // the form n(n - 1)(n - 2)...(n - r + 1) // ----------------------------- // (r!) // in the above equation, (n - r)! is cancelled // out in the numerator and denominator $numerator = 1; for ($i = $n; $i > $n - $r; $i--) $numerator = ($numerator * $i); $denominator = 1; for ($i = 1; $i < $r + 1; $i++) $denominator = ($denominator * $i); return (floor($numerator / $denominator));} // Returns number of ways to cut// a rod of length N into K pieces.function countWays($N, $K){ return nCr($N - 1, $K - 1);} // Driver code$N = 5;$K = 2;echo countWays($N, $K);return 0; // This code is contributed by nitin mittal.?>", "e": 31766, "s": 30710, "text": null }, { "code": "<script>//Javascript Implementation// to calculate the number of ways// to divide a stick of length n into k pieces // function to generate nCk or nChoosekfunction nCr(n,r){ if (n < r) return 0; // Reduces to the form n! / n! if (r == 0) return 1; // nCr has been simplified to this form by // expanding numerator and denominator to // the form n(n - 1)(n - 2)...(n - r + 1) // ----------------------------- // (r!) // in the above equation, (n - r)! is cancelled // out in the numerator and denominator var numerator = 1; for (var i = n; i > n - r; i--) numerator = (numerator * i); var denominator = 1; for (var i = 1; i < r + 1; i++) denominator = (denominator * i); return Math.floor(numerator / denominator);} // Returns number of ways to cut// a rod of length N into K pieces.function countWays(N,K){ return nCr(N - 1, K - 1);} // Driver codevar N = 5;var K = 2;document.write(countWays(N, K)); // This code is contributed by shubhamsingh10</script>", "e": 32841, "s": 31766, "text": null }, { "code": null, "e": 32852, "s": 32841, "text": "Output : " }, { "code": null, "e": 32855, "s": 32852, "text": "4 " }, { "code": null, "e": 33546, "s": 32855, "text": "Exercise : Extend the above problem with 0 length pieces allowed. Hint : The number of solutions can similarly be found by writing each xi as yi – 1, and we get an equation y1 + y2 + ..... + yK = N + K. The number of solutions to this equation is (N + K – 1)C(K – 1)This article is contributed by Deepak Srivatsav. 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": 33559, "s": 33546, "text": "nitin mittal" }, { "code": null, "e": 33572, "s": 33559, "text": "Akanksha_Rai" }, { "code": null, "e": 33587, "s": 33572, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 33600, "s": 33587, "text": "simmytarika5" }, { "code": null, "e": 33614, "s": 33600, "text": "Combinatorial" }, { "code": null, "e": 33628, "s": 33614, "text": "Combinatorial" }, { "code": null, "e": 33726, "s": 33628, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33735, "s": 33726, "text": "Comments" }, { "code": null, "e": 33748, "s": 33735, "text": "Old Comments" }, { "code": null, "e": 33825, "s": 33748, "text": "Find the Number of Permutations that satisfy the given condition in an array" }, { "code": null, "e": 33927, "s": 33825, "text": "Split array into subarrays at minimum cost by minimizing count of repeating elements in each subarray" }, { "code": null, "e": 33999, "s": 33927, "text": "Ways to sum to N using Natural Numbers up to K with repetitions allowed" }, { "code": null, "e": 34038, "s": 33999, "text": "Largest substring with same Characters" }, { "code": null, "e": 34068, "s": 34038, "text": "Combinations with repetitions" }, { "code": null, "e": 34146, "s": 34068, "text": "Generate all possible combinations of at most X characters from a given array" }, { "code": null, "e": 34209, "s": 34146, "text": "Combinations from n arrays picking one element from each array" }, { "code": null, "e": 34276, "s": 34209, "text": "Given number of matches played, find number of teams in tournament" }, { "code": null, "e": 34311, "s": 34276, "text": "Combinations in a String of Digits" } ]
Add a "salt and pepper" noise to an image with Python - GeeksforGeeks
27 Oct, 2021 In this article, we are going to see how to add a “salt and pepper” noise to an image with Python. Noise: Noise means random disturbance in a signal in a computer version. In our case, the signal is an image. Random disturbance in the brightness and color of an image is called Image noise. Salt-and-pepper: It is found only in grayscale images (black and white image). As the name suggests salt (white) in pepper (black)–white spots in the dark regions or pepper (black) in salt (white)–black spots in the white regions. In other words, an image having salt-and-pepper noise will have a few dark pixels in bright regions and a few bright pixels in dark regions. Salt-and-pepper noise is also called impulse noise. It can be caused by several reasons like dead pixels, analog-to-digital conversion error, bit transmission error, etc. Let’s see how to add salt-and-pepper noise in an image – Salt-and-pepper noise can only be added in a grayscale image. So, convert an image to grayscale after reading it Randomly pick the number of pixels to which noise is added (number_of_pixels) Randomly pick some pixels in the image to which noise will be added. It can be done by randomly picking x and y coordinate Note the random values generated must be within the range of the image dimensions. The x and y coordinates must be within the range of the image size Random numbers can be generated using random number generator functions like random.randint used in the code Color some randomly picked pixels as black setting their value to 0 Color some randomly picked pixels as white setting their value to 255 Save the value of the image Below is the implementation: Python import randomimport cv2 def add_noise(img): # Getting the dimensions of the image row , col = img.shape # Randomly pick some pixels in the # image for coloring them white # Pick a random number between 300 and 10000 number_of_pixels = random.randint(300, 10000) for i in range(number_of_pixels): # Pick a random y coordinate y_coord=random.randint(0, row - 1) # Pick a random x coordinate x_coord=random.randint(0, col - 1) # Color that pixel to white img[y_coord][x_coord] = 255 # Randomly pick some pixels in # the image for coloring them black # Pick a random number between 300 and 10000 number_of_pixels = random.randint(300 , 10000) for i in range(number_of_pixels): # Pick a random y coordinate y_coord=random.randint(0, row - 1) # Pick a random x coordinate x_coord=random.randint(0, col - 1) # Color that pixel to black img[y_coord][x_coord] = 0 return img # salt-and-pepper noise can# be applied only to grayscale images# Reading the color image in grayscale imageimg = cv2.imread('lena.jpg', cv2.IMREAD_GRAYSCALE) #Storing the imagecv2.imwrite('salt-and-pepper-lena.jpg', add_noise(img)) Output: Input image: “lena.jpg” Output image: “Salt-and-pepper-lena.jpg” sooda367 Image-Processing Picked Python-OpenCV 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": "\n27 Oct, 2021" }, { "code": null, "e": 24391, "s": 24292, "text": "In this article, we are going to see how to add a “salt and pepper” noise to an image with Python." }, { "code": null, "e": 24584, "s": 24391, "text": "Noise: Noise means random disturbance in a signal in a computer version. In our case, the signal is an image. Random disturbance in the brightness and color of an image is called Image noise. " }, { "code": null, "e": 25127, "s": 24584, "text": "Salt-and-pepper: It is found only in grayscale images (black and white image). As the name suggests salt (white) in pepper (black)–white spots in the dark regions or pepper (black) in salt (white)–black spots in the white regions. In other words, an image having salt-and-pepper noise will have a few dark pixels in bright regions and a few bright pixels in dark regions. Salt-and-pepper noise is also called impulse noise. It can be caused by several reasons like dead pixels, analog-to-digital conversion error, bit transmission error, etc." }, { "code": null, "e": 25184, "s": 25127, "text": "Let’s see how to add salt-and-pepper noise in an image –" }, { "code": null, "e": 25297, "s": 25184, "text": "Salt-and-pepper noise can only be added in a grayscale image. So, convert an image to grayscale after reading it" }, { "code": null, "e": 25375, "s": 25297, "text": "Randomly pick the number of pixels to which noise is added (number_of_pixels)" }, { "code": null, "e": 25498, "s": 25375, "text": "Randomly pick some pixels in the image to which noise will be added. It can be done by randomly picking x and y coordinate" }, { "code": null, "e": 25648, "s": 25498, "text": "Note the random values generated must be within the range of the image dimensions. The x and y coordinates must be within the range of the image size" }, { "code": null, "e": 25757, "s": 25648, "text": "Random numbers can be generated using random number generator functions like random.randint used in the code" }, { "code": null, "e": 25825, "s": 25757, "text": "Color some randomly picked pixels as black setting their value to 0" }, { "code": null, "e": 25895, "s": 25825, "text": "Color some randomly picked pixels as white setting their value to 255" }, { "code": null, "e": 25923, "s": 25895, "text": "Save the value of the image" }, { "code": null, "e": 25952, "s": 25923, "text": "Below is the implementation:" }, { "code": null, "e": 25959, "s": 25952, "text": "Python" }, { "code": "import randomimport cv2 def add_noise(img): # Getting the dimensions of the image row , col = img.shape # Randomly pick some pixels in the # image for coloring them white # Pick a random number between 300 and 10000 number_of_pixels = random.randint(300, 10000) for i in range(number_of_pixels): # Pick a random y coordinate y_coord=random.randint(0, row - 1) # Pick a random x coordinate x_coord=random.randint(0, col - 1) # Color that pixel to white img[y_coord][x_coord] = 255 # Randomly pick some pixels in # the image for coloring them black # Pick a random number between 300 and 10000 number_of_pixels = random.randint(300 , 10000) for i in range(number_of_pixels): # Pick a random y coordinate y_coord=random.randint(0, row - 1) # Pick a random x coordinate x_coord=random.randint(0, col - 1) # Color that pixel to black img[y_coord][x_coord] = 0 return img # salt-and-pepper noise can# be applied only to grayscale images# Reading the color image in grayscale imageimg = cv2.imread('lena.jpg', cv2.IMREAD_GRAYSCALE) #Storing the imagecv2.imwrite('salt-and-pepper-lena.jpg', add_noise(img))", "e": 27282, "s": 25959, "text": null }, { "code": null, "e": 27290, "s": 27282, "text": "Output:" }, { "code": null, "e": 27314, "s": 27290, "text": "Input image: “lena.jpg”" }, { "code": null, "e": 27355, "s": 27314, "text": "Output image: “Salt-and-pepper-lena.jpg”" }, { "code": null, "e": 27364, "s": 27355, "text": "sooda367" }, { "code": null, "e": 27381, "s": 27364, "text": "Image-Processing" }, { "code": null, "e": 27388, "s": 27381, "text": "Picked" }, { "code": null, "e": 27402, "s": 27388, "text": "Python-OpenCV" }, { "code": null, "e": 27409, "s": 27402, "text": "Python" }, { "code": null, "e": 27507, "s": 27409, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27516, "s": 27507, "text": "Comments" }, { "code": null, "e": 27529, "s": 27516, "text": "Old Comments" }, { "code": null, "e": 27561, "s": 27529, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27617, "s": 27561, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27672, "s": 27617, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 27714, "s": 27672, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27756, "s": 27714, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27787, "s": 27756, "text": "Python | os.path.join() method" }, { "code": null, "e": 27826, "s": 27787, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27848, "s": 27826, "text": "Defaultdict in Python" }, { "code": null, "e": 27877, "s": 27848, "text": "Create a directory in Python" } ]
MomentJS - Unix Timestamp
Using this, you can pass the integer value in milliseconds and seconds to moment. moment(Number); var day = moment(1315681876406); To use seconds inside moment will have to use it as moment.unix(timestamp) moment.unix(Number) var day = moment.unix(1968781876); Print Add Notes Bookmark this page
[ { "code": null, "e": 2042, "s": 1960, "text": "Using this, you can pass the integer value in milliseconds and seconds to moment." }, { "code": null, "e": 2059, "s": 2042, "text": "moment(Number);\n" }, { "code": null, "e": 2092, "s": 2059, "text": "var day = moment(1315681876406);" }, { "code": null, "e": 2167, "s": 2092, "text": "To use seconds inside moment will have to use it as moment.unix(timestamp)" }, { "code": null, "e": 2188, "s": 2167, "text": "moment.unix(Number)\n" }, { "code": null, "e": 2223, "s": 2188, "text": "var day = moment.unix(1968781876);" }, { "code": null, "e": 2230, "s": 2223, "text": " Print" }, { "code": null, "e": 2241, "s": 2230, "text": " Add Notes" } ]
Darken or lighten a color in Matplotlib
To darken and lighten the color, we can chage the alpha value in the argument of plot() method.Greater the aplha value, darker will be the color. Create data points for xs and ys using numpy. Plot two lines with different value of alpha, to replicate darker and lighter color of the lines Place legend of the plot using legend() method. To display the figure, use show() method. import numpy as np from matplotlib import pyplot as plt plt.rcParams["figure.figsize"] = [7.00, 3.50] plt.rcParams["figure.autolayout"] = True xs = np.linspace(-2, 2, 100) ys = np.sin(xs) plt.plot(xs, ys, c='red', lw=10, label="Darken") plt.plot(xs+.75, ys+.75, c='red', lw=10, alpha=0.3, label="Lighten") plt.legend(loc='upper left') plt.show()
[ { "code": null, "e": 1208, "s": 1062, "text": "To darken and lighten the color, we can chage the alpha value in the argument of plot() method.Greater the aplha value, darker will be the color." }, { "code": null, "e": 1254, "s": 1208, "text": "Create data points for xs and ys using numpy." }, { "code": null, "e": 1351, "s": 1254, "text": "Plot two lines with different value of alpha, to replicate darker and lighter color of the lines" }, { "code": null, "e": 1399, "s": 1351, "text": "Place legend of the plot using legend() method." }, { "code": null, "e": 1441, "s": 1399, "text": "To display the figure, use show() method." }, { "code": null, "e": 1787, "s": 1441, "text": "import numpy as np\nfrom matplotlib import pyplot as plt\nplt.rcParams[\"figure.figsize\"] = [7.00, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\nxs = np.linspace(-2, 2, 100)\nys = np.sin(xs)\nplt.plot(xs, ys, c='red', lw=10, label=\"Darken\")\nplt.plot(xs+.75, ys+.75, c='red', lw=10, alpha=0.3, label=\"Lighten\")\nplt.legend(loc='upper left')\nplt.show()" } ]
Arduino - Math Library
The Arduino Math library (math.h) includes a number of useful mathematical functions for manipulating floating-point numbers. Following are the macros defined in the header math.h − 1.4426950408889634074 /* log_2 e */ 0.31830988618379067154 /* 1/pi */ 0.63661977236758134308 /* 2/pi */ 1.12837916709551257390 /* 2/sqrt(pi) */ 2.30258509299404568402 /* log_e 10 */ 0.69314718055994530942 /* log_e 2 */ 0.43429448190325182765 /* log_10 e */ 3.14159265358979323846 /* pi */ 3.3V1.57079632679489661923 /* pi/2 */ 0.78539816339744830962 /* pi/4 */ 0.70710678118654752440 /* 1/sqrt(2) */ 1.41421356237309504880 /* sqrt(2) */ The following functions are defined in the header math.h − double acos (double __x) The acos() function computes the principal value of the arc cosine of __x. The returned value is in the range [0, pi] radians. A domain error occurs for arguments not in the range [-1, +1]. double asin (double __x) The asin() function computes the principal value of the arc sine of __x. The returned value is in the range [-pi/2, pi/2] radians. A domain error occurs for arguments not in the range [-1, +1]. double atan (double __x) The atan() function computes the principal value of the arc tangent of __x. The returned value is in the range [-pi/2, pi/2] radians. double atan2 (double __y, double __x) The atan2() function computes the principal value of the arc tangent of __y / __x, using the signs of both arguments to determine the quadrant of the return value. The returned value is in the range [-pi, +pi] radians. double cbrt (double __x) The cbrt() function returns the cube root of __x. double ceil (double __x) The ceil() function returns the smallest integral value greater than or equal to __x, expressed as a floating-point number. static double copysign (double __x, double __y) The copysign() function returns __x but with the sign of __y. They work even if __x or __y are NaN or zero. double cos(double __x) The cos() function returns the cosine of __x, measured in radians. double cosh (double __x) The cosh() function returns the hyperbolic cosine of __x. double exp (double __x) The exp() function returns the exponential value of __x. double fabs (double __x) The fabs() function computes the absolute value of a floating-point number __x. double fdim (double __x, double __y) The fdim() function returns max(__x - __y, 0). If __x or __y or both are NaN, NaN is returned. double floor (double __x) The floor() function returns the largest integral value less than or equal to __x, expressed as a floating-point number. double fma (double __x, double __y, double __z) The fma() function performs floating-point multiply-add. This is the operation (__x * __y) + __z, but the intermediate result is not rounded to the destination type. This can sometimes improve the precision of a calculation. double fmax (double __x, double __y) The fmax() function returns the greater of the two values __x and __y. If an argument is NaN, the other argument is returned. If both the arguments are NaN, NaN is returned. double fmin (double __x, double __y) The fmin() function returns the lesser of the two values __x and __y. If an argument is NaN, the other argument is returned. If both the arguments are NaN, NaN is returned. double fmod (double __x, double__y) The function fmod() returns the floating-point remainder of __x / __y. double frexp (double __x, int * __pexp) The frexp() function breaks a floating-point number into a normalized fraction and an integral power of 2. It stores the integer in the int object pointed to by __pexp. If __x is a normal float point number, the frexp() function returns the value v, such that v has a magnitude in the interval [1/2, 1) or zero, and __x equals v times 2 raised to the power __pexp. If __x is zero, both parts of the result are zero. If __x is not a finite number, the frexp() returns __x as is and stores 0 by __pexp. Note − This implementation permits a zero pointer as a directive to skip a storing the exponent. double hypot (double __x, double__y) The hypot() function returns sqrt(__x*__x + __y*__y). This is the length of the hypotenuse of a right triangle with sides of length __x and __y, or the distance of the point (__x, __y) from the origin. Using this function instead of the direct formula is wise, since the error is much smaller. No underflow with small __x and __y. No overflow if result is in range. static int isfinite (double __x) The isfinite() function returns a nonzero value if __x is finite: not plus or minus infinity, and not NaN. int isinf (double __x) The function isinf() returns 1 if the argument __x is positive infinity, -1 if __x is negative infinity, and 0 otherwise. Note − The GCC 4.3 can replace this function with inline code that returns the 1 value for both infinities (gcc bug #35509). int isnan (double __x) The function isnan() returns 1 if the argument __x represents a "not-a-number" (NaN) object, otherwise 0. double ldexp (double __x, int __exp ) The ldexp() function multiplies a floating-point number by an integral power of 2. It returns the value of __x times 2 raised to the power __exp. double log (double __x) The log() function returns the natural logarithm of argument __x. double log10(double __x) The log10() function returns the logarithm of argument __x to base 10. long lrint (double __x) The lrint() function rounds __x to the nearest integer, rounding the halfway cases to the even integer direction. (That is both 1.5 and 2.5 values are rounded to 2). This function is similar to rint() function, but it differs in type of return value and in that an overflow is possible. Returns The rounded long integer value. If __x is not a finite number or an overflow, this realization returns the LONG_MIN value (0x80000000). long lround (double __x) The lround() function rounds __x to the nearest integer, but rounds halfway cases away from zero (instead of to the nearest even integer). This function is similar to round() function, but it differs in type of return value and in that an overflow is possible. Returns The rounded long integer value. If __x is not a finite number or an overflow was, this realization returns the LONG_MIN value (0x80000000). double modf (double __x, double * __iptr ) The modf() function breaks the argument __x into integral and fractional parts, each of which has the same sign as the argument. It stores the integral part as a double in the object pointed to by __iptr. The modf() function returns the signed fractional part of __x. Note − This implementation skips writing by zero pointer. However, the GCC 4.3 can replace this function with inline code that does not permit to use NULL address for the avoiding of storing. float modff (float __x, float * __iptr) The alias for modf(). double pow (double __x, double __y) The function pow() returns the value of __x to the exponent __y. double round (double __x) The round() function rounds __x to the nearest integer, but rounds halfway cases away from zero (instead of to the nearest even integer). Overflow is impossible. Returns The rounded value. If __x is an integral or infinite, __x itself is returned. If __x is NaN, then NaN is returned. int signbit (double __x) The signbit() function returns a nonzero value if the value of __x has its sign bit set. This is not the same as `__x < 0.0', because IEEE 754 floating point allows zero to be signed. The comparison `-0.0 < 0.0' is false, but `signbit (-0.0)' will return a nonzero value. double sin (double __x) The sin() function returns the sine of __x, measured in radians. double sinh (double __x) The sinh() function returns the hyperbolic sine of __x. double sqrt (double __x) The sqrt() function returns the non-negative square root of __x. double square (double __x) The function square() returns __x * __x. Note − This function does not belong to the C standard definition. double tan (double __x) The tan() function returns the tangent of __x, measured in radians. double tanh ( double __x) The tanh() function returns the hyperbolic tangent of __x. double trunc (double __x) The trunc() function rounds __x to the nearest integer not larger in absolute value. The following example shows how to use the most common math.h library functions − double double__x = 45.45 ; double double__y = 30.20 ; void setup() { Serial.begin(9600); Serial.print("cos num = "); Serial.println (cos (double__x) ); // returns cosine of x Serial.print("absolute value of num = "); Serial.println (fabs (double__x) ); // absolute value of a float Serial.print("floating point modulo = "); Serial.println (fmod (double__x, double__y)); // floating point modulo Serial.print("sine of num = "); Serial.println (sin (double__x) ) ;// returns sine of x Serial.print("square root of num : "); Serial.println ( sqrt (double__x) );// returns square root of x Serial.print("tangent of num : "); Serial.println ( tan (double__x) ); // returns tangent of x Serial.print("exponential value of num : "); Serial.println ( exp (double__x) ); // function returns the exponential value of x. Serial.print("cos num : "); Serial.println (atan (double__x) ); // arc tangent of x Serial.print("tangent of num : "); Serial.println (atan2 (double__y, double__x) );// arc tangent of y/x Serial.print("arc tangent of num : "); Serial.println (log (double__x) ) ; // natural logarithm of x Serial.print("cos num : "); Serial.println ( log10 (double__x)); // logarithm of x to base 10. Serial.print("logarithm of num to base 10 : "); Serial.println (pow (double__x, double__y) );// x to power of y Serial.print("power of num : "); Serial.println (square (double__x)); // square of x } void loop() { } cos num = 0.10 absolute value of num = 45.45 floating point modulo =15.25 sine of num = 0.99 square root of num : 6.74 tangent of num : 9.67 exponential value of num : ovf cos num : 1.55 tangent of num : 0.59 arc tangent of num : 3.82 cos num : 1.66 logarithm of num to base 10 : inf power of num : 2065.70 65 Lectures 6.5 hours Amit Rana 43 Lectures 3 hours Amit Rana 20 Lectures 2 hours Ashraf Said 19 Lectures 1.5 hours Ashraf Said 11 Lectures 47 mins Ashraf Said 9 Lectures 41 mins Ashraf Said Print Add Notes Bookmark this page
[ { "code": null, "e": 2996, "s": 2870, "text": "The Arduino Math library (math.h) includes a number of useful mathematical functions for manipulating floating-point numbers." }, { "code": null, "e": 3052, "s": 2996, "text": "Following are the macros defined in the header math.h −" }, { "code": null, "e": 3074, "s": 3052, "text": "1.4426950408889634074" }, { "code": null, "e": 3088, "s": 3074, "text": "/* log_2 e */" }, { "code": null, "e": 3111, "s": 3088, "text": "0.31830988618379067154" }, { "code": null, "e": 3122, "s": 3111, "text": "/* 1/pi */" }, { "code": null, "e": 3145, "s": 3122, "text": "0.63661977236758134308" }, { "code": null, "e": 3156, "s": 3145, "text": "/* 2/pi */" }, { "code": null, "e": 3179, "s": 3156, "text": "1.12837916709551257390" }, { "code": null, "e": 3196, "s": 3179, "text": "/* 2/sqrt(pi) */" }, { "code": null, "e": 3219, "s": 3196, "text": "2.30258509299404568402" }, { "code": null, "e": 3234, "s": 3219, "text": "/* log_e 10 */" }, { "code": null, "e": 3257, "s": 3234, "text": "0.69314718055994530942" }, { "code": null, "e": 3271, "s": 3257, "text": "/* log_e 2 */" }, { "code": null, "e": 3294, "s": 3271, "text": "0.43429448190325182765" }, { "code": null, "e": 3309, "s": 3294, "text": "/* log_10 e */" }, { "code": null, "e": 3332, "s": 3309, "text": "3.14159265358979323846" }, { "code": null, "e": 3341, "s": 3332, "text": "/* pi */" }, { "code": null, "e": 3368, "s": 3341, "text": "3.3V1.57079632679489661923" }, { "code": null, "e": 3379, "s": 3368, "text": "/* pi/2 */" }, { "code": null, "e": 3402, "s": 3379, "text": "0.78539816339744830962" }, { "code": null, "e": 3413, "s": 3402, "text": "/* pi/4 */" }, { "code": null, "e": 3436, "s": 3413, "text": "0.70710678118654752440" }, { "code": null, "e": 3452, "s": 3436, "text": "/* 1/sqrt(2) */" }, { "code": null, "e": 3475, "s": 3452, "text": "1.41421356237309504880" }, { "code": null, "e": 3489, "s": 3475, "text": "/* sqrt(2) */" }, { "code": null, "e": 3548, "s": 3489, "text": "The following functions are defined in the header math.h −" }, { "code": null, "e": 3573, "s": 3548, "text": "double acos (double __x)" }, { "code": null, "e": 3763, "s": 3573, "text": "The acos() function computes the principal value of the arc cosine of __x. The returned value is in the range [0, pi] radians. A domain error occurs for arguments not in the range [-1, +1]." }, { "code": null, "e": 3788, "s": 3763, "text": "double asin (double __x)" }, { "code": null, "e": 3982, "s": 3788, "text": "The asin() function computes the principal value of the arc sine of __x. The returned value is in the range [-pi/2, pi/2] radians. A domain error occurs for arguments not in the range [-1, +1]." }, { "code": null, "e": 4007, "s": 3982, "text": "double atan (double __x)" }, { "code": null, "e": 4141, "s": 4007, "text": "The atan() function computes the principal value of the arc tangent of __x. The returned value is in the range [-pi/2, pi/2] radians." }, { "code": null, "e": 4179, "s": 4141, "text": "double atan2 (double __y, double __x)" }, { "code": null, "e": 4398, "s": 4179, "text": "The atan2() function computes the principal value of the arc tangent of __y / __x, using the signs of both arguments to determine the quadrant of the return value. The returned value is in the range [-pi, +pi] radians." }, { "code": null, "e": 4423, "s": 4398, "text": "double cbrt (double __x)" }, { "code": null, "e": 4473, "s": 4423, "text": "The cbrt() function returns the cube root of __x." }, { "code": null, "e": 4498, "s": 4473, "text": "double ceil (double __x)" }, { "code": null, "e": 4622, "s": 4498, "text": "The ceil() function returns the smallest integral value greater than or equal to __x, expressed as a floating-point number." }, { "code": null, "e": 4670, "s": 4622, "text": "static double copysign (double __x, double __y)" }, { "code": null, "e": 4778, "s": 4670, "text": "The copysign() function returns __x but with the sign of __y. They work even if __x or __y are NaN or zero." }, { "code": null, "e": 4801, "s": 4778, "text": "double cos(double __x)" }, { "code": null, "e": 4868, "s": 4801, "text": "The cos() function returns the cosine of __x, measured in radians." }, { "code": null, "e": 4893, "s": 4868, "text": "double cosh (double __x)" }, { "code": null, "e": 4951, "s": 4893, "text": "The cosh() function returns the hyperbolic cosine of __x." }, { "code": null, "e": 4975, "s": 4951, "text": "double exp (double __x)" }, { "code": null, "e": 5032, "s": 4975, "text": "The exp() function returns the exponential value of __x." }, { "code": null, "e": 5057, "s": 5032, "text": "double fabs (double __x)" }, { "code": null, "e": 5137, "s": 5057, "text": "The fabs() function computes the absolute value of a floating-point number __x." }, { "code": null, "e": 5174, "s": 5137, "text": "double fdim (double __x, double __y)" }, { "code": null, "e": 5269, "s": 5174, "text": "The fdim() function returns max(__x - __y, 0). If __x or __y or both are NaN, NaN is returned." }, { "code": null, "e": 5295, "s": 5269, "text": "double floor (double __x)" }, { "code": null, "e": 5416, "s": 5295, "text": "The floor() function returns the largest integral value less than or equal to __x, expressed as a floating-point number." }, { "code": null, "e": 5464, "s": 5416, "text": "double fma (double __x, double __y, double __z)" }, { "code": null, "e": 5689, "s": 5464, "text": "The fma() function performs floating-point multiply-add. This is the operation (__x * __y) + __z, but the intermediate result is not rounded to the destination type. This can sometimes improve the precision of a calculation." }, { "code": null, "e": 5726, "s": 5689, "text": "double fmax (double __x, double __y)" }, { "code": null, "e": 5900, "s": 5726, "text": "The fmax() function returns the greater of the two values __x and __y. If an argument is NaN, the other argument is returned. If both the arguments are NaN, NaN is returned." }, { "code": null, "e": 5937, "s": 5900, "text": "double fmin (double __x, double __y)" }, { "code": null, "e": 6110, "s": 5937, "text": "The fmin() function returns the lesser of the two values __x and __y. If an argument is NaN, the other argument is returned. If both the arguments are NaN, NaN is returned." }, { "code": null, "e": 6146, "s": 6110, "text": "double fmod (double __x, double__y)" }, { "code": null, "e": 6217, "s": 6146, "text": "The function fmod() returns the floating-point remainder of __x / __y." }, { "code": null, "e": 6257, "s": 6217, "text": "double frexp (double __x, int * __pexp)" }, { "code": null, "e": 6758, "s": 6257, "text": "The frexp() function breaks a floating-point number into a normalized fraction and an integral power of 2. It stores the integer in the int object pointed to by __pexp. If __x is a normal float point number, the frexp() function returns the value v, such that v has a magnitude in the interval [1/2, 1) or zero, and __x equals v times 2 raised to the power __pexp. If __x is zero, both parts of the result are zero. If __x is not a finite number, the frexp() returns __x as is and stores 0 by __pexp." }, { "code": null, "e": 6855, "s": 6758, "text": "Note − This implementation permits a zero pointer as a directive to skip a storing the exponent." }, { "code": null, "e": 6892, "s": 6855, "text": "double hypot (double __x, double__y)" }, { "code": null, "e": 7258, "s": 6892, "text": "The hypot() function returns sqrt(__x*__x + __y*__y). This is the length of the hypotenuse of a right triangle with sides of length __x and __y, or the distance of the point (__x, __y) from the origin. Using this function instead of the direct formula is wise, since the error is much smaller. No underflow with small __x and __y. No overflow if result is in range." }, { "code": null, "e": 7291, "s": 7258, "text": "static int isfinite (double __x)" }, { "code": null, "e": 7398, "s": 7291, "text": "The isfinite() function returns a nonzero value if __x is finite: not plus or minus infinity, and not NaN." }, { "code": null, "e": 7421, "s": 7398, "text": "int isinf (double __x)" }, { "code": null, "e": 7543, "s": 7421, "text": "The function isinf() returns 1 if the argument __x is positive infinity, -1 if __x is negative infinity, and 0 otherwise." }, { "code": null, "e": 7668, "s": 7543, "text": "Note − The GCC 4.3 can replace this function with inline code that returns the 1 value for both infinities (gcc bug #35509)." }, { "code": null, "e": 7691, "s": 7668, "text": "int isnan (double __x)" }, { "code": null, "e": 7797, "s": 7691, "text": "The function isnan() returns 1 if the argument __x represents a \"not-a-number\" (NaN) object, otherwise 0." }, { "code": null, "e": 7835, "s": 7797, "text": "double ldexp (double __x, int __exp )" }, { "code": null, "e": 7981, "s": 7835, "text": "The ldexp() function multiplies a floating-point number by an integral power of 2. It returns the value of __x times 2 raised to the power __exp." }, { "code": null, "e": 8005, "s": 7981, "text": "double log (double __x)" }, { "code": null, "e": 8071, "s": 8005, "text": "The log() function returns the natural logarithm of argument __x." }, { "code": null, "e": 8096, "s": 8071, "text": "double log10(double __x)" }, { "code": null, "e": 8167, "s": 8096, "text": "The log10() function returns the logarithm of argument __x to base 10." }, { "code": null, "e": 8191, "s": 8167, "text": "long lrint (double __x)" }, { "code": null, "e": 8478, "s": 8191, "text": "The lrint() function rounds __x to the nearest integer, rounding the halfway cases to the even integer direction. (That is both 1.5 and 2.5 values are rounded to 2). This function is similar to rint() function, but it differs in type of return value and in that an overflow is possible." }, { "code": null, "e": 8486, "s": 8478, "text": "Returns" }, { "code": null, "e": 8622, "s": 8486, "text": "The rounded long integer value. If __x is not a finite number or an overflow, this realization returns the LONG_MIN value (0x80000000)." }, { "code": null, "e": 8647, "s": 8622, "text": "long lround (double __x)" }, { "code": null, "e": 8908, "s": 8647, "text": "The lround() function rounds __x to the nearest integer, but rounds halfway cases away from zero (instead of to the nearest even integer). This function is similar to round() function, but it differs in type of return value and in that an overflow is possible." }, { "code": null, "e": 8916, "s": 8908, "text": "Returns" }, { "code": null, "e": 9056, "s": 8916, "text": "The rounded long integer value. If __x is not a finite number or an overflow was, this realization returns the LONG_MIN value (0x80000000)." }, { "code": null, "e": 9099, "s": 9056, "text": "double modf (double __x, double * __iptr )" }, { "code": null, "e": 9304, "s": 9099, "text": "The modf() function breaks the argument __x into integral and fractional parts, each of which has the same sign as the argument. It stores the integral part as a double in the object pointed to by __iptr." }, { "code": null, "e": 9367, "s": 9304, "text": "The modf() function returns the signed fractional part of __x." }, { "code": null, "e": 9559, "s": 9367, "text": "Note − This implementation skips writing by zero pointer. However, the GCC 4.3 can replace this function with inline code that does not permit to use NULL address for the avoiding of storing." }, { "code": null, "e": 9599, "s": 9559, "text": "float modff (float __x, float * __iptr)" }, { "code": null, "e": 9621, "s": 9599, "text": "The alias for modf()." }, { "code": null, "e": 9657, "s": 9621, "text": "double pow (double __x, double __y)" }, { "code": null, "e": 9722, "s": 9657, "text": "The function pow() returns the value of __x to the exponent __y." }, { "code": null, "e": 9748, "s": 9722, "text": "double round (double __x)" }, { "code": null, "e": 9910, "s": 9748, "text": "The round() function rounds __x to the nearest integer, but rounds halfway cases away from zero (instead of to the nearest even integer). Overflow is impossible." }, { "code": null, "e": 9918, "s": 9910, "text": "Returns" }, { "code": null, "e": 10033, "s": 9918, "text": "The rounded value. If __x is an integral or infinite, __x itself is returned. If __x is NaN, then NaN is returned." }, { "code": null, "e": 10058, "s": 10033, "text": "int signbit (double __x)" }, { "code": null, "e": 10330, "s": 10058, "text": "The signbit() function returns a nonzero value if the value of __x has its sign bit set. This is not the same as `__x < 0.0', because IEEE 754 floating point allows zero to be signed. The comparison `-0.0 < 0.0' is false, but `signbit (-0.0)' will return a nonzero value." }, { "code": null, "e": 10354, "s": 10330, "text": "double sin (double __x)" }, { "code": null, "e": 10419, "s": 10354, "text": "The sin() function returns the sine of __x, measured in radians." }, { "code": null, "e": 10444, "s": 10419, "text": "double sinh (double __x)" }, { "code": null, "e": 10500, "s": 10444, "text": "The sinh() function returns the hyperbolic sine of __x." }, { "code": null, "e": 10525, "s": 10500, "text": "double sqrt (double __x)" }, { "code": null, "e": 10590, "s": 10525, "text": "The sqrt() function returns the non-negative square root of __x." }, { "code": null, "e": 10617, "s": 10590, "text": "double square (double __x)" }, { "code": null, "e": 10658, "s": 10617, "text": "The function square() returns __x * __x." }, { "code": null, "e": 10725, "s": 10658, "text": "Note − This function does not belong to the C standard definition." }, { "code": null, "e": 10749, "s": 10725, "text": "double tan (double __x)" }, { "code": null, "e": 10817, "s": 10749, "text": "The tan() function returns the tangent of __x, measured in radians." }, { "code": null, "e": 10843, "s": 10817, "text": "double tanh ( double __x)" }, { "code": null, "e": 10902, "s": 10843, "text": "The tanh() function returns the hyperbolic tangent of __x." }, { "code": null, "e": 10928, "s": 10902, "text": "double trunc (double __x)" }, { "code": null, "e": 11013, "s": 10928, "text": "The trunc() function rounds __x to the nearest integer not larger in absolute value." }, { "code": null, "e": 11095, "s": 11013, "text": "The following example shows how to use the most common math.h library functions −" }, { "code": null, "e": 12589, "s": 11095, "text": "double double__x = 45.45 ;\ndouble double__y = 30.20 ;\n\nvoid setup() {\n Serial.begin(9600);\n Serial.print(\"cos num = \");\n Serial.println (cos (double__x) ); // returns cosine of x\n Serial.print(\"absolute value of num = \");\n Serial.println (fabs (double__x) ); // absolute value of a float\n Serial.print(\"floating point modulo = \");\n Serial.println (fmod (double__x, double__y)); // floating point modulo\n Serial.print(\"sine of num = \");\n Serial.println (sin (double__x) ) ;// returns sine of x\n Serial.print(\"square root of num : \");\n Serial.println ( sqrt (double__x) );// returns square root of x\n Serial.print(\"tangent of num : \");\n Serial.println ( tan (double__x) ); // returns tangent of x\n Serial.print(\"exponential value of num : \");\n Serial.println ( exp (double__x) ); // function returns the exponential value of x.\n Serial.print(\"cos num : \");\n\n Serial.println (atan (double__x) ); // arc tangent of x\n Serial.print(\"tangent of num : \");\n Serial.println (atan2 (double__y, double__x) );// arc tangent of y/x\n Serial.print(\"arc tangent of num : \");\n Serial.println (log (double__x) ) ; // natural logarithm of x\n Serial.print(\"cos num : \");\n Serial.println ( log10 (double__x)); // logarithm of x to base 10.\n Serial.print(\"logarithm of num to base 10 : \");\n Serial.println (pow (double__x, double__y) );// x to power of y\n Serial.print(\"power of num : \");\n Serial.println (square (double__x)); // square of x\n}\n\nvoid loop() {\n\n}" }, { "code": null, "e": 12897, "s": 12589, "text": "cos num = 0.10\nabsolute value of num = 45.45\nfloating point modulo =15.25\nsine of num = 0.99\nsquare root of num : 6.74\ntangent of num : 9.67\nexponential value of num : ovf\ncos num : 1.55\ntangent of num : 0.59\narc tangent of num : 3.82\ncos num : 1.66\nlogarithm of num to base 10 : inf\npower of num : 2065.70\n" }, { "code": null, "e": 12932, "s": 12897, "text": "\n 65 Lectures \n 6.5 hours \n" }, { "code": null, "e": 12943, "s": 12932, "text": " Amit Rana" }, { "code": null, "e": 12976, "s": 12943, "text": "\n 43 Lectures \n 3 hours \n" }, { "code": null, "e": 12987, "s": 12976, "text": " Amit Rana" }, { "code": null, "e": 13020, "s": 12987, "text": "\n 20 Lectures \n 2 hours \n" }, { "code": null, "e": 13033, "s": 13020, "text": " Ashraf Said" }, { "code": null, "e": 13068, "s": 13033, "text": "\n 19 Lectures \n 1.5 hours \n" }, { "code": null, "e": 13081, "s": 13068, "text": " Ashraf Said" }, { "code": null, "e": 13113, "s": 13081, "text": "\n 11 Lectures \n 47 mins\n" }, { "code": null, "e": 13126, "s": 13113, "text": " Ashraf Said" }, { "code": null, "e": 13157, "s": 13126, "text": "\n 9 Lectures \n 41 mins\n" }, { "code": null, "e": 13170, "s": 13157, "text": " Ashraf Said" }, { "code": null, "e": 13177, "s": 13170, "text": " Print" }, { "code": null, "e": 13188, "s": 13177, "text": " Add Notes" } ]
How to display output data in tabular form in Node.js ?
01 Jul, 2020 Tables are a combination of rows and columns. Node.js has its own module named as a table that helps in making tables with a wide variety of styles that can be applied to the table such as border styles, colors body style, etc. Installation of module: npm install table Syntax: table(data, config) Parameters: data: Data is an Array of array i.e. data to be saved in the table. config: Different predefined configuration. Return Value: A string is returned by the function. Example 1: Filename: script.js let table = require("table");let data, config; // Data to be saved in the tablesdata = [ ["A", "B", "C"], ["D", "E", "F"], ["G", "H", "I"],] config = { // Predefined styles of table border: table.getBorderCharacters("ramac"),} let x = table.table(data, config);console.log(x) Step to run this program: Run script.js using the following command: node script.js Output: Example 2: Filename: script.js let table = require("table");let data, config; data = [ ["A", "B", "C"], ["D", "E", "F"], ["G", "H", "I"],] // Creating column width configurationconfig = { columns: { 0: { width: 1 // Column 0 of width 1 }, 1: { width: 20 // Column 1 of width 20 }, 2: { width: 5 // Column 2 of width 5 } }};let x = table.table(data, config);console.log(x) Step to run this program: Run script.js using the following command: node script.js Output: Node.js-Misc Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between promise and async await in Node.js Mongoose | findByIdAndUpdate() Function JWT Authentication with Node.js Installation of Node.js on Windows Node.js forEach() function 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 ? Differences between Functional Components and Class Components in React
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Jul, 2020" }, { "code": null, "e": 256, "s": 28, "text": "Tables are a combination of rows and columns. Node.js has its own module named as a table that helps in making tables with a wide variety of styles that can be applied to the table such as border styles, colors body style, etc." }, { "code": null, "e": 280, "s": 256, "text": "Installation of module:" }, { "code": null, "e": 298, "s": 280, "text": "npm install table" }, { "code": null, "e": 306, "s": 298, "text": "Syntax:" }, { "code": null, "e": 326, "s": 306, "text": "table(data, config)" }, { "code": null, "e": 338, "s": 326, "text": "Parameters:" }, { "code": null, "e": 406, "s": 338, "text": "data: Data is an Array of array i.e. data to be saved in the table." }, { "code": null, "e": 450, "s": 406, "text": "config: Different predefined configuration." }, { "code": null, "e": 502, "s": 450, "text": "Return Value: A string is returned by the function." }, { "code": null, "e": 533, "s": 502, "text": "Example 1: Filename: script.js" }, { "code": "let table = require(\"table\");let data, config; // Data to be saved in the tablesdata = [ [\"A\", \"B\", \"C\"], [\"D\", \"E\", \"F\"], [\"G\", \"H\", \"I\"],] config = { // Predefined styles of table border: table.getBorderCharacters(\"ramac\"),} let x = table.table(data, config);console.log(x)", "e": 829, "s": 533, "text": null }, { "code": null, "e": 898, "s": 829, "text": "Step to run this program: Run script.js using the following command:" }, { "code": null, "e": 913, "s": 898, "text": "node script.js" }, { "code": null, "e": 921, "s": 913, "text": "Output:" }, { "code": null, "e": 952, "s": 921, "text": "Example 2: Filename: script.js" }, { "code": "let table = require(\"table\");let data, config; data = [ [\"A\", \"B\", \"C\"], [\"D\", \"E\", \"F\"], [\"G\", \"H\", \"I\"],] // Creating column width configurationconfig = { columns: { 0: { width: 1 // Column 0 of width 1 }, 1: { width: 20 // Column 1 of width 20 }, 2: { width: 5 // Column 2 of width 5 } }};let x = table.table(data, config);console.log(x)", "e": 1339, "s": 952, "text": null }, { "code": null, "e": 1408, "s": 1339, "text": "Step to run this program: Run script.js using the following command:" }, { "code": null, "e": 1423, "s": 1408, "text": "node script.js" }, { "code": null, "e": 1431, "s": 1423, "text": "Output:" }, { "code": null, "e": 1444, "s": 1431, "text": "Node.js-Misc" }, { "code": null, "e": 1452, "s": 1444, "text": "Node.js" }, { "code": null, "e": 1469, "s": 1452, "text": "Web Technologies" }, { "code": null, "e": 1567, "s": 1469, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1621, "s": 1567, "text": "Difference between promise and async await in Node.js" }, { "code": null, "e": 1661, "s": 1621, "text": "Mongoose | findByIdAndUpdate() Function" }, { "code": null, "e": 1693, "s": 1661, "text": "JWT Authentication with Node.js" }, { "code": null, "e": 1728, "s": 1693, "text": "Installation of Node.js on Windows" }, { "code": null, "e": 1755, "s": 1728, "text": "Node.js forEach() function" }, { "code": null, "e": 1817, "s": 1755, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 1878, "s": 1817, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 1928, "s": 1878, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 1971, "s": 1928, "text": "How to fetch data from an API in ReactJS ?" } ]
HTML DOM innerHTML Property
16 Jun, 2022 The DOM innerHTML property is used to set or return the HTML content of an element. Syntax: It returns the innerHTML Property. Object.innerHTML It is used to set the innerHTML property. Object.innerHTML = value Where, value: It represents the text content of the HTML element. Return Value: This property returns a string that represents the HTML content of an element. Example 1: This example shows how to change the content of the paragraph tag using the innerHTML property. HTML <!DOCTYPE html><html> <body style="text-align: center"> <h1 style="color:green"> GeeksforGeeks </h1> <h2> DOM innerHTML Property </h2> <p id="p">GeeksforGeeks</p> <button onclick="geek()">Click me!</button> <script> function geek() { document.getElementById("p").innerHTML = "A computer science portal for geeks."; } </script></body> </html> Output: innerHTML Property Example 2: This example shows how to get the value of the paragraph tag using the innerHTML property. HTML <!DOCTYPE html><html> <body style="text-align: center"> <h1 style="color:green"> GeeksforGeeks </h1> <h2> DOM innerHTML Property </h2> <p id="P">A computer science portal for geeks.</p> <button onclick="geek()">Try it</button> <p id="p"></p> <script> function geek() { var x = document.getElementById("P").innerHTML; document.getElementById("p").innerHTML = x; document.getElementById("p").style.color = "green"; } </script></body> </html> Output: innerHTML Property Supported Browsers: The browser supported by DOM innerHTML property are listed below: Google Chrome 33.0 and above Internet Explorer 4 and above Microsoft Edge 12.0 and above Firefox 1.0 and above Opera 8.0 and above Safari 9.0 and above simranarora5sos bhaskargeeksforgeeks kumargaurav97520 HTML-DOM Picked HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to update Node.js and NPM to next version ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? REST API (Introduction) Hide or show elements in HTML using display property 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": "\n16 Jun, 2022" }, { "code": null, "e": 112, "s": 28, "text": "The DOM innerHTML property is used to set or return the HTML content of an element." }, { "code": null, "e": 120, "s": 112, "text": "Syntax:" }, { "code": null, "e": 155, "s": 120, "text": "It returns the innerHTML Property." }, { "code": null, "e": 172, "s": 155, "text": "Object.innerHTML" }, { "code": null, "e": 214, "s": 172, "text": "It is used to set the innerHTML property." }, { "code": null, "e": 239, "s": 214, "text": "Object.innerHTML = value" }, { "code": null, "e": 246, "s": 239, "text": "Where," }, { "code": null, "e": 305, "s": 246, "text": "value: It represents the text content of the HTML element." }, { "code": null, "e": 398, "s": 305, "text": "Return Value: This property returns a string that represents the HTML content of an element." }, { "code": null, "e": 506, "s": 398, "text": "Example 1: This example shows how to change the content of the paragraph tag using the innerHTML property. " }, { "code": null, "e": 511, "s": 506, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <body style=\"text-align: center\"> <h1 style=\"color:green\"> GeeksforGeeks </h1> <h2> DOM innerHTML Property </h2> <p id=\"p\">GeeksforGeeks</p> <button onclick=\"geek()\">Click me!</button> <script> function geek() { document.getElementById(\"p\").innerHTML = \"A computer science portal for geeks.\"; } </script></body> </html>", "e": 913, "s": 511, "text": null }, { "code": null, "e": 921, "s": 913, "text": "Output:" }, { "code": null, "e": 940, "s": 921, "text": "innerHTML Property" }, { "code": null, "e": 1042, "s": 940, "text": "Example 2: This example shows how to get the value of the paragraph tag using the innerHTML property." }, { "code": null, "e": 1047, "s": 1042, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <body style=\"text-align: center\"> <h1 style=\"color:green\"> GeeksforGeeks </h1> <h2> DOM innerHTML Property </h2> <p id=\"P\">A computer science portal for geeks.</p> <button onclick=\"geek()\">Try it</button> <p id=\"p\"></p> <script> function geek() { var x = document.getElementById(\"P\").innerHTML; document.getElementById(\"p\").innerHTML = x; document.getElementById(\"p\").style.color = \"green\"; } </script></body> </html>", "e": 1564, "s": 1047, "text": null }, { "code": null, "e": 1572, "s": 1564, "text": "Output:" }, { "code": null, "e": 1591, "s": 1572, "text": "innerHTML Property" }, { "code": null, "e": 1677, "s": 1591, "text": "Supported Browsers: The browser supported by DOM innerHTML property are listed below:" }, { "code": null, "e": 1706, "s": 1677, "text": "Google Chrome 33.0 and above" }, { "code": null, "e": 1736, "s": 1706, "text": "Internet Explorer 4 and above" }, { "code": null, "e": 1766, "s": 1736, "text": "Microsoft Edge 12.0 and above" }, { "code": null, "e": 1788, "s": 1766, "text": "Firefox 1.0 and above" }, { "code": null, "e": 1808, "s": 1788, "text": "Opera 8.0 and above" }, { "code": null, "e": 1829, "s": 1808, "text": "Safari 9.0 and above" }, { "code": null, "e": 1845, "s": 1829, "text": "simranarora5sos" }, { "code": null, "e": 1866, "s": 1845, "text": "bhaskargeeksforgeeks" }, { "code": null, "e": 1883, "s": 1866, "text": "kumargaurav97520" }, { "code": null, "e": 1892, "s": 1883, "text": "HTML-DOM" }, { "code": null, "e": 1899, "s": 1892, "text": "Picked" }, { "code": null, "e": 1904, "s": 1899, "text": "HTML" }, { "code": null, "e": 1921, "s": 1904, "text": "Web Technologies" }, { "code": null, "e": 1926, "s": 1921, "text": "HTML" }, { "code": null, "e": 2024, "s": 1926, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2072, "s": 2024, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 2134, "s": 2072, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2184, "s": 2134, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 2208, "s": 2184, "text": "REST API (Introduction)" }, { "code": null, "e": 2261, "s": 2208, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 2323, "s": 2261, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2356, "s": 2323, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2417, "s": 2356, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2467, "s": 2417, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
How to Resolve Java.lang.ExceptionInInitializerError In Java?
03 Mar, 2022 An unexpected, unwanted event that disturbed the normal flow of a program is called an Exception. There are mainly two types of exception in Java: 1. Checked Exception 2. Unchecked Exception ExceptionInInitializerError is the child class of the Error class and hence it is an unchecked exception. This exception is rise automatically by JVM when JVM attempts to load a new class as, during class loading, all static variables and static initializer block are being evaluated. This exception also acts as a signal that tells us that an unexpected exception has occurred in a static initializer block or in the assignment of value to the static variable. There are basically two cases when ExceptionInInitializerError can occur in a Java Program: 1. ExceptionInInitializerError While Assigning Value To The Static Variable In the below example we assign a static variable to 20/0 where 20/0 gives an undefined arithmetic behavior and hence there occurs an exception in the static variable assignment and ultimately we will get ExceptionInInitializerError. Java // Java Program for showing the ExceptionInInitializerError// While Assigning Value To The Static Variableclass GFG { // assignment of static variable static int x = 20 / 0; public static void main(String[] args) { // printing the value of x System.out.println("The value of x is " + x); }} 2. ExceptionInInitializerError While Assigning Null Value Inside A Static Block In the below example we have declared a static block inside which we create a string s and assign a null value to it, and then we are printing the length of string, so we will get NullPointerException because we were trying to print the length of a string that has its value as null and as we see that this exception occurs inside the static block, so we will get ExceptionInInitializerError. Java // Java Program for showing the ExceptionInInitializerError// While Assigning Null Value Inside A Static Blockclass GFG { // declaring a static initializer block static { // creating a string and assigning a null value to // it String s = null; // printing the length of string but as the string // is null so an exception occur in the static block System.out.println(s.length()); } public static void main(String[] args) { System.out.println("GeeksForGeeks Is Best"); }} How to Resolve Java.lang.ExceptionInInitializerError ? We can resolve the java.lang.ExceptionInInitializerError by ensuring that static initializer block of classes does not throw any Runtime Exception. We can resolve also resolve this exception by ensuring that the initializing static variable of classes also doesn’t throw any Runtime Exception. adnanirshad158 avtarkumar719 Java-Exceptions Picked Technical Scripter 2020 How To Java Technical Scripter Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Set Git Username and Password in GitBash? How to Install Jupyter Notebook on MacOS? How to Install and Use NVM on Windows? How to Install Python Packages for AWS Lambda Layers? How to Add External JAR File to an IntelliJ IDEA Project? Arrays in Java Split() String method in Java with examples Arrays.sort() in Java with examples Object Oriented Programming (OOPs) Concept in Java Reverse a string in Java
[ { "code": null, "e": 53, "s": 25, "text": "\n03 Mar, 2022" }, { "code": null, "e": 151, "s": 53, "text": "An unexpected, unwanted event that disturbed the normal flow of a program is called an Exception." }, { "code": null, "e": 200, "s": 151, "text": "There are mainly two types of exception in Java:" }, { "code": null, "e": 221, "s": 200, "text": "1. Checked Exception" }, { "code": null, "e": 244, "s": 221, "text": "2. Unchecked Exception" }, { "code": null, "e": 706, "s": 244, "text": "ExceptionInInitializerError is the child class of the Error class and hence it is an unchecked exception. This exception is rise automatically by JVM when JVM attempts to load a new class as, during class loading, all static variables and static initializer block are being evaluated. This exception also acts as a signal that tells us that an unexpected exception has occurred in a static initializer block or in the assignment of value to the static variable." }, { "code": null, "e": 798, "s": 706, "text": "There are basically two cases when ExceptionInInitializerError can occur in a Java Program:" }, { "code": null, "e": 874, "s": 798, "text": "1. ExceptionInInitializerError While Assigning Value To The Static Variable" }, { "code": null, "e": 1107, "s": 874, "text": "In the below example we assign a static variable to 20/0 where 20/0 gives an undefined arithmetic behavior and hence there occurs an exception in the static variable assignment and ultimately we will get ExceptionInInitializerError." }, { "code": null, "e": 1112, "s": 1107, "text": "Java" }, { "code": "// Java Program for showing the ExceptionInInitializerError// While Assigning Value To The Static Variableclass GFG { // assignment of static variable static int x = 20 / 0; public static void main(String[] args) { // printing the value of x System.out.println(\"The value of x is \" + x); }}", "e": 1432, "s": 1112, "text": null }, { "code": null, "e": 1517, "s": 1437, "text": "2. ExceptionInInitializerError While Assigning Null Value Inside A Static Block" }, { "code": null, "e": 1912, "s": 1519, "text": "In the below example we have declared a static block inside which we create a string s and assign a null value to it, and then we are printing the length of string, so we will get NullPointerException because we were trying to print the length of a string that has its value as null and as we see that this exception occurs inside the static block, so we will get ExceptionInInitializerError." }, { "code": null, "e": 1919, "s": 1914, "text": "Java" }, { "code": "// Java Program for showing the ExceptionInInitializerError// While Assigning Null Value Inside A Static Blockclass GFG { // declaring a static initializer block static { // creating a string and assigning a null value to // it String s = null; // printing the length of string but as the string // is null so an exception occur in the static block System.out.println(s.length()); } public static void main(String[] args) { System.out.println(\"GeeksForGeeks Is Best\"); }}", "e": 2462, "s": 1919, "text": null }, { "code": null, "e": 2522, "s": 2467, "text": "How to Resolve Java.lang.ExceptionInInitializerError ?" }, { "code": null, "e": 2672, "s": 2524, "text": "We can resolve the java.lang.ExceptionInInitializerError by ensuring that static initializer block of classes does not throw any Runtime Exception." }, { "code": null, "e": 2818, "s": 2672, "text": "We can resolve also resolve this exception by ensuring that the initializing static variable of classes also doesn’t throw any Runtime Exception." }, { "code": null, "e": 2835, "s": 2820, "text": "adnanirshad158" }, { "code": null, "e": 2849, "s": 2835, "text": "avtarkumar719" }, { "code": null, "e": 2865, "s": 2849, "text": "Java-Exceptions" }, { "code": null, "e": 2872, "s": 2865, "text": "Picked" }, { "code": null, "e": 2896, "s": 2872, "text": "Technical Scripter 2020" }, { "code": null, "e": 2903, "s": 2896, "text": "How To" }, { "code": null, "e": 2908, "s": 2903, "text": "Java" }, { "code": null, "e": 2927, "s": 2908, "text": "Technical Scripter" }, { "code": null, "e": 2932, "s": 2927, "text": "Java" }, { "code": null, "e": 3030, "s": 2932, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3079, "s": 3030, "text": "How to Set Git Username and Password in GitBash?" }, { "code": null, "e": 3121, "s": 3079, "text": "How to Install Jupyter Notebook on MacOS?" }, { "code": null, "e": 3160, "s": 3121, "text": "How to Install and Use NVM on Windows?" }, { "code": null, "e": 3214, "s": 3160, "text": "How to Install Python Packages for AWS Lambda Layers?" }, { "code": null, "e": 3272, "s": 3214, "text": "How to Add External JAR File to an IntelliJ IDEA Project?" }, { "code": null, "e": 3287, "s": 3272, "text": "Arrays in Java" }, { "code": null, "e": 3331, "s": 3287, "text": "Split() String method in Java with examples" }, { "code": null, "e": 3367, "s": 3331, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 3418, "s": 3367, "text": "Object Oriented Programming (OOPs) Concept in Java" } ]
How to plot excel data in R?
26 Mar, 2021 Plotting graph in R using an excel file, we need an excel file with two-column in it, the values in the first column will be considered as the points at the x-axis and the values in the second column will be considered as the points at the y-axis. In this article, we will be discussing the approach to plot a graph using an excel file in R language. To import and read the excel file to the R console, the read_excel() function from readxl library in R will be used. This function will read an excel-file available in your current working directory. To install the package of the readxl library in R the user must need to follow the following syntax in the R console. Syntax: install.packages(“readxl”) Data in use: plot() function is used for plotting of R objects. With the provided parameters this function returns a scatter plot by default. Syntax: plot(x,y,main,xlab,ylab,sub,asp) Parameters: x:-the x coordinates of points in the plot y:-the y coordinates of points in the plot main:-an overall title for the plot sub:-a subtitle for the plot xlab:-a title for the x-axis ylab:-a title for the y-axis asp:-the y/x aspect ratio Return: Scatter plot of the given x and y values. Approach Import library Import excel file Read its data Plot graph Display plot Example: R library(readxl) Data_gfg <- read_excel("Data_gfg.xlsx") plot(x = Data_gfg$x,y = Data_gfg$y, xlab = "x-axis", ylab = "y-axis", main = "Plot") Output: Picked R-Excel R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change Color of Bars in Barchart using ggplot2 in R How to Split Column Into Multiple Columns in R DataFrame? Group by function in R using Dplyr How to Change Axis Scales in R Plots? How to filter R DataFrame by values in a column? R - if statement Logistic Regression in R Programming Replace Specific Characters in String in R How to import an Excel File into R ? Joining of Dataframes in R Programming
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Mar, 2021" }, { "code": null, "e": 379, "s": 28, "text": "Plotting graph in R using an excel file, we need an excel file with two-column in it, the values in the first column will be considered as the points at the x-axis and the values in the second column will be considered as the points at the y-axis. In this article, we will be discussing the approach to plot a graph using an excel file in R language." }, { "code": null, "e": 698, "s": 379, "text": "To import and read the excel file to the R console, the read_excel() function from readxl library in R will be used. This function will read an excel-file available in your current working directory. To install the package of the readxl library in R the user must need to follow the following syntax in the R console." }, { "code": null, "e": 706, "s": 698, "text": "Syntax:" }, { "code": null, "e": 734, "s": 706, "text": "install.packages(“readxl”) " }, { "code": null, "e": 747, "s": 734, "text": "Data in use:" }, { "code": null, "e": 876, "s": 747, "text": "plot() function is used for plotting of R objects. With the provided parameters this function returns a scatter plot by default." }, { "code": null, "e": 884, "s": 876, "text": "Syntax:" }, { "code": null, "e": 917, "s": 884, "text": "plot(x,y,main,xlab,ylab,sub,asp)" }, { "code": null, "e": 929, "s": 917, "text": "Parameters:" }, { "code": null, "e": 972, "s": 929, "text": "x:-the x coordinates of points in the plot" }, { "code": null, "e": 1015, "s": 972, "text": "y:-the y coordinates of points in the plot" }, { "code": null, "e": 1051, "s": 1015, "text": "main:-an overall title for the plot" }, { "code": null, "e": 1080, "s": 1051, "text": "sub:-a subtitle for the plot" }, { "code": null, "e": 1109, "s": 1080, "text": "xlab:-a title for the x-axis" }, { "code": null, "e": 1138, "s": 1109, "text": "ylab:-a title for the y-axis" }, { "code": null, "e": 1164, "s": 1138, "text": "asp:-the y/x aspect ratio" }, { "code": null, "e": 1172, "s": 1164, "text": "Return:" }, { "code": null, "e": 1214, "s": 1172, "text": "Scatter plot of the given x and y values." }, { "code": null, "e": 1223, "s": 1214, "text": "Approach" }, { "code": null, "e": 1238, "s": 1223, "text": "Import library" }, { "code": null, "e": 1256, "s": 1238, "text": "Import excel file" }, { "code": null, "e": 1270, "s": 1256, "text": "Read its data" }, { "code": null, "e": 1281, "s": 1270, "text": "Plot graph" }, { "code": null, "e": 1294, "s": 1281, "text": "Display plot" }, { "code": null, "e": 1303, "s": 1294, "text": "Example:" }, { "code": null, "e": 1305, "s": 1303, "text": "R" }, { "code": "library(readxl) Data_gfg <- read_excel(\"Data_gfg.xlsx\") plot(x = Data_gfg$x,y = Data_gfg$y, xlab = \"x-axis\", ylab = \"y-axis\", main = \"Plot\")", "e": 1460, "s": 1305, "text": null }, { "code": null, "e": 1468, "s": 1460, "text": "Output:" }, { "code": null, "e": 1475, "s": 1468, "text": "Picked" }, { "code": null, "e": 1483, "s": 1475, "text": "R-Excel" }, { "code": null, "e": 1494, "s": 1483, "text": "R Language" }, { "code": null, "e": 1592, "s": 1494, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1644, "s": 1592, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 1702, "s": 1644, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 1737, "s": 1702, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 1775, "s": 1737, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 1824, "s": 1775, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 1841, "s": 1824, "text": "R - if statement" }, { "code": null, "e": 1878, "s": 1841, "text": "Logistic Regression in R Programming" }, { "code": null, "e": 1921, "s": 1878, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 1958, "s": 1921, "text": "How to import an Excel File into R ?" } ]
Longest Span with same Sum in two Binary arrays
22 Jun, 2022 Given two binary arrays, arr1[] and arr2[] of the same size n. Find the length of the longest common span (i, j) where j >= i such that arr1[i] + arr1[i+1] + .... + arr1[j] = arr2[i] + arr2[i+1] + .... + arr2[j].The expected time complexity is Θ(n). Examples: Input: arr1[] = {0, 1, 0, 0, 0, 0}; arr2[] = {1, 0, 1, 0, 0, 1}; Output: 4 The longest span with same sum is from index 1 to 4. Input: arr1[] = {0, 1, 0, 1, 1, 1, 1}; arr2[] = {1, 1, 1, 1, 1, 0, 1}; Output: 6 The longest span with same sum is from index 1 to 6. Input: arr1[] = {0, 0, 0}; arr2[] = {1, 1, 1}; Output: 0 Input: arr1[] = {0, 0, 1, 0}; arr2[] = {1, 1, 1, 1}; Output: 1 Method 1 (Simple Solution) One by one by consider same subarrays of both arrays. For all subarrays, compute sums and if sums are same and current length is more than max length, then update max length. Below is C++ implementation of the simple approach. C++ Java Python3 C# PHP Javascript // A Simple C++ program to find longest common// subarray of two binary arrays with same sum#include<bits/stdc++.h>using namespace std; // Returns length of the longest common subarray// with same sumint longestCommonSum(bool arr1[], bool arr2[], int n){ // Initialize result int maxLen = 0; // One by one pick all possible starting points // of subarrays for (int i=0; i<n; i++) { // Initialize sums of current subarrays int sum1 = 0, sum2 = 0; // Consider all points for starting with arr[i] for (int j=i; j<n; j++) { // Update sums sum1 += arr1[j]; sum2 += arr2[j]; // If sums are same and current length is // more than maxLen, update maxLen if (sum1 == sum2) { int len = j-i+1; if (len > maxLen) maxLen = len; } } } return maxLen;} // Driver program to test above functionint main(){ bool arr1[] = {0, 1, 0, 1, 1, 1, 1}; bool arr2[] = {1, 1, 1, 1, 1, 0, 1}; int n = sizeof(arr1)/sizeof(arr1[0]); cout << "Length of the longest common span with same " "sum is "<< longestCommonSum(arr1, arr2, n); return 0;} // A Simple Java program to find longest common// subarray of two binary arrays with same sum class Test{ static int arr1[] = new int[]{0, 1, 0, 1, 1, 1, 1}; static int arr2[] = new int[]{1, 1, 1, 1, 1, 0, 1}; // Returns length of the longest common sum in arr1[] // and arr2[]. Both are of same size n. static int longestCommonSum(int n) { // Initialize result int maxLen = 0; // One by one pick all possible starting points // of subarrays for (int i=0; i<n; i++) { // Initialize sums of current subarrays int sum1 = 0, sum2 = 0; // Consider all points for starting with arr[i] for (int j=i; j<n; j++) { // Update sums sum1 += arr1[j]; sum2 += arr2[j]; // If sums are same and current length is // more than maxLen, update maxLen if (sum1 == sum2) { int len = j-i+1; if (len > maxLen) maxLen = len; } } } return maxLen; } // Driver method to test the above function public static void main(String[] args) { System.out.print("Length of the longest common span with same sum is "); System.out.println(longestCommonSum(arr1.length)); }} # A Simple python program to find longest common# subarray of two binary arrays with same sum # Returns length of the longest common subarray# with same sumdef longestCommonSum(arr1, arr2, n): # Initialize result maxLen = 0 # One by one pick all possible starting points # of subarrays for i in range(0,n): # Initialize sums of current subarrays sum1 = 0 sum2 = 0 # Consider all points for starting with arr[i] for j in range(i,n): # Update sums sum1 += arr1[j] sum2 += arr2[j] # If sums are same and current length is # more than maxLen, update maxLen if (sum1 == sum2): len = j-i+1 if (len > maxLen): maxLen = len return maxLen # Driver program to test above functionarr1 = [0, 1, 0, 1, 1, 1, 1]arr2 = [1, 1, 1, 1, 1, 0, 1]n = len(arr1)print("Length of the longest common span with same " "sum is",longestCommonSum(arr1, arr2, n)) # This code is contributed by# Smitha Dinesh Semwal // A Simple C# program to find// longest common subarray of// two binary arrays with same sumusing System; class GFG{static int[] arr1 = new int[]{0, 1, 0, 1, 1, 1, 1};static int[] arr2 = new int[]{1, 1, 1, 1, 1, 0, 1}; // Returns length of the longest// common sum in arr1[] and arr2[].// Both are of same size n.static int longestCommonSum(int n){ // Initialize result int maxLen = 0; // One by one pick all possible // starting points of subarrays for (int i = 0; i < n; i++) { // Initialize sums of current // subarrays int sum1 = 0, sum2 = 0; // Consider all points for // starting with arr[i] for (int j = i; j < n; j++) { // Update sums sum1 += arr1[j]; sum2 += arr2[j]; // If sums are same and current // length is more than maxLen, // update maxLen if (sum1 == sum2) { int len = j - i + 1; if (len > maxLen) maxLen = len; } } } return maxLen;} // Driver Codepublic static void Main(){ Console.Write("Length of the longest " + "common span with same sum is "); Console.Write(longestCommonSum(arr1.Length));}} // This code is contributed// by ChitraNayal <?php// A Simple PHP program to find// longest common subarray of// two binary arrays with same sum // Returns length of the longest// common subarray with same sumfunction longestCommonSum($arr1, $arr2, $n){ // Initialize result $maxLen = 0; // One by one pick all possible // starting points of subarrays for ($i = 0; $i < $n; $i++) { // Initialize sums of // current subarrays $sum1 = 0; $sum2 = 0; // Consider all points // for starting with arr[i] for ($j = $i; $j < $n; $j++) { // Update sums $sum1 += $arr1[$j]; $sum2 += $arr2[$j]; // If sums are same and current // length is more than maxLen, // update maxLen if ($sum1 == $sum2) { $len = $j - $i + 1; if ($len > $maxLen) $maxLen = $len; } } } return $maxLen;} // Driver Code$arr1 = array(0, 1, 0, 1, 1, 1, 1);$arr2 = array (1, 1, 1, 1, 1, 0, 1);$n = sizeof($arr1);echo "Length of the longest common span ". "with same ", "sum is ", longestCommonSum($arr1, $arr2, $n); // This code is contributed by aj_36?> <script> // A Simple Javascript program to find // longest common subarray of // two binary arrays with same sum let arr1 = [0, 1, 0, 1, 1, 1, 1]; let arr2 = [1, 1, 1, 1, 1, 0, 1]; // Returns length of the longest // common sum in arr1[] and arr2[]. // Both are of same size n. function longestCommonSum(n) { // Initialize result let maxLen = 0; // One by one pick all possible // starting points of subarrays for (let i = 0; i < n; i++) { // Initialize sums of current // subarrays let sum1 = 0, sum2 = 0; // Consider all points for // starting with arr[i] for (let j = i; j < n; j++) { // Update sums sum1 += arr1[j]; sum2 += arr2[j]; // If sums are same and current // length is more than maxLen, // update maxLen if (sum1 == sum2) { let len = j - i + 1; if (len > maxLen) maxLen = len; } } } return maxLen; } document.write("Length of the longest " + "common span with same sum is "); document.write(longestCommonSum(arr1.length)); </script> Output : Length of the longest common span with same sum is 6 Time Complexity : O(n2) Auxiliary Space : O(1) Chapters descriptions off, selected captions settings, opens captions settings dialog captions off, selected English This is a modal window. Beginning of dialog window. Escape will cancel and close the window. End of dialog window. Method 2 (Using Auxiliary Array) The idea is based on the below observations. Since there are total n elements, maximum sum is n for both arrays.The difference between two sums varies from -n to n. So there are total 2n + 1 possible values of difference.If differences between prefix sums of two arrays become same at two points, then subarrays between these two points have same sum. Since there are total n elements, maximum sum is n for both arrays. The difference between two sums varies from -n to n. So there are total 2n + 1 possible values of difference. If differences between prefix sums of two arrays become same at two points, then subarrays between these two points have same sum. Below is the Complete Algorithm. Create an auxiliary array of size 2n+1 to store starting points of all possible values of differences (Note that possible values of differences vary from -n to n, i.e., there are total 2n+1 possible values)Initialize starting points of all differences as -1.Initialize maxLen as 0 and prefix sums of both arrays as 0, preSum1 = 0, preSum2 = 0Traverse both arrays from i = 0 to n-1. Update prefix sums: preSum1 += arr1[i], preSum2 += arr2[i]Compute difference of current prefix sums: curr_diff = preSum1 – preSum2Find index in diff array: diffIndex = n + curr_diff // curr_diff can be negative and can go till -nIf curr_diff is 0, then i+1 is maxLen so farElse If curr_diff is seen first time, i.e., starting point of current diff is -1, then update starting point as iElse (curr_diff is NOT seen first time), then consider i as ending point and find length of current same sum span. If this length is more, then update maxLenReturn maxLen Create an auxiliary array of size 2n+1 to store starting points of all possible values of differences (Note that possible values of differences vary from -n to n, i.e., there are total 2n+1 possible values) Initialize starting points of all differences as -1. Initialize maxLen as 0 and prefix sums of both arrays as 0, preSum1 = 0, preSum2 = 0 Traverse both arrays from i = 0 to n-1. Update prefix sums: preSum1 += arr1[i], preSum2 += arr2[i]Compute difference of current prefix sums: curr_diff = preSum1 – preSum2Find index in diff array: diffIndex = n + curr_diff // curr_diff can be negative and can go till -nIf curr_diff is 0, then i+1 is maxLen so farElse If curr_diff is seen first time, i.e., starting point of current diff is -1, then update starting point as iElse (curr_diff is NOT seen first time), then consider i as ending point and find length of current same sum span. If this length is more, then update maxLen Update prefix sums: preSum1 += arr1[i], preSum2 += arr2[i]Compute difference of current prefix sums: curr_diff = preSum1 – preSum2Find index in diff array: diffIndex = n + curr_diff // curr_diff can be negative and can go till -nIf curr_diff is 0, then i+1 is maxLen so farElse If curr_diff is seen first time, i.e., starting point of current diff is -1, then update starting point as iElse (curr_diff is NOT seen first time), then consider i as ending point and find length of current same sum span. If this length is more, then update maxLen Update prefix sums: preSum1 += arr1[i], preSum2 += arr2[i] Compute difference of current prefix sums: curr_diff = preSum1 – preSum2 Find index in diff array: diffIndex = n + curr_diff // curr_diff can be negative and can go till -n If curr_diff is 0, then i+1 is maxLen so far Else If curr_diff is seen first time, i.e., starting point of current diff is -1, then update starting point as i Else (curr_diff is NOT seen first time), then consider i as ending point and find length of current same sum span. If this length is more, then update maxLen Return maxLen Below is the implementation of above algorithm. C++ Java Python C# Javascript // A O(n) and O(n) extra space C++ program to find// longest common subarray of two binary arrays with// same sum#include<bits/stdc++.h>using namespace std; // Returns length of the longest common sum in arr1[]// and arr2[]. Both are of same size n.int longestCommonSum(bool arr1[], bool arr2[], int n){ // Initialize result int maxLen = 0; // Initialize prefix sums of two arrays int preSum1 = 0, preSum2 = 0; // Create an array to store starting and ending // indexes of all possible diff values. diff[i] // would store starting and ending points for // difference "i-n" int diff[2*n+1]; // Initialize all starting and ending values as -1. memset(diff, -1, sizeof(diff)); // Traverse both arrays for (int i=0; i<n; i++) { // Update prefix sums preSum1 += arr1[i]; preSum2 += arr2[i]; // Compute current diff and index to be used // in diff array. Note that diff can be negative // and can have minimum value as -1. int curr_diff = preSum1 - preSum2; int diffIndex = n + curr_diff; // If current diff is 0, then there are same number // of 1's so far in both arrays, i.e., (i+1) is // maximum length. if (curr_diff == 0) maxLen = i+1; // If current diff is seen first time, then update // starting index of diff. else if ( diff[diffIndex] == -1) diff[diffIndex] = i; // Current diff is already seen else { // Find length of this same sum common span int len = i - diff[diffIndex]; // Update max len if needed if (len > maxLen) maxLen = len; } } return maxLen;} // Driver codeint main(){ bool arr1[] = {0, 1, 0, 1, 1, 1, 1}; bool arr2[] = {1, 1, 1, 1, 1, 0, 1}; int n = sizeof(arr1)/sizeof(arr1[0]); cout << "Length of the longest common span with same " "sum is "<< longestCommonSum(arr1, arr2, n); return 0;} // A O(n) and O(n) extra space Java program to find// longest common subarray of two binary arrays with// same sum class Test{ static int arr1[] = new int[]{0, 1, 0, 1, 1, 1, 1}; static int arr2[] = new int[]{1, 1, 1, 1, 1, 0, 1}; // Returns length of the longest common sum in arr1[] // and arr2[]. Both are of same size n. static int longestCommonSum(int n) { // Initialize result int maxLen = 0; // Initialize prefix sums of two arrays int preSum1 = 0, preSum2 = 0; // Create an array to store starting and ending // indexes of all possible diff values. diff[i] // would store starting and ending points for // difference "i-n" int diff[] = new int[2*n+1]; // Initialize all starting and ending values as -1. for (int i = 0; i < diff.length; i++) { diff[i] = -1; } // Traverse both arrays for (int i=0; i<n; i++) { // Update prefix sums preSum1 += arr1[i]; preSum2 += arr2[i]; // Compute current diff and index to be used // in diff array. Note that diff can be negative // and can have minimum value as -1. int curr_diff = preSum1 - preSum2; int diffIndex = n + curr_diff; // If current diff is 0, then there are same number // of 1's so far in both arrays, i.e., (i+1) is // maximum length. if (curr_diff == 0) maxLen = i+1; // If current diff is seen first time, then update // starting index of diff. else if ( diff[diffIndex] == -1) diff[diffIndex] = i; // Current diff is already seen else { // Find length of this same sum common span int len = i - diff[diffIndex]; // Update max len if needed if (len > maxLen) maxLen = len; } } return maxLen; } // Driver method to test the above function public static void main(String[] args) { System.out.print("Length of the longest common span with same sum is "); System.out.println(longestCommonSum(arr1.length)); }} # Python program to find longest common# subarray of two binary arrays with# same sum def longestCommonSum(arr1, arr2, n): # Initialize result maxLen = 0 # Initialize prefix sums of two arrays presum1 = presum2 = 0 # Create a dictionary to store indices # of all possible sums diff = {} # Traverse both arrays for i in range(n): # Update prefix sums presum1 += arr1[i] presum2 += arr2[i] # Compute current diff which will be # used as index in diff dictionary curr_diff = presum1 - presum2 # If current diff is 0, then there # are same number of 1's so far in # both arrays, i.e., (i+1) is # maximum length. if curr_diff == 0: maxLen = i+1 elif curr_diff not in diff: # save the index for this diff diff[curr_diff] = i else: # calculate the span length length = i - diff[curr_diff] maxLen = max(maxLen, length) return maxLen # Driver program arr1 = [0, 1, 0, 1, 1, 1, 1]arr2 = [1, 1, 1, 1, 1, 0, 1]print("Length of the longest common", " span with same", end = " ")print("sum is",longestCommonSum(arr1, arr2, len(arr1))) # This code is contributed by Abhijeet Nautiyal // A O(n) and O(n) extra space C# program// to find longest common subarray of two// binary arrays with same sumusing System; class GFG{static int[] arr1 = new int[]{0, 1, 0, 1, 1, 1, 1};static int[] arr2 = new int[]{1, 1, 1, 1, 1, 0, 1}; // Returns length of the longest// common sum in arr1[] and arr2[].// Both are of same size n.static int longestCommonSum(int n){ // Initialize result int maxLen = 0; // Initialize prefix sums of // two arrays int preSum1 = 0, preSum2 = 0; // Create an array to store starting // and ending indexes of all possible // diff values. diff[i] would store // starting and ending points for // difference "i-n" int[] diff = new int[2 * n + 1]; // Initialize all starting and ending // values as -1. for (int i = 0; i < diff.Length; i++) { diff[i] = -1; } // Traverse both arrays for (int i = 0; i < n; i++) { // Update prefix sums preSum1 += arr1[i]; preSum2 += arr2[i]; // Compute current diff and index to // be used in diff array. Note that // diff can be negative and can have // minimum value as -1. int curr_diff = preSum1 - preSum2; int diffIndex = n + curr_diff; // If current diff is 0, then there // are same number of 1's so far in // both arrays, i.e., (i+1) is // maximum length. if (curr_diff == 0) maxLen = i + 1; // If current diff is seen first time, // then update starting index of diff. else if ( diff[diffIndex] == -1) diff[diffIndex] = i; // Current diff is already seen else { // Find length of this same // sum common span int len = i - diff[diffIndex]; // Update max len if needed if (len > maxLen) maxLen = len; } } return maxLen;} // Driver Codepublic static void Main(){ Console.Write("Length of the longest common " + "span with same sum is "); Console.WriteLine(longestCommonSum(arr1.Length));}} // This code is contributed// by Akanksha Rai(Abby_akku) <script> // A O(n) and O(n) extra space // Javascript program to find longest // common subarray of two binary arrays // with same sum let arr1 = [0, 1, 0, 1, 1, 1, 1]; let arr2 = [1, 1, 1, 1, 1, 0, 1]; // Returns length of the longest // common sum in arr1[] and arr2[]. // Both are of same size n. function longestCommonSum(n) { // Initialize result let maxLen = 0; // Initialize prefix sums of // two arrays let preSum1 = 0, preSum2 = 0; // Create an array to store starting // and ending indexes of all possible // diff values. diff[i] would store // starting and ending points for // difference "i-n" let diff = new Array(2 * n + 1); // Initialize all starting and ending // values as -1. for (let i = 0; i < diff.length; i++) { diff[i] = -1; } // Traverse both arrays for (let i = 0; i < n; i++) { // Update prefix sums preSum1 += arr1[i]; preSum2 += arr2[i]; // Compute current diff and index to // be used in diff array. Note that // diff can be negative and can have // minimum value as -1. let curr_diff = preSum1 - preSum2; let diffIndex = n + curr_diff; // If current diff is 0, then there // are same number of 1's so far in // both arrays, i.e., (i+1) is // maximum length. if (curr_diff == 0) maxLen = i + 1; // If current diff is seen first time, // then update starting index of diff. else if ( diff[diffIndex] == -1) diff[diffIndex] = i; // Current diff is already seen else { // Find length of this same // sum common span let len = i - diff[diffIndex]; // Update max len if needed if (len > maxLen) maxLen = len; } } return maxLen; } document.write("Length of the longest common " + "span with same sum is "); document.write(longestCommonSum(arr1.length)); </script> Output: Length of the longest common span with same sum is 6 Time Complexity: O(n) Auxiliary Space: O(n) Method 3 (Using Hashing) Find difference array arr[] such that arr[i] = arr1[i] – arr2[i].Largest subarray with equal number of 0s and 1s in the difference array. Find difference array arr[] such that arr[i] = arr1[i] – arr2[i]. Largest subarray with equal number of 0s and 1s in the difference array. C++ Java Python3 C# Javascript // C++ program to find largest subarray// with equal number of 0's and 1's.#include <bits/stdc++.h>using namespace std; // Returns largest common subarray with equal// number of 0s and 1s in both of tint longestCommonSum(bool arr1[], bool arr2[], int n){ // Find difference between the two int arr[n]; for (int i=0; i<n; i++) arr[i] = arr1[i] - arr2[i]; // Creates an empty hashMap hM unordered_map<int, int> hM; int sum = 0; // Initialize sum of elements int max_len = 0; // Initialize result // Traverse through the given array for (int i = 0; i < n; i++) { // Add current element to sum sum += arr[i]; // To handle sum=0 at last index if (sum == 0) max_len = i + 1; // If this sum is seen before, // then update max_len if required if (hM.find(sum) != hM.end()) max_len = max(max_len, i - hM[sum]); else // Else put this sum in hash table hM[sum] = i; } return max_len;} // Driver program to test above functionint main(){ bool arr1[] = {0, 1, 0, 1, 1, 1, 1}; bool arr2[] = {1, 1, 1, 1, 1, 0, 1}; int n = sizeof(arr1)/sizeof(arr1[0]); cout << longestCommonSum(arr1, arr2, n); return 0;} // Java program to find largest subarray// with equal number of 0's and 1's.import java.io.*;import java.util.*; class GFG{ // Returns largest common subarray with equal // number of 0s and 1s static int longestCommonSum(int[] arr1, int[] arr2, int n) { // Find difference between the two int[] arr = new int[n]; for (int i = 0; i < n; i++) arr[i] = arr1[i] - arr2[i]; // Creates an empty hashMap hM HashMap<Integer, Integer> hM = new HashMap<>(); int sum = 0; // Initialize sum of elements int max_len = 0; // Initialize result // Traverse through the given array for (int i = 0; i < n; i++) { // Add current element to sum sum += arr[i]; // To handle sum=0 at last index if (sum == 0) max_len = i + 1; // If this sum is seen before, // then update max_len if required if (hM.containsKey(sum)) max_len = Math.max(max_len, i - hM.get(sum)); else // Else put this sum in hash table hM.put(sum, i); } return max_len; } // Driver code public static void main(String args[]) { int[] arr1 = {0, 1, 0, 1, 1, 1, 1}; int[] arr2 = {1, 1, 1, 1, 1, 0, 1}; int n = arr1.length; System.out.println(longestCommonSum(arr1, arr2, n)); }} // This code is contributed by rachana soma # Python program to find largest subarray # with equal number of 0's and 1's. # Returns largest common subarray with equal # number of 0s and 1sdef longestCommonSum(arr1, arr2, n): # Find difference between the two arr = [0 for i in range(n)] for i in range(n): arr[i] = arr1[i] - arr2[i]; # Creates an empty hashMap hM hm = {} sum = 0 # Initialize sum of elements max_len = 0 #Initialize result # Traverse through the given array for i in range(n): # Add current element to sum sum += arr[i] # To handle sum=0 at last index if (sum == 0): max_len = i + 1 # If this sum is seen before, # then update max_len if required if sum in hm: max_len = max(max_len, i - hm[sum]) else: # Else put this sum in hash table hm[sum] = i return max_len # Driver codearr1 = [0, 1, 0, 1, 1, 1, 1]arr2 = [1, 1, 1, 1, 1, 0, 1]n = len(arr1)print(longestCommonSum(arr1, arr2, n)) # This code is contributed by rag2127 // C# program to find largest subarray// with equal number of 0's and 1's.using System;using System.Collections.Generic;public class GFG{ // Returns largest common subarray with equal // number of 0s and 1s static int longestCommonSum(int[] arr1, int[] arr2, int n) { // Find difference between the two int[] arr = new int[n]; for (int i = 0; i < n; i++) arr[i] = arr1[i] - arr2[i]; // Creates an empty hashMap hM Dictionary<int,int> hM = new Dictionary<int,int>(); int sum = 0; // Initialize sum of elements int max_len = 0; // Initialize result // Traverse through the given array for (int i = 0; i < n; i++) { // Add current element to sum sum += arr[i]; // To handle sum=0 at last index if (sum == 0) max_len = i + 1; // If this sum is seen before, // then update max_len if required if (hM.ContainsKey(sum)) max_len = Math.Max(max_len, i - hM[sum]); else // Else put this sum in hash table hM[sum] = i; } return max_len; } // Driver code static public void Main () { int[] arr1 = {0, 1, 0, 1, 1, 1, 1}; int[] arr2 = {1, 1, 1, 1, 1, 0, 1}; int n = arr1.Length; Console.WriteLine(longestCommonSum(arr1, arr2, n)); }} // This code is contributed by avanitrachhadiya2155 <script>// Javascript program to find largest subarray// with equal number of 0's and 1's. // Returns largest common subarray with equal// number of 0s and 1sfunction longestCommonSum(arr1,arr2,n){ // Find difference between the two let arr = new Array(n); for (let i = 0; i < n; i++) arr[i] = arr1[i] - arr2[i]; // Creates an empty hashMap hM let hM = new Map(); let sum = 0; // Initialize sum of elements let max_len = 0; // Initialize result // Traverse through the given array for (let i = 0; i < n; i++) { // Add current element to sum sum += arr[i]; // To handle sum=0 at last index if (sum == 0) max_len = i + 1; // If this sum is seen before, // then update max_len if required if (hM.has(sum)) max_len = Math.max(max_len, i - hM.get(sum)); else // Else put this sum in hash table hM.set(sum, i); } return max_len;} // Driver codelet arr1=[0, 1, 0, 1, 1, 1, 1];let arr2=[1, 1, 1, 1, 1, 0, 1];let n = arr1.length;document.write(longestCommonSum(arr1, arr2, n)); // This code is contributed by ab2127</script> Output: 6 Time Complexity: O(n) (As the array is traversed only once.)Auxiliary Space: O(n) (As hashmap has been used which takes extra space.) https://www.youtube.com/watch?v=xtfj4 -r_AhsThis article is contributed by Sumit Gupta. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above jit_t ukasp Akanksha_Rai rachana soma Shivam_k shubham_singh rag2127 avanitrachhadiya2155 rameshtravel07 divyeshrabadiya07 ab2127 kk9826225 rajeev0719singh gulshankumarar231 sumitgumber28 isha307 binary-string cpp-unordered_map prefix-sum Arrays prefix-sum Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Arrays in Java Write a program to reverse an array or string Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Largest Sum Contiguous Subarray Arrays in C/C++ Multidimensional Arrays in Java Stack Data Structure (Introduction and Program) Linear Search Subset Sum Problem | DP-25
[ { "code": null, "e": 52, "s": 24, "text": "\n22 Jun, 2022" }, { "code": null, "e": 302, "s": 52, "text": "Given two binary arrays, arr1[] and arr2[] of the same size n. Find the length of the longest common span (i, j) where j >= i such that arr1[i] + arr1[i+1] + .... + arr1[j] = arr2[i] + arr2[i+1] + .... + arr2[j].The expected time complexity is Θ(n)." }, { "code": null, "e": 314, "s": 302, "text": "Examples: " }, { "code": null, "e": 728, "s": 314, "text": "Input: arr1[] = {0, 1, 0, 0, 0, 0};\n arr2[] = {1, 0, 1, 0, 0, 1};\nOutput: 4\nThe longest span with same sum is from index 1 to 4.\n\nInput: arr1[] = {0, 1, 0, 1, 1, 1, 1};\n arr2[] = {1, 1, 1, 1, 1, 0, 1};\nOutput: 6\nThe longest span with same sum is from index 1 to 6.\n\nInput: arr1[] = {0, 0, 0};\n arr2[] = {1, 1, 1};\nOutput: 0\n\nInput: arr1[] = {0, 0, 1, 0};\n arr2[] = {1, 1, 1, 1};\nOutput: 1 " }, { "code": null, "e": 984, "s": 728, "text": "Method 1 (Simple Solution) One by one by consider same subarrays of both arrays. For all subarrays, compute sums and if sums are same and current length is more than max length, then update max length. Below is C++ implementation of the simple approach. " }, { "code": null, "e": 988, "s": 984, "text": "C++" }, { "code": null, "e": 993, "s": 988, "text": "Java" }, { "code": null, "e": 1001, "s": 993, "text": "Python3" }, { "code": null, "e": 1004, "s": 1001, "text": "C#" }, { "code": null, "e": 1008, "s": 1004, "text": "PHP" }, { "code": null, "e": 1019, "s": 1008, "text": "Javascript" }, { "code": "// A Simple C++ program to find longest common// subarray of two binary arrays with same sum#include<bits/stdc++.h>using namespace std; // Returns length of the longest common subarray// with same sumint longestCommonSum(bool arr1[], bool arr2[], int n){ // Initialize result int maxLen = 0; // One by one pick all possible starting points // of subarrays for (int i=0; i<n; i++) { // Initialize sums of current subarrays int sum1 = 0, sum2 = 0; // Consider all points for starting with arr[i] for (int j=i; j<n; j++) { // Update sums sum1 += arr1[j]; sum2 += arr2[j]; // If sums are same and current length is // more than maxLen, update maxLen if (sum1 == sum2) { int len = j-i+1; if (len > maxLen) maxLen = len; } } } return maxLen;} // Driver program to test above functionint main(){ bool arr1[] = {0, 1, 0, 1, 1, 1, 1}; bool arr2[] = {1, 1, 1, 1, 1, 0, 1}; int n = sizeof(arr1)/sizeof(arr1[0]); cout << \"Length of the longest common span with same \" \"sum is \"<< longestCommonSum(arr1, arr2, n); return 0;}", "e": 2241, "s": 1019, "text": null }, { "code": "// A Simple Java program to find longest common// subarray of two binary arrays with same sum class Test{ static int arr1[] = new int[]{0, 1, 0, 1, 1, 1, 1}; static int arr2[] = new int[]{1, 1, 1, 1, 1, 0, 1}; // Returns length of the longest common sum in arr1[] // and arr2[]. Both are of same size n. static int longestCommonSum(int n) { // Initialize result int maxLen = 0; // One by one pick all possible starting points // of subarrays for (int i=0; i<n; i++) { // Initialize sums of current subarrays int sum1 = 0, sum2 = 0; // Consider all points for starting with arr[i] for (int j=i; j<n; j++) { // Update sums sum1 += arr1[j]; sum2 += arr2[j]; // If sums are same and current length is // more than maxLen, update maxLen if (sum1 == sum2) { int len = j-i+1; if (len > maxLen) maxLen = len; } } } return maxLen; } // Driver method to test the above function public static void main(String[] args) { System.out.print(\"Length of the longest common span with same sum is \"); System.out.println(longestCommonSum(arr1.length)); }}", "e": 3631, "s": 2241, "text": null }, { "code": "# A Simple python program to find longest common# subarray of two binary arrays with same sum # Returns length of the longest common subarray# with same sumdef longestCommonSum(arr1, arr2, n): # Initialize result maxLen = 0 # One by one pick all possible starting points # of subarrays for i in range(0,n): # Initialize sums of current subarrays sum1 = 0 sum2 = 0 # Consider all points for starting with arr[i] for j in range(i,n): # Update sums sum1 += arr1[j] sum2 += arr2[j] # If sums are same and current length is # more than maxLen, update maxLen if (sum1 == sum2): len = j-i+1 if (len > maxLen): maxLen = len return maxLen # Driver program to test above functionarr1 = [0, 1, 0, 1, 1, 1, 1]arr2 = [1, 1, 1, 1, 1, 0, 1]n = len(arr1)print(\"Length of the longest common span with same \" \"sum is\",longestCommonSum(arr1, arr2, n)) # This code is contributed by# Smitha Dinesh Semwal", "e": 4711, "s": 3631, "text": null }, { "code": "// A Simple C# program to find// longest common subarray of// two binary arrays with same sumusing System; class GFG{static int[] arr1 = new int[]{0, 1, 0, 1, 1, 1, 1};static int[] arr2 = new int[]{1, 1, 1, 1, 1, 0, 1}; // Returns length of the longest// common sum in arr1[] and arr2[].// Both are of same size n.static int longestCommonSum(int n){ // Initialize result int maxLen = 0; // One by one pick all possible // starting points of subarrays for (int i = 0; i < n; i++) { // Initialize sums of current // subarrays int sum1 = 0, sum2 = 0; // Consider all points for // starting with arr[i] for (int j = i; j < n; j++) { // Update sums sum1 += arr1[j]; sum2 += arr2[j]; // If sums are same and current // length is more than maxLen, // update maxLen if (sum1 == sum2) { int len = j - i + 1; if (len > maxLen) maxLen = len; } } } return maxLen;} // Driver Codepublic static void Main(){ Console.Write(\"Length of the longest \" + \"common span with same sum is \"); Console.Write(longestCommonSum(arr1.Length));}} // This code is contributed// by ChitraNayal", "e": 5940, "s": 4711, "text": null }, { "code": "<?php// A Simple PHP program to find// longest common subarray of// two binary arrays with same sum // Returns length of the longest// common subarray with same sumfunction longestCommonSum($arr1, $arr2, $n){ // Initialize result $maxLen = 0; // One by one pick all possible // starting points of subarrays for ($i = 0; $i < $n; $i++) { // Initialize sums of // current subarrays $sum1 = 0; $sum2 = 0; // Consider all points // for starting with arr[i] for ($j = $i; $j < $n; $j++) { // Update sums $sum1 += $arr1[$j]; $sum2 += $arr2[$j]; // If sums are same and current // length is more than maxLen, // update maxLen if ($sum1 == $sum2) { $len = $j - $i + 1; if ($len > $maxLen) $maxLen = $len; } } } return $maxLen;} // Driver Code$arr1 = array(0, 1, 0, 1, 1, 1, 1);$arr2 = array (1, 1, 1, 1, 1, 0, 1);$n = sizeof($arr1);echo \"Length of the longest common span \". \"with same \", \"sum is \", longestCommonSum($arr1, $arr2, $n); // This code is contributed by aj_36?>", "e": 7081, "s": 5940, "text": null }, { "code": "<script> // A Simple Javascript program to find // longest common subarray of // two binary arrays with same sum let arr1 = [0, 1, 0, 1, 1, 1, 1]; let arr2 = [1, 1, 1, 1, 1, 0, 1]; // Returns length of the longest // common sum in arr1[] and arr2[]. // Both are of same size n. function longestCommonSum(n) { // Initialize result let maxLen = 0; // One by one pick all possible // starting points of subarrays for (let i = 0; i < n; i++) { // Initialize sums of current // subarrays let sum1 = 0, sum2 = 0; // Consider all points for // starting with arr[i] for (let j = i; j < n; j++) { // Update sums sum1 += arr1[j]; sum2 += arr2[j]; // If sums are same and current // length is more than maxLen, // update maxLen if (sum1 == sum2) { let len = j - i + 1; if (len > maxLen) maxLen = len; } } } return maxLen; } document.write(\"Length of the longest \" + \"common span with same sum is \"); document.write(longestCommonSum(arr1.length)); </script>", "e": 8385, "s": 7081, "text": null }, { "code": null, "e": 8395, "s": 8385, "text": "Output : " }, { "code": null, "e": 8448, "s": 8395, "text": "Length of the longest common span with same sum is 6" }, { "code": null, "e": 8498, "s": 8448, "text": "Time Complexity : O(n2) Auxiliary Space : O(1) " }, { "code": null, "e": 8507, "s": 8498, "text": "Chapters" }, { "code": null, "e": 8534, "s": 8507, "text": "descriptions off, selected" }, { "code": null, "e": 8584, "s": 8534, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 8607, "s": 8584, "text": "captions off, selected" }, { "code": null, "e": 8615, "s": 8607, "text": "English" }, { "code": null, "e": 8639, "s": 8615, "text": "This is a modal window." }, { "code": null, "e": 8708, "s": 8639, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 8730, "s": 8708, "text": "End of dialog window." }, { "code": null, "e": 8809, "s": 8730, "text": "Method 2 (Using Auxiliary Array) The idea is based on the below observations. " }, { "code": null, "e": 9116, "s": 8809, "text": "Since there are total n elements, maximum sum is n for both arrays.The difference between two sums varies from -n to n. So there are total 2n + 1 possible values of difference.If differences between prefix sums of two arrays become same at two points, then subarrays between these two points have same sum." }, { "code": null, "e": 9184, "s": 9116, "text": "Since there are total n elements, maximum sum is n for both arrays." }, { "code": null, "e": 9294, "s": 9184, "text": "The difference between two sums varies from -n to n. So there are total 2n + 1 possible values of difference." }, { "code": null, "e": 9425, "s": 9294, "text": "If differences between prefix sums of two arrays become same at two points, then subarrays between these two points have same sum." }, { "code": null, "e": 9460, "s": 9425, "text": "Below is the Complete Algorithm. " }, { "code": null, "e": 10399, "s": 9460, "text": "Create an auxiliary array of size 2n+1 to store starting points of all possible values of differences (Note that possible values of differences vary from -n to n, i.e., there are total 2n+1 possible values)Initialize starting points of all differences as -1.Initialize maxLen as 0 and prefix sums of both arrays as 0, preSum1 = 0, preSum2 = 0Traverse both arrays from i = 0 to n-1. Update prefix sums: preSum1 += arr1[i], preSum2 += arr2[i]Compute difference of current prefix sums: curr_diff = preSum1 – preSum2Find index in diff array: diffIndex = n + curr_diff // curr_diff can be negative and can go till -nIf curr_diff is 0, then i+1 is maxLen so farElse If curr_diff is seen first time, i.e., starting point of current diff is -1, then update starting point as iElse (curr_diff is NOT seen first time), then consider i as ending point and find length of current same sum span. If this length is more, then update maxLenReturn maxLen" }, { "code": null, "e": 10606, "s": 10399, "text": "Create an auxiliary array of size 2n+1 to store starting points of all possible values of differences (Note that possible values of differences vary from -n to n, i.e., there are total 2n+1 possible values)" }, { "code": null, "e": 10659, "s": 10606, "text": "Initialize starting points of all differences as -1." }, { "code": null, "e": 10744, "s": 10659, "text": "Initialize maxLen as 0 and prefix sums of both arrays as 0, preSum1 = 0, preSum2 = 0" }, { "code": null, "e": 11328, "s": 10744, "text": "Traverse both arrays from i = 0 to n-1. Update prefix sums: preSum1 += arr1[i], preSum2 += arr2[i]Compute difference of current prefix sums: curr_diff = preSum1 – preSum2Find index in diff array: diffIndex = n + curr_diff // curr_diff can be negative and can go till -nIf curr_diff is 0, then i+1 is maxLen so farElse If curr_diff is seen first time, i.e., starting point of current diff is -1, then update starting point as iElse (curr_diff is NOT seen first time), then consider i as ending point and find length of current same sum span. If this length is more, then update maxLen" }, { "code": null, "e": 11872, "s": 11328, "text": "Update prefix sums: preSum1 += arr1[i], preSum2 += arr2[i]Compute difference of current prefix sums: curr_diff = preSum1 – preSum2Find index in diff array: diffIndex = n + curr_diff // curr_diff can be negative and can go till -nIf curr_diff is 0, then i+1 is maxLen so farElse If curr_diff is seen first time, i.e., starting point of current diff is -1, then update starting point as iElse (curr_diff is NOT seen first time), then consider i as ending point and find length of current same sum span. If this length is more, then update maxLen" }, { "code": null, "e": 11931, "s": 11872, "text": "Update prefix sums: preSum1 += arr1[i], preSum2 += arr2[i]" }, { "code": null, "e": 12004, "s": 11931, "text": "Compute difference of current prefix sums: curr_diff = preSum1 – preSum2" }, { "code": null, "e": 12104, "s": 12004, "text": "Find index in diff array: diffIndex = n + curr_diff // curr_diff can be negative and can go till -n" }, { "code": null, "e": 12149, "s": 12104, "text": "If curr_diff is 0, then i+1 is maxLen so far" }, { "code": null, "e": 12263, "s": 12149, "text": "Else If curr_diff is seen first time, i.e., starting point of current diff is -1, then update starting point as i" }, { "code": null, "e": 12421, "s": 12263, "text": "Else (curr_diff is NOT seen first time), then consider i as ending point and find length of current same sum span. If this length is more, then update maxLen" }, { "code": null, "e": 12435, "s": 12421, "text": "Return maxLen" }, { "code": null, "e": 12485, "s": 12435, "text": "Below is the implementation of above algorithm. " }, { "code": null, "e": 12489, "s": 12485, "text": "C++" }, { "code": null, "e": 12494, "s": 12489, "text": "Java" }, { "code": null, "e": 12501, "s": 12494, "text": "Python" }, { "code": null, "e": 12504, "s": 12501, "text": "C#" }, { "code": null, "e": 12515, "s": 12504, "text": "Javascript" }, { "code": "// A O(n) and O(n) extra space C++ program to find// longest common subarray of two binary arrays with// same sum#include<bits/stdc++.h>using namespace std; // Returns length of the longest common sum in arr1[]// and arr2[]. Both are of same size n.int longestCommonSum(bool arr1[], bool arr2[], int n){ // Initialize result int maxLen = 0; // Initialize prefix sums of two arrays int preSum1 = 0, preSum2 = 0; // Create an array to store starting and ending // indexes of all possible diff values. diff[i] // would store starting and ending points for // difference \"i-n\" int diff[2*n+1]; // Initialize all starting and ending values as -1. memset(diff, -1, sizeof(diff)); // Traverse both arrays for (int i=0; i<n; i++) { // Update prefix sums preSum1 += arr1[i]; preSum2 += arr2[i]; // Compute current diff and index to be used // in diff array. Note that diff can be negative // and can have minimum value as -1. int curr_diff = preSum1 - preSum2; int diffIndex = n + curr_diff; // If current diff is 0, then there are same number // of 1's so far in both arrays, i.e., (i+1) is // maximum length. if (curr_diff == 0) maxLen = i+1; // If current diff is seen first time, then update // starting index of diff. else if ( diff[diffIndex] == -1) diff[diffIndex] = i; // Current diff is already seen else { // Find length of this same sum common span int len = i - diff[diffIndex]; // Update max len if needed if (len > maxLen) maxLen = len; } } return maxLen;} // Driver codeint main(){ bool arr1[] = {0, 1, 0, 1, 1, 1, 1}; bool arr2[] = {1, 1, 1, 1, 1, 0, 1}; int n = sizeof(arr1)/sizeof(arr1[0]); cout << \"Length of the longest common span with same \" \"sum is \"<< longestCommonSum(arr1, arr2, n); return 0;}", "e": 14525, "s": 12515, "text": null }, { "code": "// A O(n) and O(n) extra space Java program to find// longest common subarray of two binary arrays with// same sum class Test{ static int arr1[] = new int[]{0, 1, 0, 1, 1, 1, 1}; static int arr2[] = new int[]{1, 1, 1, 1, 1, 0, 1}; // Returns length of the longest common sum in arr1[] // and arr2[]. Both are of same size n. static int longestCommonSum(int n) { // Initialize result int maxLen = 0; // Initialize prefix sums of two arrays int preSum1 = 0, preSum2 = 0; // Create an array to store starting and ending // indexes of all possible diff values. diff[i] // would store starting and ending points for // difference \"i-n\" int diff[] = new int[2*n+1]; // Initialize all starting and ending values as -1. for (int i = 0; i < diff.length; i++) { diff[i] = -1; } // Traverse both arrays for (int i=0; i<n; i++) { // Update prefix sums preSum1 += arr1[i]; preSum2 += arr2[i]; // Compute current diff and index to be used // in diff array. Note that diff can be negative // and can have minimum value as -1. int curr_diff = preSum1 - preSum2; int diffIndex = n + curr_diff; // If current diff is 0, then there are same number // of 1's so far in both arrays, i.e., (i+1) is // maximum length. if (curr_diff == 0) maxLen = i+1; // If current diff is seen first time, then update // starting index of diff. else if ( diff[diffIndex] == -1) diff[diffIndex] = i; // Current diff is already seen else { // Find length of this same sum common span int len = i - diff[diffIndex]; // Update max len if needed if (len > maxLen) maxLen = len; } } return maxLen; } // Driver method to test the above function public static void main(String[] args) { System.out.print(\"Length of the longest common span with same sum is \"); System.out.println(longestCommonSum(arr1.length)); }}", "e": 16853, "s": 14525, "text": null }, { "code": "# Python program to find longest common# subarray of two binary arrays with# same sum def longestCommonSum(arr1, arr2, n): # Initialize result maxLen = 0 # Initialize prefix sums of two arrays presum1 = presum2 = 0 # Create a dictionary to store indices # of all possible sums diff = {} # Traverse both arrays for i in range(n): # Update prefix sums presum1 += arr1[i] presum2 += arr2[i] # Compute current diff which will be # used as index in diff dictionary curr_diff = presum1 - presum2 # If current diff is 0, then there # are same number of 1's so far in # both arrays, i.e., (i+1) is # maximum length. if curr_diff == 0: maxLen = i+1 elif curr_diff not in diff: # save the index for this diff diff[curr_diff] = i else: # calculate the span length length = i - diff[curr_diff] maxLen = max(maxLen, length) return maxLen # Driver program arr1 = [0, 1, 0, 1, 1, 1, 1]arr2 = [1, 1, 1, 1, 1, 0, 1]print(\"Length of the longest common\", \" span with same\", end = \" \")print(\"sum is\",longestCommonSum(arr1, arr2, len(arr1))) # This code is contributed by Abhijeet Nautiyal", "e": 18202, "s": 16853, "text": null }, { "code": "// A O(n) and O(n) extra space C# program// to find longest common subarray of two// binary arrays with same sumusing System; class GFG{static int[] arr1 = new int[]{0, 1, 0, 1, 1, 1, 1};static int[] arr2 = new int[]{1, 1, 1, 1, 1, 0, 1}; // Returns length of the longest// common sum in arr1[] and arr2[].// Both are of same size n.static int longestCommonSum(int n){ // Initialize result int maxLen = 0; // Initialize prefix sums of // two arrays int preSum1 = 0, preSum2 = 0; // Create an array to store starting // and ending indexes of all possible // diff values. diff[i] would store // starting and ending points for // difference \"i-n\" int[] diff = new int[2 * n + 1]; // Initialize all starting and ending // values as -1. for (int i = 0; i < diff.Length; i++) { diff[i] = -1; } // Traverse both arrays for (int i = 0; i < n; i++) { // Update prefix sums preSum1 += arr1[i]; preSum2 += arr2[i]; // Compute current diff and index to // be used in diff array. Note that // diff can be negative and can have // minimum value as -1. int curr_diff = preSum1 - preSum2; int diffIndex = n + curr_diff; // If current diff is 0, then there // are same number of 1's so far in // both arrays, i.e., (i+1) is // maximum length. if (curr_diff == 0) maxLen = i + 1; // If current diff is seen first time, // then update starting index of diff. else if ( diff[diffIndex] == -1) diff[diffIndex] = i; // Current diff is already seen else { // Find length of this same // sum common span int len = i - diff[diffIndex]; // Update max len if needed if (len > maxLen) maxLen = len; } } return maxLen;} // Driver Codepublic static void Main(){ Console.Write(\"Length of the longest common \" + \"span with same sum is \"); Console.WriteLine(longestCommonSum(arr1.Length));}} // This code is contributed// by Akanksha Rai(Abby_akku)", "e": 20366, "s": 18202, "text": null }, { "code": "<script> // A O(n) and O(n) extra space // Javascript program to find longest // common subarray of two binary arrays // with same sum let arr1 = [0, 1, 0, 1, 1, 1, 1]; let arr2 = [1, 1, 1, 1, 1, 0, 1]; // Returns length of the longest // common sum in arr1[] and arr2[]. // Both are of same size n. function longestCommonSum(n) { // Initialize result let maxLen = 0; // Initialize prefix sums of // two arrays let preSum1 = 0, preSum2 = 0; // Create an array to store starting // and ending indexes of all possible // diff values. diff[i] would store // starting and ending points for // difference \"i-n\" let diff = new Array(2 * n + 1); // Initialize all starting and ending // values as -1. for (let i = 0; i < diff.length; i++) { diff[i] = -1; } // Traverse both arrays for (let i = 0; i < n; i++) { // Update prefix sums preSum1 += arr1[i]; preSum2 += arr2[i]; // Compute current diff and index to // be used in diff array. Note that // diff can be negative and can have // minimum value as -1. let curr_diff = preSum1 - preSum2; let diffIndex = n + curr_diff; // If current diff is 0, then there // are same number of 1's so far in // both arrays, i.e., (i+1) is // maximum length. if (curr_diff == 0) maxLen = i + 1; // If current diff is seen first time, // then update starting index of diff. else if ( diff[diffIndex] == -1) diff[diffIndex] = i; // Current diff is already seen else { // Find length of this same // sum common span let len = i - diff[diffIndex]; // Update max len if needed if (len > maxLen) maxLen = len; } } return maxLen; } document.write(\"Length of the longest common \" + \"span with same sum is \"); document.write(longestCommonSum(arr1.length)); </script>", "e": 22636, "s": 20366, "text": null }, { "code": null, "e": 22645, "s": 22636, "text": "Output: " }, { "code": null, "e": 22698, "s": 22645, "text": "Length of the longest common span with same sum is 6" }, { "code": null, "e": 22743, "s": 22698, "text": "Time Complexity: O(n) Auxiliary Space: O(n) " }, { "code": null, "e": 22768, "s": 22743, "text": "Method 3 (Using Hashing)" }, { "code": null, "e": 22906, "s": 22768, "text": "Find difference array arr[] such that arr[i] = arr1[i] – arr2[i].Largest subarray with equal number of 0s and 1s in the difference array." }, { "code": null, "e": 22972, "s": 22906, "text": "Find difference array arr[] such that arr[i] = arr1[i] – arr2[i]." }, { "code": null, "e": 23045, "s": 22972, "text": "Largest subarray with equal number of 0s and 1s in the difference array." }, { "code": null, "e": 23049, "s": 23045, "text": "C++" }, { "code": null, "e": 23054, "s": 23049, "text": "Java" }, { "code": null, "e": 23062, "s": 23054, "text": "Python3" }, { "code": null, "e": 23065, "s": 23062, "text": "C#" }, { "code": null, "e": 23076, "s": 23065, "text": "Javascript" }, { "code": "// C++ program to find largest subarray// with equal number of 0's and 1's.#include <bits/stdc++.h>using namespace std; // Returns largest common subarray with equal// number of 0s and 1s in both of tint longestCommonSum(bool arr1[], bool arr2[], int n){ // Find difference between the two int arr[n]; for (int i=0; i<n; i++) arr[i] = arr1[i] - arr2[i]; // Creates an empty hashMap hM unordered_map<int, int> hM; int sum = 0; // Initialize sum of elements int max_len = 0; // Initialize result // Traverse through the given array for (int i = 0; i < n; i++) { // Add current element to sum sum += arr[i]; // To handle sum=0 at last index if (sum == 0) max_len = i + 1; // If this sum is seen before, // then update max_len if required if (hM.find(sum) != hM.end()) max_len = max(max_len, i - hM[sum]); else // Else put this sum in hash table hM[sum] = i; } return max_len;} // Driver program to test above functionint main(){ bool arr1[] = {0, 1, 0, 1, 1, 1, 1}; bool arr2[] = {1, 1, 1, 1, 1, 0, 1}; int n = sizeof(arr1)/sizeof(arr1[0]); cout << longestCommonSum(arr1, arr2, n); return 0;}", "e": 24336, "s": 23076, "text": null }, { "code": "// Java program to find largest subarray// with equal number of 0's and 1's.import java.io.*;import java.util.*; class GFG{ // Returns largest common subarray with equal // number of 0s and 1s static int longestCommonSum(int[] arr1, int[] arr2, int n) { // Find difference between the two int[] arr = new int[n]; for (int i = 0; i < n; i++) arr[i] = arr1[i] - arr2[i]; // Creates an empty hashMap hM HashMap<Integer, Integer> hM = new HashMap<>(); int sum = 0; // Initialize sum of elements int max_len = 0; // Initialize result // Traverse through the given array for (int i = 0; i < n; i++) { // Add current element to sum sum += arr[i]; // To handle sum=0 at last index if (sum == 0) max_len = i + 1; // If this sum is seen before, // then update max_len if required if (hM.containsKey(sum)) max_len = Math.max(max_len, i - hM.get(sum)); else // Else put this sum in hash table hM.put(sum, i); } return max_len; } // Driver code public static void main(String args[]) { int[] arr1 = {0, 1, 0, 1, 1, 1, 1}; int[] arr2 = {1, 1, 1, 1, 1, 0, 1}; int n = arr1.length; System.out.println(longestCommonSum(arr1, arr2, n)); }} // This code is contributed by rachana soma", "e": 25825, "s": 24336, "text": null }, { "code": "# Python program to find largest subarray # with equal number of 0's and 1's. # Returns largest common subarray with equal # number of 0s and 1sdef longestCommonSum(arr1, arr2, n): # Find difference between the two arr = [0 for i in range(n)] for i in range(n): arr[i] = arr1[i] - arr2[i]; # Creates an empty hashMap hM hm = {} sum = 0 # Initialize sum of elements max_len = 0 #Initialize result # Traverse through the given array for i in range(n): # Add current element to sum sum += arr[i] # To handle sum=0 at last index if (sum == 0): max_len = i + 1 # If this sum is seen before, # then update max_len if required if sum in hm: max_len = max(max_len, i - hm[sum]) else: # Else put this sum in hash table hm[sum] = i return max_len # Driver codearr1 = [0, 1, 0, 1, 1, 1, 1]arr2 = [1, 1, 1, 1, 1, 0, 1]n = len(arr1)print(longestCommonSum(arr1, arr2, n)) # This code is contributed by rag2127", "e": 26910, "s": 25825, "text": null }, { "code": "// C# program to find largest subarray// with equal number of 0's and 1's.using System;using System.Collections.Generic;public class GFG{ // Returns largest common subarray with equal // number of 0s and 1s static int longestCommonSum(int[] arr1, int[] arr2, int n) { // Find difference between the two int[] arr = new int[n]; for (int i = 0; i < n; i++) arr[i] = arr1[i] - arr2[i]; // Creates an empty hashMap hM Dictionary<int,int> hM = new Dictionary<int,int>(); int sum = 0; // Initialize sum of elements int max_len = 0; // Initialize result // Traverse through the given array for (int i = 0; i < n; i++) { // Add current element to sum sum += arr[i]; // To handle sum=0 at last index if (sum == 0) max_len = i + 1; // If this sum is seen before, // then update max_len if required if (hM.ContainsKey(sum)) max_len = Math.Max(max_len, i - hM[sum]); else // Else put this sum in hash table hM[sum] = i; } return max_len; } // Driver code static public void Main () { int[] arr1 = {0, 1, 0, 1, 1, 1, 1}; int[] arr2 = {1, 1, 1, 1, 1, 0, 1}; int n = arr1.Length; Console.WriteLine(longestCommonSum(arr1, arr2, n)); }} // This code is contributed by avanitrachhadiya2155", "e": 28219, "s": 26910, "text": null }, { "code": "<script>// Javascript program to find largest subarray// with equal number of 0's and 1's. // Returns largest common subarray with equal// number of 0s and 1sfunction longestCommonSum(arr1,arr2,n){ // Find difference between the two let arr = new Array(n); for (let i = 0; i < n; i++) arr[i] = arr1[i] - arr2[i]; // Creates an empty hashMap hM let hM = new Map(); let sum = 0; // Initialize sum of elements let max_len = 0; // Initialize result // Traverse through the given array for (let i = 0; i < n; i++) { // Add current element to sum sum += arr[i]; // To handle sum=0 at last index if (sum == 0) max_len = i + 1; // If this sum is seen before, // then update max_len if required if (hM.has(sum)) max_len = Math.max(max_len, i - hM.get(sum)); else // Else put this sum in hash table hM.set(sum, i); } return max_len;} // Driver codelet arr1=[0, 1, 0, 1, 1, 1, 1];let arr2=[1, 1, 1, 1, 1, 0, 1];let n = arr1.length;document.write(longestCommonSum(arr1, arr2, n)); // This code is contributed by ab2127</script>", "e": 29488, "s": 28219, "text": null }, { "code": null, "e": 29497, "s": 29488, "text": "Output: " }, { "code": null, "e": 29499, "s": 29497, "text": "6" }, { "code": null, "e": 29634, "s": 29499, "text": "Time Complexity: O(n) (As the array is traversed only once.)Auxiliary Space: O(n) (As hashmap has been used which takes extra space.)" }, { "code": null, "e": 29672, "s": 29634, "text": "https://www.youtube.com/watch?v=xtfj4" }, { "code": null, "e": 29847, "s": 29672, "text": "-r_AhsThis article is contributed by Sumit Gupta. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 29853, "s": 29847, "text": "jit_t" }, { "code": null, "e": 29859, "s": 29853, "text": "ukasp" }, { "code": null, "e": 29872, "s": 29859, "text": "Akanksha_Rai" }, { "code": null, "e": 29885, "s": 29872, "text": "rachana soma" }, { "code": null, "e": 29894, "s": 29885, "text": "Shivam_k" }, { "code": null, "e": 29908, "s": 29894, "text": "shubham_singh" }, { "code": null, "e": 29916, "s": 29908, "text": "rag2127" }, { "code": null, "e": 29937, "s": 29916, "text": "avanitrachhadiya2155" }, { "code": null, "e": 29952, "s": 29937, "text": "rameshtravel07" }, { "code": null, "e": 29970, "s": 29952, "text": "divyeshrabadiya07" }, { "code": null, "e": 29977, "s": 29970, "text": "ab2127" }, { "code": null, "e": 29987, "s": 29977, "text": "kk9826225" }, { "code": null, "e": 30003, "s": 29987, "text": "rajeev0719singh" }, { "code": null, "e": 30021, "s": 30003, "text": "gulshankumarar231" }, { "code": null, "e": 30035, "s": 30021, "text": "sumitgumber28" }, { "code": null, "e": 30043, "s": 30035, "text": "isha307" }, { "code": null, "e": 30057, "s": 30043, "text": "binary-string" }, { "code": null, "e": 30075, "s": 30057, "text": "cpp-unordered_map" }, { "code": null, "e": 30086, "s": 30075, "text": "prefix-sum" }, { "code": null, "e": 30093, "s": 30086, "text": "Arrays" }, { "code": null, "e": 30104, "s": 30093, "text": "prefix-sum" }, { "code": null, "e": 30111, "s": 30104, "text": "Arrays" }, { "code": null, "e": 30209, "s": 30111, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30224, "s": 30209, "text": "Arrays in Java" }, { "code": null, "e": 30270, "s": 30224, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 30338, "s": 30270, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 30382, "s": 30338, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 30414, "s": 30382, "text": "Largest Sum Contiguous Subarray" }, { "code": null, "e": 30430, "s": 30414, "text": "Arrays in C/C++" }, { "code": null, "e": 30462, "s": 30430, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 30510, "s": 30462, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 30524, "s": 30510, "text": "Linear Search" } ]
Form the smallest number using at most one swap operation
20 May, 2021 Given a non-negative number num. The problem is to apply at most one swap operation on the number num so that the resultant is the smallest possible number. The number could be very large so a string type can be used to store the number. The input does not contain leading 0’s and the output should also not contain leading 0’s. Note: The same set of digits should be there in the resultant number as was there in the original number.Examples: Input : n = 9625635 Output : 2695635 Swapped the digits 9 and 2. Input : n = 1205763 Output : 1025763 Approach: Create an array rightMin[]. rightMin[i] contains the index of the smallest digit which is on the right side of num[i] and also smaller than num[i]. If no such digit exists then rightMin[i] = -1. Now, check that whether num[0] has a right smaller digit which is not equal to 0. If so then swap 1st digit with its right smaller digit. Else, traverse the rightMin[] array from i = 1 to n-1(where n is the total number of digits in num), and find the first element having rightMin[i] != -1. Perform the swap(num[i], num[rightMin[i]]) operation and break. C++ Java Python 3 C# PHP Javascript // C++ implementation to form the smallest// number using at most one swap operation#include <bits/stdc++.h>using namespace std; // function to form the smallest number// using at most one swap operationstring smallestNumber(string num){ int n = num.size(); int rightMin[n], right; // for the rightmost digit, there // will be no smaller right digit rightMin[n - 1] = -1; // index of the smallest right digit // till the current index from the // right direction right = n - 1; // traverse the array from second // right element up to the left // element for (int i = n - 2; i >= 1; i--) { // if 'num[i]' is greater than // the smallest digit encountered // so far if (num[i] >= num[right]) rightMin[i] = right; else { // for cases like 120000654 or 1000000321 // rightMin will be same for all 0's // except the first from last if (num[i] == num[i + 1]) { rightMin[i] = right; } else { rightMin[i] = -1; right = i; } } } // special condition for the 1st digit so that // it is not swapped with digit '0' int small = -1; for (int i = 1; i < n; i++) if (num[i] != '0') { if (small == -1) { if (num[i] < num[0]) small = i; } else if (num[i] <= num[small]) small = i; } if (small != -1) swap(num[0], num[small]); else { // traverse the 'rightMin[]' array from // 2nd digit up to the last digit for (int i = 1; i < n; i++) { // if for the current digit, smaller // right digit exists, then swap it // with its smaller right digit and // break if (rightMin[i] != -1 && num[i] != num[rightMin[i]]) { // performing the required // swap operation swap(num[i], num[rightMin[i]]); break; } } } // required smallest number return num;} // Driver program to test aboveint main(){ string num = "9625635"; cout << "Smallest number: " << smallestNumber(num); return 0;} // Java implementation to form the smallest// number using at most one swap operationimport java.util.*;import java.lang.*; public class GeeksforGeeks { // function to form the smallest number // using at most one swap operation public static String smallestNumber(String str) { char[] num = str.toCharArray(); int n = str.length(); int[] rightMin = new int[n]; // for the rightmost digit, there // will be no smaller right digit rightMin[n - 1] = -1; // index of the smallest right digit // till the current index from the // right direction int right = n - 1; // traverse the array from second // right element up to the left // element for (int i = n - 2; i >= 1; i--) { // if 'num[i]' is greater than // the smallest digit // encountered so far if (num[i] > num[right]) rightMin[i] = right; else { // there is no smaller right // digit for 'num[i]' rightMin[i] = -1; // update 'right' index right = i; } } // special condition for the 1st // digit so that it is not swapped // with digit '0' int small = -1; for (int i = 1; i < n; i++) if (num[i] != '0') { if (small == -1) { if (num[i] < num[0]) small = i; } else if (num[i] < num[small]) small = i; } if (small != -1) { char temp; temp = num[0]; num[0] = num[small]; num[small] = temp; } else { // traverse the 'rightMin[]' // array from 2nd digit up // to the last digit for (int i = 1; i < n; i++) { // if for the current digit, // smaller right digit exists, // then swap it with its smaller // right digit and break if (rightMin[i] != -1) { // performing the required // swap operation char temp; temp = num[i]; num[i] = num[rightMin[i]]; num[rightMin[i]] = temp; break; } } } // required smallest number return (new String(num)); } // driver function public static void main(String argc[]) { String num = "9625635"; System.out.println("Smallest number: " + smallestNumber(num)); }} /*This code is contributed by Sagar Shukla.*/ # Python implementation to form the smallest# number using at most one swap operation # function to form the smallest number# using at most one swap operationdef smallestNumber(num): num = list(num) n = len(num) rightMin = [0]*n right = 0 # for the rightmost digit, there # will be no smaller right digit rightMin[n-1] = -1; # index of the smallest right digit # till the current index from the # right direction right = n-1; # traverse the array from second # right element up to the left # element for i in range(n-2, 0, -1): # if 'num[i]' is greater than # the smallest digit encountered # so far if num[i] > num[right]: rightMin[i] = right else: # there is no smaller right # digit for 'num[i]' rightMin[i] = -1 # update 'right' index right = i # special condition for the 1st digit so that # it is not swapped with digit '0' small = -1 for i in range(1, n): if num[i] != '0': if small == -1: if num[i] < num[0]: small = i elif num[i] < num[small]: small = i if small != -1: num[0], num[small] = num[small], num[0] else: # traverse the 'rightMin[]' array from # 2nd digit up to the last digit for i in range(1, n): # if for the current digit, smaller # right digit exists, then swap it # with its smaller right digit and # break if rightMin[i] != -1: # performing the required # swap operation num[i], num[rightMin[i]] = num[rightMin[i]], num[i] break # required smallest number return ''.join(num) # Driver Codeif __name__ == "__main__": num = "9625635" print("Smallest number: ", smallestNumber(num)) # This code is contributed by# sanjeev2552 // C# implementation to form the smallest// number using at most one swap operation.using System; public class GeeksforGeeks { // function to form the smallest number // using at most one swap operation public static String smallestNumber(String str) { char[] num = str.ToCharArray(); int n = str.Length; int[] rightMin = new int[n]; // for the rightmost digit, there // will be no smaller right digit rightMin[n - 1] = -1; // index of the smallest right digit // till the current index from the // right direction int right = n - 1; // traverse the array from second // right element up to the left // element for (int i = n - 2; i >= 1; i--) { // if 'num[i]' is greater than // the smallest digit // encountered so far if (num[i] > num[right]) rightMin[i] = right; else { // there is no smaller right // digit for 'num[i]' rightMin[i] = -1; // update 'right' index right = i; } } // special condition for the 1st // digit so that it is not swapped // with digit '0' int small = -1; for (int i = 1; i < n; i++) if (num[i] != '0') { if (small == -1) { if (num[i] < num[0]) small = i; } else if (num[i] < num[small]) small = i; } if (small != -1) { char temp; temp = num[0]; num[0] = num[small]; num[small] = temp; } else { // traverse the 'rightMin[]' // array from 2nd digit up // to the last digit for (int i = 1; i < n; i++) { // if for the current digit, // smaller right digit exists, // then swap it with its smaller // right digit and break if (rightMin[i] != -1) { // performing the required // swap operation char temp; temp = num[i]; num[i] = num[rightMin[i]]; num[rightMin[i]] = temp; break; } } } // required smallest number return (new String(num)); } // Driver code public static void Main() { String num = "9625635"; Console.Write("Smallest number: " + smallestNumber(num)); }} // This code is contributed by Nitin Mittal. <?php// PHP implementation to// form the smallest number// using at most one swap// operation // function to form the// smallest number using// at most one swap operationfunction smallestNumber($num){ $n = strlen($num); $rightMin = array_fill(0, $n, -1); $right; // for the rightmost digit, // there will be no smaller // right digit $rightMin[$n - 1] = -1; // index of the smallest // right digit till the // current index from the // right direction $right = $n - 1; // traverse the array from // second right element up // to the left element for ($i = $n - 2; $i >= 1; $i--) { // if 'num[i]' is greater // than the smallest digit // encountered so far if ($num[$i] > $num[$right]) $rightMin[$i] = $right; else { // there is no smaller // right digit for 'num[i]' $rightMin[$i] = -1; // update 'right' index $right = $i; } } // special condition for // the 1st digit so that // it is not swapped with // digit '0' $small = -1; for ($i = 1; $i < $n; $i++) if ($num[$i] != '0') { if ($small == -1) { if ($num[$i] < $num[0]) $small = $i; } else if ($num[$i] < $num[$small]) $small = $i; } if ($small != -1) { $tmp = $num[0]; $num[0] = $num[$small]; $num[$small] = $tmp; } else { // traverse the 'rightMin[]' // array from 2nd digit up // to the last digit for ($i = 1; $i < $n; $i++) { // if for the current // digit, smaller right // digit exists, then // swap it with its // smaller right digit // and break if ($rightMin[$i] != -1) { // performing the required // swap operation $tmp = $num[$i]; $num[$i] = $num[$rightMin[$i]]; $num[$rightMin[$i]] = $tmp; break; } } } // required smallest number return $num;} // Driver Code$num = "9625635";echo "Smallest number: " . smallestNumber($num); // This code is contributed by mits?> <script> // Javascript implementation to form the smallest// number using at most one swap operation // function to form the smallest number// using at most one swap operationfunction smallestNumber(num){ var n = num.length; var rightMin = Array(n).fill(0), right; // for the rightmost digit, there // will be no smaller right digit rightMin[n - 1] = -1; // index of the smallest right digit // till the current index from the // right direction right = n - 1; // traverse the array from second // right element up to the left // element for (var i = n - 2; i >= 1; i--) { // if 'num[i]' is greater than // the smallest digit encountered // so far if (num[i].charCodeAt(0) >= num[right].charCodeAt(0)) rightMin[i] = right; else { // for cases like 120000654 or 1000000321 // rightMin will be same for all 0's // except the first from last if (num[i] == num[i + 1]) { rightMin[i] = right; } else { rightMin[i] = -1; right = i; } } } // special condition for the 1st digit so that // it is not swapped with digit '0' var small = -1; for (var i = 1; i < n; i++) if (num[i] != '0') { if (small == -1) { if (num[i].charCodeAt(0) < num[0].charCodeAt(0)) small = i; } else if (num[i].charCodeAt(0) <= num[small].charCodeAt(0)) small = i; } if (small != -1) { var tmp = num[0] num[0] = num[small] num[small] = tmp } else { // traverse the 'rightMin[]' array from // 2nd digit up to the last digit for (var i = 1; i < n; i++) { // if for the current digit, smaller // right digit exists, then swap it // with its smaller right digit and // break if (rightMin[i] != -1 && num[i] != num[rightMin[i]]) { // performing the required // swap operation var tmp = num[i] num[i]= num[rightMin[i]]; num[rightMin[i]] = tmp break; } } } // required smallest number return num.join('');} // Driver program to test abovevar num = "9625635".split('');document.write( "Smallest number: " + smallestNumber(num)); // This code is contributed by rrrtnx.</script> Output: Smallest number: 2695635 Time Complexity: O(n), where n is the total number of digits. Auxiliary Space: O(n), where n is the total number of digits.This article is contributed by Ayush Jauhari. 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 Mithun Kumar sanjeev2552 AchalDuggal rrrtnx number-digits Mathematical Strings Strings Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n20 May, 2021" }, { "code": null, "e": 500, "s": 54, "text": "Given a non-negative number num. The problem is to apply at most one swap operation on the number num so that the resultant is the smallest possible number. The number could be very large so a string type can be used to store the number. The input does not contain leading 0’s and the output should also not contain leading 0’s. Note: The same set of digits should be there in the resultant number as was there in the original number.Examples: " }, { "code": null, "e": 603, "s": 500, "text": "Input : n = 9625635\nOutput : 2695635\nSwapped the digits 9 and 2.\n\nInput : n = 1205763\nOutput : 1025763" }, { "code": null, "e": 1167, "s": 605, "text": "Approach: Create an array rightMin[]. rightMin[i] contains the index of the smallest digit which is on the right side of num[i] and also smaller than num[i]. If no such digit exists then rightMin[i] = -1. Now, check that whether num[0] has a right smaller digit which is not equal to 0. If so then swap 1st digit with its right smaller digit. Else, traverse the rightMin[] array from i = 1 to n-1(where n is the total number of digits in num), and find the first element having rightMin[i] != -1. Perform the swap(num[i], num[rightMin[i]]) operation and break. " }, { "code": null, "e": 1171, "s": 1167, "text": "C++" }, { "code": null, "e": 1176, "s": 1171, "text": "Java" }, { "code": null, "e": 1185, "s": 1176, "text": "Python 3" }, { "code": null, "e": 1188, "s": 1185, "text": "C#" }, { "code": null, "e": 1192, "s": 1188, "text": "PHP" }, { "code": null, "e": 1203, "s": 1192, "text": "Javascript" }, { "code": "// C++ implementation to form the smallest// number using at most one swap operation#include <bits/stdc++.h>using namespace std; // function to form the smallest number// using at most one swap operationstring smallestNumber(string num){ int n = num.size(); int rightMin[n], right; // for the rightmost digit, there // will be no smaller right digit rightMin[n - 1] = -1; // index of the smallest right digit // till the current index from the // right direction right = n - 1; // traverse the array from second // right element up to the left // element for (int i = n - 2; i >= 1; i--) { // if 'num[i]' is greater than // the smallest digit encountered // so far if (num[i] >= num[right]) rightMin[i] = right; else { // for cases like 120000654 or 1000000321 // rightMin will be same for all 0's // except the first from last if (num[i] == num[i + 1]) { rightMin[i] = right; } else { rightMin[i] = -1; right = i; } } } // special condition for the 1st digit so that // it is not swapped with digit '0' int small = -1; for (int i = 1; i < n; i++) if (num[i] != '0') { if (small == -1) { if (num[i] < num[0]) small = i; } else if (num[i] <= num[small]) small = i; } if (small != -1) swap(num[0], num[small]); else { // traverse the 'rightMin[]' array from // 2nd digit up to the last digit for (int i = 1; i < n; i++) { // if for the current digit, smaller // right digit exists, then swap it // with its smaller right digit and // break if (rightMin[i] != -1 && num[i] != num[rightMin[i]]) { // performing the required // swap operation swap(num[i], num[rightMin[i]]); break; } } } // required smallest number return num;} // Driver program to test aboveint main(){ string num = \"9625635\"; cout << \"Smallest number: \" << smallestNumber(num); return 0;}", "e": 3483, "s": 1203, "text": null }, { "code": "// Java implementation to form the smallest// number using at most one swap operationimport java.util.*;import java.lang.*; public class GeeksforGeeks { // function to form the smallest number // using at most one swap operation public static String smallestNumber(String str) { char[] num = str.toCharArray(); int n = str.length(); int[] rightMin = new int[n]; // for the rightmost digit, there // will be no smaller right digit rightMin[n - 1] = -1; // index of the smallest right digit // till the current index from the // right direction int right = n - 1; // traverse the array from second // right element up to the left // element for (int i = n - 2; i >= 1; i--) { // if 'num[i]' is greater than // the smallest digit // encountered so far if (num[i] > num[right]) rightMin[i] = right; else { // there is no smaller right // digit for 'num[i]' rightMin[i] = -1; // update 'right' index right = i; } } // special condition for the 1st // digit so that it is not swapped // with digit '0' int small = -1; for (int i = 1; i < n; i++) if (num[i] != '0') { if (small == -1) { if (num[i] < num[0]) small = i; } else if (num[i] < num[small]) small = i; } if (small != -1) { char temp; temp = num[0]; num[0] = num[small]; num[small] = temp; } else { // traverse the 'rightMin[]' // array from 2nd digit up // to the last digit for (int i = 1; i < n; i++) { // if for the current digit, // smaller right digit exists, // then swap it with its smaller // right digit and break if (rightMin[i] != -1) { // performing the required // swap operation char temp; temp = num[i]; num[i] = num[rightMin[i]]; num[rightMin[i]] = temp; break; } } } // required smallest number return (new String(num)); } // driver function public static void main(String argc[]) { String num = \"9625635\"; System.out.println(\"Smallest number: \" + smallestNumber(num)); }} /*This code is contributed by Sagar Shukla.*/", "e": 6212, "s": 3483, "text": null }, { "code": "# Python implementation to form the smallest# number using at most one swap operation # function to form the smallest number# using at most one swap operationdef smallestNumber(num): num = list(num) n = len(num) rightMin = [0]*n right = 0 # for the rightmost digit, there # will be no smaller right digit rightMin[n-1] = -1; # index of the smallest right digit # till the current index from the # right direction right = n-1; # traverse the array from second # right element up to the left # element for i in range(n-2, 0, -1): # if 'num[i]' is greater than # the smallest digit encountered # so far if num[i] > num[right]: rightMin[i] = right else: # there is no smaller right # digit for 'num[i]' rightMin[i] = -1 # update 'right' index right = i # special condition for the 1st digit so that # it is not swapped with digit '0' small = -1 for i in range(1, n): if num[i] != '0': if small == -1: if num[i] < num[0]: small = i elif num[i] < num[small]: small = i if small != -1: num[0], num[small] = num[small], num[0] else: # traverse the 'rightMin[]' array from # 2nd digit up to the last digit for i in range(1, n): # if for the current digit, smaller # right digit exists, then swap it # with its smaller right digit and # break if rightMin[i] != -1: # performing the required # swap operation num[i], num[rightMin[i]] = num[rightMin[i]], num[i] break # required smallest number return ''.join(num) # Driver Codeif __name__ == \"__main__\": num = \"9625635\" print(\"Smallest number: \", smallestNumber(num)) # This code is contributed by# sanjeev2552", "e": 8244, "s": 6212, "text": null }, { "code": "// C# implementation to form the smallest// number using at most one swap operation.using System; public class GeeksforGeeks { // function to form the smallest number // using at most one swap operation public static String smallestNumber(String str) { char[] num = str.ToCharArray(); int n = str.Length; int[] rightMin = new int[n]; // for the rightmost digit, there // will be no smaller right digit rightMin[n - 1] = -1; // index of the smallest right digit // till the current index from the // right direction int right = n - 1; // traverse the array from second // right element up to the left // element for (int i = n - 2; i >= 1; i--) { // if 'num[i]' is greater than // the smallest digit // encountered so far if (num[i] > num[right]) rightMin[i] = right; else { // there is no smaller right // digit for 'num[i]' rightMin[i] = -1; // update 'right' index right = i; } } // special condition for the 1st // digit so that it is not swapped // with digit '0' int small = -1; for (int i = 1; i < n; i++) if (num[i] != '0') { if (small == -1) { if (num[i] < num[0]) small = i; } else if (num[i] < num[small]) small = i; } if (small != -1) { char temp; temp = num[0]; num[0] = num[small]; num[small] = temp; } else { // traverse the 'rightMin[]' // array from 2nd digit up // to the last digit for (int i = 1; i < n; i++) { // if for the current digit, // smaller right digit exists, // then swap it with its smaller // right digit and break if (rightMin[i] != -1) { // performing the required // swap operation char temp; temp = num[i]; num[i] = num[rightMin[i]]; num[rightMin[i]] = temp; break; } } } // required smallest number return (new String(num)); } // Driver code public static void Main() { String num = \"9625635\"; Console.Write(\"Smallest number: \" + smallestNumber(num)); }} // This code is contributed by Nitin Mittal.", "e": 10926, "s": 8244, "text": null }, { "code": "<?php// PHP implementation to// form the smallest number// using at most one swap// operation // function to form the// smallest number using// at most one swap operationfunction smallestNumber($num){ $n = strlen($num); $rightMin = array_fill(0, $n, -1); $right; // for the rightmost digit, // there will be no smaller // right digit $rightMin[$n - 1] = -1; // index of the smallest // right digit till the // current index from the // right direction $right = $n - 1; // traverse the array from // second right element up // to the left element for ($i = $n - 2; $i >= 1; $i--) { // if 'num[i]' is greater // than the smallest digit // encountered so far if ($num[$i] > $num[$right]) $rightMin[$i] = $right; else { // there is no smaller // right digit for 'num[i]' $rightMin[$i] = -1; // update 'right' index $right = $i; } } // special condition for // the 1st digit so that // it is not swapped with // digit '0' $small = -1; for ($i = 1; $i < $n; $i++) if ($num[$i] != '0') { if ($small == -1) { if ($num[$i] < $num[0]) $small = $i; } else if ($num[$i] < $num[$small]) $small = $i; } if ($small != -1) { $tmp = $num[0]; $num[0] = $num[$small]; $num[$small] = $tmp; } else { // traverse the 'rightMin[]' // array from 2nd digit up // to the last digit for ($i = 1; $i < $n; $i++) { // if for the current // digit, smaller right // digit exists, then // swap it with its // smaller right digit // and break if ($rightMin[$i] != -1) { // performing the required // swap operation $tmp = $num[$i]; $num[$i] = $num[$rightMin[$i]]; $num[$rightMin[$i]] = $tmp; break; } } } // required smallest number return $num;} // Driver Code$num = \"9625635\";echo \"Smallest number: \" . smallestNumber($num); // This code is contributed by mits?>", "e": 13268, "s": 10926, "text": null }, { "code": "<script> // Javascript implementation to form the smallest// number using at most one swap operation // function to form the smallest number// using at most one swap operationfunction smallestNumber(num){ var n = num.length; var rightMin = Array(n).fill(0), right; // for the rightmost digit, there // will be no smaller right digit rightMin[n - 1] = -1; // index of the smallest right digit // till the current index from the // right direction right = n - 1; // traverse the array from second // right element up to the left // element for (var i = n - 2; i >= 1; i--) { // if 'num[i]' is greater than // the smallest digit encountered // so far if (num[i].charCodeAt(0) >= num[right].charCodeAt(0)) rightMin[i] = right; else { // for cases like 120000654 or 1000000321 // rightMin will be same for all 0's // except the first from last if (num[i] == num[i + 1]) { rightMin[i] = right; } else { rightMin[i] = -1; right = i; } } } // special condition for the 1st digit so that // it is not swapped with digit '0' var small = -1; for (var i = 1; i < n; i++) if (num[i] != '0') { if (small == -1) { if (num[i].charCodeAt(0) < num[0].charCodeAt(0)) small = i; } else if (num[i].charCodeAt(0) <= num[small].charCodeAt(0)) small = i; } if (small != -1) { var tmp = num[0] num[0] = num[small] num[small] = tmp } else { // traverse the 'rightMin[]' array from // 2nd digit up to the last digit for (var i = 1; i < n; i++) { // if for the current digit, smaller // right digit exists, then swap it // with its smaller right digit and // break if (rightMin[i] != -1 && num[i] != num[rightMin[i]]) { // performing the required // swap operation var tmp = num[i] num[i]= num[rightMin[i]]; num[rightMin[i]] = tmp break; } } } // required smallest number return num.join('');} // Driver program to test abovevar num = \"9625635\".split('');document.write( \"Smallest number: \" + smallestNumber(num)); // This code is contributed by rrrtnx.</script> ", "e": 15769, "s": 13268, "text": null }, { "code": null, "e": 15779, "s": 15769, "text": "Output: " }, { "code": null, "e": 15804, "s": 15779, "text": "Smallest number: 2695635" }, { "code": null, "e": 16349, "s": 15804, "text": "Time Complexity: O(n), where n is the total number of digits. Auxiliary Space: O(n), where n is the total number of digits.This article is contributed by Ayush Jauhari. 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": 16362, "s": 16349, "text": "nitin mittal" }, { "code": null, "e": 16375, "s": 16362, "text": "Mithun Kumar" }, { "code": null, "e": 16387, "s": 16375, "text": "sanjeev2552" }, { "code": null, "e": 16399, "s": 16387, "text": "AchalDuggal" }, { "code": null, "e": 16406, "s": 16399, "text": "rrrtnx" }, { "code": null, "e": 16420, "s": 16406, "text": "number-digits" }, { "code": null, "e": 16433, "s": 16420, "text": "Mathematical" }, { "code": null, "e": 16441, "s": 16433, "text": "Strings" }, { "code": null, "e": 16449, "s": 16441, "text": "Strings" }, { "code": null, "e": 16462, "s": 16449, "text": "Mathematical" } ]
ES6 | Events
23 Oct, 2019 The ES6 Events are the part of every HTML element that contains a set of events that can trigger the JavaScript code. An Event is an action or occurrence recognized by the software. It can be triggered by the user or the system. Mostly Events are used on buttons, hyperlinks, hovers, page loading, etc. All this stuff gets into action(processed) with the help of Event Handlers. Event handler: Simply, when a mentioned Event occurs it gets Handled. When the event is raised, it gets handled in the form of a set of instructions (function()). The following are some of the most commonly used HTML events: onclick: This event gets activated on a click on a button with the help of left-clicking on the mouse. With a click, the “onclick” calls the respective function() assigned to it. Example:<!DOCTYPE html><html> <head> <title> ES6 Events using onclick </title> <script> function geeks() { document.write ("A Computer" + " Science Portal for Geeks") } </script> </head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksforGeeks </h1> <h3> With a click, the “onclick” calls geeks() </h3> <input type = "button" onclick = "geeks()" value = "Click here" /> </body> </html> <!DOCTYPE html><html> <head> <title> ES6 Events using onclick </title> <script> function geeks() { document.write ("A Computer" + " Science Portal for Geeks") } </script> </head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksforGeeks </h1> <h3> With a click, the “onclick” calls geeks() </h3> <input type = "button" onclick = "geeks()" value = "Click here" /> </body> </html> Output: onmouseover and onmouseout: These event types will help us create nice effects with images or even with text as well. The “onmouseover” event triggers when you bring your mouse cursor over any element and the “onmouseout” triggers when you move your mouse cursor out from that element. Example:<!DOCTYPE html><html> <head> <title> ES6 Events using onmouseover and onmouseout </title> <script type="text/javascript"> function mouseOver() { document.getElementById("d1").style.color = "green"; document.getElementById("d2").innerHTML = "mouseOver triggered"; } function mouseOut() { document.getElementById("d1").style.color = "black"; document.getElementById("d2").innerHTML = "mouseOut triggered"; } </script></head> <body style="text-align:center;"> <h1 id="d1" onmouseover="mouseOver()" onmouseout="mouseOut()"> GeeksforGeeks </h1> <h3> when the cursor is on the element h1 the "onmouseover" gets triggers and when the cursor is out of h1 the "onmouseout" gets triggers. </h3> <p id="d2"></p></body> </html> <!DOCTYPE html><html> <head> <title> ES6 Events using onmouseover and onmouseout </title> <script type="text/javascript"> function mouseOver() { document.getElementById("d1").style.color = "green"; document.getElementById("d2").innerHTML = "mouseOver triggered"; } function mouseOut() { document.getElementById("d1").style.color = "black"; document.getElementById("d2").innerHTML = "mouseOut triggered"; } </script></head> <body style="text-align:center;"> <h1 id="d1" onmouseover="mouseOver()" onmouseout="mouseOut()"> GeeksforGeeks </h1> <h3> when the cursor is on the element h1 the "onmouseover" gets triggers and when the cursor is out of h1 the "onmouseout" gets triggers. </h3> <p id="d2"></p></body> </html> Output: onmousedown, onmouseup, onmousewheel : These event types will help us create nice effects with images or even with text as well. The “onmousedown” event triggers when you click the element and till you hold on to it when you release it “onmouseup” events triggers, “onmousewheel” event triggers when the mouse wheel is being rotated for the slightest. Example:<!DOCTYPE hmtl><html> <head> <title> ES6 Events using onmousedown, onmouseup and onmousewheel </title> <script> function mouseDown() { document.getElementById("d1").style.color = "blue"; document.getElementById("d2").innerHTML = "mouseDown triggered"; } function mouseUp() { document.getElementById("d1").style.color = "green"; document.getElementById("d2").innerHTML = "mouseUp triggered"; } function mouseWheel() { document.getElementById("d1").style.color = "violet"; document.getElementById("d2").innerHTML = "mouseWheel triggered"; } </script></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksforGeeks </h1> <p> when the mouse pointer clicks on the element h1, the text color changes to 'blue' when released changes to 'green', if the mouse wheel rotates color changes to 'violet'. </p> <input id="d1" type="button" onmousedown="mouseDown()" onmouseup="mouseUp()" onmousewheel="mouseWheel()" value="Hello Geeks" /> <p id="d2"></p></body> </html> <!DOCTYPE hmtl><html> <head> <title> ES6 Events using onmousedown, onmouseup and onmousewheel </title> <script> function mouseDown() { document.getElementById("d1").style.color = "blue"; document.getElementById("d2").innerHTML = "mouseDown triggered"; } function mouseUp() { document.getElementById("d1").style.color = "green"; document.getElementById("d2").innerHTML = "mouseUp triggered"; } function mouseWheel() { document.getElementById("d1").style.color = "violet"; document.getElementById("d2").innerHTML = "mouseWheel triggered"; } </script></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksforGeeks </h1> <p> when the mouse pointer clicks on the element h1, the text color changes to 'blue' when released changes to 'green', if the mouse wheel rotates color changes to 'violet'. </p> <input id="d1" type="button" onmousedown="mouseDown()" onmouseup="mouseUp()" onmousewheel="mouseWheel()" value="Hello Geeks" /> <p id="d2"></p></body> </html> Output: onsubmit: It’s an event that occurs when you try to validate a form before submitting it to the next action(server). You can put your form validation against this event type. With a click, the “onsubmit” calls the respective “return function()” assigned to it and takes the response from the function() in the form of true or false and decides the action. Check out this page ES6 | Validation for basic and detailed examples on “onsubmit”. Check out the following table for few mostly used Event Handlers: JavaScript-ES Picked 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 Roadmap to Learn JavaScript For Beginners Difference Between PUT and PATCH Request 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": "\n23 Oct, 2019" }, { "code": null, "e": 407, "s": 28, "text": "The ES6 Events are the part of every HTML element that contains a set of events that can trigger the JavaScript code. An Event is an action or occurrence recognized by the software. It can be triggered by the user or the system. Mostly Events are used on buttons, hyperlinks, hovers, page loading, etc. All this stuff gets into action(processed) with the help of Event Handlers." }, { "code": null, "e": 570, "s": 407, "text": "Event handler: Simply, when a mentioned Event occurs it gets Handled. When the event is raised, it gets handled in the form of a set of instructions (function())." }, { "code": null, "e": 632, "s": 570, "text": "The following are some of the most commonly used HTML events:" }, { "code": null, "e": 811, "s": 632, "text": "onclick: This event gets activated on a click on a button with the help of left-clicking on the mouse. With a click, the “onclick” calls the respective function() assigned to it." }, { "code": null, "e": 1350, "s": 811, "text": "Example:<!DOCTYPE html><html> <head> <title> ES6 Events using onclick </title> <script> function geeks() { document.write (\"A Computer\" + \" Science Portal for Geeks\") } </script> </head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <h3> With a click, the “onclick” calls geeks() </h3> <input type = \"button\" onclick = \"geeks()\" value = \"Click here\" /> </body> </html>" }, { "code": "<!DOCTYPE html><html> <head> <title> ES6 Events using onclick </title> <script> function geeks() { document.write (\"A Computer\" + \" Science Portal for Geeks\") } </script> </head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <h3> With a click, the “onclick” calls geeks() </h3> <input type = \"button\" onclick = \"geeks()\" value = \"Click here\" /> </body> </html>", "e": 1881, "s": 1350, "text": null }, { "code": null, "e": 1889, "s": 1881, "text": "Output:" }, { "code": null, "e": 2175, "s": 1889, "text": "onmouseover and onmouseout: These event types will help us create nice effects with images or even with text as well. The “onmouseover” event triggers when you bring your mouse cursor over any element and the “onmouseout” triggers when you move your mouse cursor out from that element." }, { "code": null, "e": 3235, "s": 2175, "text": "Example:<!DOCTYPE html><html> <head> <title> ES6 Events using onmouseover and onmouseout </title> <script type=\"text/javascript\"> function mouseOver() { document.getElementById(\"d1\").style.color = \"green\"; document.getElementById(\"d2\").innerHTML = \"mouseOver triggered\"; } function mouseOut() { document.getElementById(\"d1\").style.color = \"black\"; document.getElementById(\"d2\").innerHTML = \"mouseOut triggered\"; } </script></head> <body style=\"text-align:center;\"> <h1 id=\"d1\" onmouseover=\"mouseOver()\" onmouseout=\"mouseOut()\"> GeeksforGeeks </h1> <h3> when the cursor is on the element h1 the \"onmouseover\" gets triggers and when the cursor is out of h1 the \"onmouseout\" gets triggers. </h3> <p id=\"d2\"></p></body> </html>" }, { "code": "<!DOCTYPE html><html> <head> <title> ES6 Events using onmouseover and onmouseout </title> <script type=\"text/javascript\"> function mouseOver() { document.getElementById(\"d1\").style.color = \"green\"; document.getElementById(\"d2\").innerHTML = \"mouseOver triggered\"; } function mouseOut() { document.getElementById(\"d1\").style.color = \"black\"; document.getElementById(\"d2\").innerHTML = \"mouseOut triggered\"; } </script></head> <body style=\"text-align:center;\"> <h1 id=\"d1\" onmouseover=\"mouseOver()\" onmouseout=\"mouseOut()\"> GeeksforGeeks </h1> <h3> when the cursor is on the element h1 the \"onmouseover\" gets triggers and when the cursor is out of h1 the \"onmouseout\" gets triggers. </h3> <p id=\"d2\"></p></body> </html>", "e": 4287, "s": 3235, "text": null }, { "code": null, "e": 4295, "s": 4287, "text": "Output:" }, { "code": null, "e": 4647, "s": 4295, "text": "onmousedown, onmouseup, onmousewheel : These event types will help us create nice effects with images or even with text as well. The “onmousedown” event triggers when you click the element and till you hold on to it when you release it “onmouseup” events triggers, “onmousewheel” event triggers when the mouse wheel is being rotated for the slightest." }, { "code": null, "e": 6050, "s": 4647, "text": "Example:<!DOCTYPE hmtl><html> <head> <title> ES6 Events using onmousedown, onmouseup and onmousewheel </title> <script> function mouseDown() { document.getElementById(\"d1\").style.color = \"blue\"; document.getElementById(\"d2\").innerHTML = \"mouseDown triggered\"; } function mouseUp() { document.getElementById(\"d1\").style.color = \"green\"; document.getElementById(\"d2\").innerHTML = \"mouseUp triggered\"; } function mouseWheel() { document.getElementById(\"d1\").style.color = \"violet\"; document.getElementById(\"d2\").innerHTML = \"mouseWheel triggered\"; } </script></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <p> when the mouse pointer clicks on the element h1, the text color changes to 'blue' when released changes to 'green', if the mouse wheel rotates color changes to 'violet'. </p> <input id=\"d1\" type=\"button\" onmousedown=\"mouseDown()\" onmouseup=\"mouseUp()\" onmousewheel=\"mouseWheel()\" value=\"Hello Geeks\" /> <p id=\"d2\"></p></body> </html>" }, { "code": "<!DOCTYPE hmtl><html> <head> <title> ES6 Events using onmousedown, onmouseup and onmousewheel </title> <script> function mouseDown() { document.getElementById(\"d1\").style.color = \"blue\"; document.getElementById(\"d2\").innerHTML = \"mouseDown triggered\"; } function mouseUp() { document.getElementById(\"d1\").style.color = \"green\"; document.getElementById(\"d2\").innerHTML = \"mouseUp triggered\"; } function mouseWheel() { document.getElementById(\"d1\").style.color = \"violet\"; document.getElementById(\"d2\").innerHTML = \"mouseWheel triggered\"; } </script></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <p> when the mouse pointer clicks on the element h1, the text color changes to 'blue' when released changes to 'green', if the mouse wheel rotates color changes to 'violet'. </p> <input id=\"d1\" type=\"button\" onmousedown=\"mouseDown()\" onmouseup=\"mouseUp()\" onmousewheel=\"mouseWheel()\" value=\"Hello Geeks\" /> <p id=\"d2\"></p></body> </html>", "e": 7445, "s": 6050, "text": null }, { "code": null, "e": 7453, "s": 7445, "text": "Output:" }, { "code": null, "e": 7893, "s": 7453, "text": "onsubmit: It’s an event that occurs when you try to validate a form before submitting it to the next action(server). You can put your form validation against this event type. With a click, the “onsubmit” calls the respective “return function()” assigned to it and takes the response from the function() in the form of true or false and decides the action. Check out this page ES6 | Validation for basic and detailed examples on “onsubmit”." }, { "code": null, "e": 7959, "s": 7893, "text": "Check out the following table for few mostly used Event Handlers:" }, { "code": null, "e": 7973, "s": 7959, "text": "JavaScript-ES" }, { "code": null, "e": 7980, "s": 7973, "text": "Picked" }, { "code": null, "e": 7991, "s": 7980, "text": "JavaScript" }, { "code": null, "e": 8008, "s": 7991, "text": "Web Technologies" }, { "code": null, "e": 8106, "s": 8008, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8167, "s": 8106, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 8239, "s": 8167, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 8279, "s": 8239, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 8321, "s": 8279, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 8362, "s": 8321, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 8395, "s": 8362, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 8457, "s": 8395, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 8518, "s": 8457, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 8568, "s": 8518, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Console readLine() method in Java with Examples
12 Jun, 2020 The readLine() method of Console class in Java is of two types: 1. The readLine() method of Console class in Java is used to read a single line of text from the console. Syntax: public String readLine() Parameters: This method does not accept any parameter. Return value: This method returns the string containing the line that is read from the console. It returns null if the stream has ended. Exceptions: This method throws IOError if an I/O error occurs. Note: System.console() returns null in an online IDE. Below programs illustrate readLine() method in Console class in IO package: Program 1: // Java program to illustrate// Console readLine() method import java.io.*; public class GFG { public static void main(String[] args) { // Create the console object Console cnsl = System.console(); if (cnsl == null) { System.out.println( "No console available"); return; } // Read line String str = cnsl.readLine( "Enter string : "); // Print System.out.println( "You entered : " + str); }} Program 2: // Java program to illustrate// Console readLine() method import java.io.*; public class GFG { public static void main(String[] args) { // Create the console object Console cnsl = System.console(); if (cnsl == null) { System.out.println( "No console available"); return; } // Read line String str = cnsl.readLine( "Enter string : "); // Print System.out.println( "You entered : " + str); }} 2. The readLine(String, Object) method of Console class in Java is used to read a single line of text from the console by providing a formatted prompt. Syntax: public String readLine(String fmt, Object... args) Parameters: This method accepts two parameters: fmt – It represents the format of the string. args – It represents the arguments that are referenced by the format specifiers in the string format. Return value: This method returns the string that contains the line read from the console. It returns null if the stream is ended. Exceptions: IllegalFormatException – This method throws IllegalFormatException if string format contains an illegal syntax or a format specifier is not compatible with the given arguments or insufficient arguments given the format string or other conditions that are illegal. IOError – This method throws IOError if an I/O error occurs. Below programs illustrate readLine(String, Object) method in Console class in IO package: Program 1: // Java program to illustrate// Console readLine(String, Object) method import java.io.*; public class GFG { public static void main(String[] args) { // Create the console object Console cnsl = System.console(); if (cnsl == null) { System.out.println( "No console available"); return; } String fmt = "%1$4s %2$10s %3$10s%n"; // Read line String str = cnsl.readLine( fmt, "Enter", "string : "); // Print line System.out.println( "You entered : " + str); }} Program 2: // Java program to illustrate// Console readLine(String, Object) method import java.io.*; public class GFG { public static void main(String[] args) { // Create the console object Console cnsl = System.console(); if (cnsl == null) { System.out.println( "No console available"); return; } String fmt = "%1$4s %2$10s %3$10s%n"; // Read line String str = cnsl.readLine( fmt, "Enter", "string : "); // Print line System.out.println( "You entered : " + str); }} References:1. https://docs.oracle.com/javase/10/docs/api/java/io/Console.html#readLine()2. https://docs.oracle.com/javase/10/docs/api/java/io/Console.html#readLine(java.lang.String, java.lang.Object...) Java-Functions Java-IO package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n12 Jun, 2020" }, { "code": null, "e": 117, "s": 53, "text": "The readLine() method of Console class in Java is of two types:" }, { "code": null, "e": 223, "s": 117, "text": "1. The readLine() method of Console class in Java is used to read a single line of text from the console." }, { "code": null, "e": 231, "s": 223, "text": "Syntax:" }, { "code": null, "e": 257, "s": 231, "text": "public String readLine()\n" }, { "code": null, "e": 312, "s": 257, "text": "Parameters: This method does not accept any parameter." }, { "code": null, "e": 449, "s": 312, "text": "Return value: This method returns the string containing the line that is read from the console. It returns null if the stream has ended." }, { "code": null, "e": 512, "s": 449, "text": "Exceptions: This method throws IOError if an I/O error occurs." }, { "code": null, "e": 566, "s": 512, "text": "Note: System.console() returns null in an online IDE." }, { "code": null, "e": 642, "s": 566, "text": "Below programs illustrate readLine() method in Console class in IO package:" }, { "code": null, "e": 653, "s": 642, "text": "Program 1:" }, { "code": "// Java program to illustrate// Console readLine() method import java.io.*; public class GFG { public static void main(String[] args) { // Create the console object Console cnsl = System.console(); if (cnsl == null) { System.out.println( \"No console available\"); return; } // Read line String str = cnsl.readLine( \"Enter string : \"); // Print System.out.println( \"You entered : \" + str); }}", "e": 1187, "s": 653, "text": null }, { "code": null, "e": 1198, "s": 1187, "text": "Program 2:" }, { "code": "// Java program to illustrate// Console readLine() method import java.io.*; public class GFG { public static void main(String[] args) { // Create the console object Console cnsl = System.console(); if (cnsl == null) { System.out.println( \"No console available\"); return; } // Read line String str = cnsl.readLine( \"Enter string : \"); // Print System.out.println( \"You entered : \" + str); }}", "e": 1732, "s": 1198, "text": null }, { "code": null, "e": 1884, "s": 1732, "text": "2. The readLine(String, Object) method of Console class in Java is used to read a single line of text from the console by providing a formatted prompt." }, { "code": null, "e": 1892, "s": 1884, "text": "Syntax:" }, { "code": null, "e": 1966, "s": 1892, "text": "public String readLine(String fmt,\n Object... args)\n" }, { "code": null, "e": 2014, "s": 1966, "text": "Parameters: This method accepts two parameters:" }, { "code": null, "e": 2060, "s": 2014, "text": "fmt – It represents the format of the string." }, { "code": null, "e": 2162, "s": 2060, "text": "args – It represents the arguments that are referenced by the format specifiers in the string format." }, { "code": null, "e": 2293, "s": 2162, "text": "Return value: This method returns the string that contains the line read from the console. It returns null if the stream is ended." }, { "code": null, "e": 2305, "s": 2293, "text": "Exceptions:" }, { "code": null, "e": 2569, "s": 2305, "text": "IllegalFormatException – This method throws IllegalFormatException if string format contains an illegal syntax or a format specifier is not compatible with the given arguments or insufficient arguments given the format string or other conditions that are illegal." }, { "code": null, "e": 2630, "s": 2569, "text": "IOError – This method throws IOError if an I/O error occurs." }, { "code": null, "e": 2720, "s": 2630, "text": "Below programs illustrate readLine(String, Object) method in Console class in IO package:" }, { "code": null, "e": 2731, "s": 2720, "text": "Program 1:" }, { "code": "// Java program to illustrate// Console readLine(String, Object) method import java.io.*; public class GFG { public static void main(String[] args) { // Create the console object Console cnsl = System.console(); if (cnsl == null) { System.out.println( \"No console available\"); return; } String fmt = \"%1$4s %2$10s %3$10s%n\"; // Read line String str = cnsl.readLine( fmt, \"Enter\", \"string : \"); // Print line System.out.println( \"You entered : \" + str); }}", "e": 3354, "s": 2731, "text": null }, { "code": null, "e": 3365, "s": 3354, "text": "Program 2:" }, { "code": "// Java program to illustrate// Console readLine(String, Object) method import java.io.*; public class GFG { public static void main(String[] args) { // Create the console object Console cnsl = System.console(); if (cnsl == null) { System.out.println( \"No console available\"); return; } String fmt = \"%1$4s %2$10s %3$10s%n\"; // Read line String str = cnsl.readLine( fmt, \"Enter\", \"string : \"); // Print line System.out.println( \"You entered : \" + str); }}", "e": 3988, "s": 3365, "text": null }, { "code": null, "e": 4191, "s": 3988, "text": "References:1. https://docs.oracle.com/javase/10/docs/api/java/io/Console.html#readLine()2. https://docs.oracle.com/javase/10/docs/api/java/io/Console.html#readLine(java.lang.String, java.lang.Object...)" }, { "code": null, "e": 4206, "s": 4191, "text": "Java-Functions" }, { "code": null, "e": 4222, "s": 4206, "text": "Java-IO package" }, { "code": null, "e": 4227, "s": 4222, "text": "Java" }, { "code": null, "e": 4232, "s": 4227, "text": "Java" } ]
Creating a Pandas dataframe using list of tuples
06 Jan, 2019 We can create a DataFrame from a list of simple tuples, and can even choose the specific elements of the tuples we want to use. Code #1: Simply passing tuple to DataFrame constructor. # import pandas to use pandas DataFrameimport pandas as pd # data in the form of list of tuplesdata = [('Peter', 18, 7), ('Riff', 15, 6), ('John', 17, 8), ('Michel', 18, 7), ('Sheli', 17, 5) ] # create DataFrame using datadf = pd.DataFrame(data, columns =['Name', 'Age', 'Score']) print(df) Output: Code #2: Using from_records() import pandas as pd # data in the form of list of tuplesdata = [('Peter', 18, 7), ('Riff', 15, 6), ('John', 17, 8), ('Michel', 18, 7), ('Sheli', 17, 5) ] # create DataFrame using datadf = pd.DataFrame.from_records(data, columns =['Team', 'Age', 'Score']) print(df) Output: Code #3: Using from_items() import pandas as pd # data in the form of list of tuplesdata = [('Age', [18, 15, 17, 18, 17]),('Team', ['A', 'B', 'A', 'C', 'B']),('Score', [7, 6, 8, 7, 5]),] # create DataFrame using datadf = pd.DataFrame.from_items(data) print(df) Output: Code #4: For pivoting it possible. # import pandas to use pandas DataFrameimport pandas as pd # data in the form of list of tuplesdata = [('Peter', 18, 7), ('Riff', 15, 6), ('John', 17, 8), ('Michel', 18, 7), ('Sheli', 17, 5) ] # create DataFrame using datadf = pd.DataFrame(data, columns =['Team', 'Age', 'Score']) a = df.pivot('Team', 'Score','Age')print(a) Output: pandas-dataframe-program Picked Python pandas-dataFrame Technical Scripter 2018 Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n06 Jan, 2019" }, { "code": null, "e": 156, "s": 28, "text": "We can create a DataFrame from a list of simple tuples, and can even choose the specific elements of the tuples we want to use." }, { "code": null, "e": 212, "s": 156, "text": "Code #1: Simply passing tuple to DataFrame constructor." }, { "code": "# import pandas to use pandas DataFrameimport pandas as pd # data in the form of list of tuplesdata = [('Peter', 18, 7), ('Riff', 15, 6), ('John', 17, 8), ('Michel', 18, 7), ('Sheli', 17, 5) ] # create DataFrame using datadf = pd.DataFrame(data, columns =['Name', 'Age', 'Score']) print(df) ", "e": 537, "s": 212, "text": null }, { "code": null, "e": 575, "s": 537, "text": "Output: Code #2: Using from_records()" }, { "code": "import pandas as pd # data in the form of list of tuplesdata = [('Peter', 18, 7), ('Riff', 15, 6), ('John', 17, 8), ('Michel', 18, 7), ('Sheli', 17, 5) ] # create DataFrame using datadf = pd.DataFrame.from_records(data, columns =['Team', 'Age', 'Score']) print(df) ", "e": 874, "s": 575, "text": null }, { "code": null, "e": 883, "s": 874, "text": "Output: " }, { "code": null, "e": 911, "s": 883, "text": "Code #3: Using from_items()" }, { "code": "import pandas as pd # data in the form of list of tuplesdata = [('Age', [18, 15, 17, 18, 17]),('Team', ['A', 'B', 'A', 'C', 'B']),('Score', [7, 6, 8, 7, 5]),] # create DataFrame using datadf = pd.DataFrame.from_items(data) print(df) ", "e": 1148, "s": 911, "text": null }, { "code": null, "e": 1191, "s": 1148, "text": "Output: Code #4: For pivoting it possible." }, { "code": "# import pandas to use pandas DataFrameimport pandas as pd # data in the form of list of tuplesdata = [('Peter', 18, 7), ('Riff', 15, 6), ('John', 17, 8), ('Michel', 18, 7), ('Sheli', 17, 5) ] # create DataFrame using datadf = pd.DataFrame(data, columns =['Team', 'Age', 'Score']) a = df.pivot('Team', 'Score','Age')print(a)", "e": 1537, "s": 1191, "text": null }, { "code": null, "e": 1545, "s": 1537, "text": "Output:" }, { "code": null, "e": 1570, "s": 1545, "text": "pandas-dataframe-program" }, { "code": null, "e": 1577, "s": 1570, "text": "Picked" }, { "code": null, "e": 1601, "s": 1577, "text": "Python pandas-dataFrame" }, { "code": null, "e": 1625, "s": 1601, "text": "Technical Scripter 2018" }, { "code": null, "e": 1632, "s": 1625, "text": "Python" }, { "code": null, "e": 1651, "s": 1632, "text": "Technical Scripter" } ]
cd command in Linux with Examples
18 Aug, 2021 cd command in linux known as change directory command. It is used to change current working directory. Syntax: $ cd [directory] To move inside a subdirectory : to move inside a subdirectory in linux we use $ cd [directory_name] In the above example, we have checked number of directories in our home directory and moved inside the Documents directory by using cd Documents command. Different functionalities of cd command : cd /: this command is used to change directory to the root directory, The root directory is the first directory in your filesystem hierarchy. $ cd / Above, / represents the root directory. cd dir_1/dir_2/dir_3: This command is used to move inside a directory from a directory $ cd dir_1/dir_2/dir_3 In above example, we have the document directory and inside the document directory we have a directory named geeksforgeeks and inside that directory we have example directory. To navigate example directory we have used command cd Documents/geeksforgeeks/example. cd ~ : this command is used to change directory to the home directory. $ cd ~ or $ cd cd : this command also work same as cd ~ command. cd .. : this command is used to move to the parent directory of current directory, or the directory one level up from the current directory. “..” represents parent directory. $ cd .. cd “dir name”: This command is used to navigate to a directory with white spaces.Instead of using double quotes we can use single quotes then also this command will work. $ cd "dir name" In above example, we have navigated the My songs directory by using cd “My songs” command. or $ cd dir\ name : this command work same as cd “dir name” command. simmytarika5 linux-command Linux-directory-commands Picked Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n18 Aug, 2021" }, { "code": null, "e": 157, "s": 53, "text": "cd command in linux known as change directory command. It is used to change current working directory. " }, { "code": null, "e": 167, "s": 157, "text": "Syntax: " }, { "code": null, "e": 184, "s": 167, "text": "$ cd [directory]" }, { "code": null, "e": 263, "s": 184, "text": "To move inside a subdirectory : to move inside a subdirectory in linux we use " }, { "code": null, "e": 286, "s": 263, "text": "$ cd [directory_name] " }, { "code": null, "e": 441, "s": 286, "text": "In the above example, we have checked number of directories in our home directory and moved inside the Documents directory by using cd Documents command. " }, { "code": null, "e": 484, "s": 441, "text": "Different functionalities of cd command : " }, { "code": null, "e": 628, "s": 484, "text": "cd /: this command is used to change directory to the root directory, The root directory is the first directory in your filesystem hierarchy. " }, { "code": null, "e": 635, "s": 628, "text": "$ cd /" }, { "code": null, "e": 675, "s": 635, "text": "Above, / represents the root directory." }, { "code": null, "e": 764, "s": 675, "text": "cd dir_1/dir_2/dir_3: This command is used to move inside a directory from a directory " }, { "code": null, "e": 787, "s": 764, "text": "$ cd dir_1/dir_2/dir_3" }, { "code": null, "e": 1050, "s": 787, "text": "In above example, we have the document directory and inside the document directory we have a directory named geeksforgeeks and inside that directory we have example directory. To navigate example directory we have used command cd Documents/geeksforgeeks/example." }, { "code": null, "e": 1123, "s": 1050, "text": "cd ~ : this command is used to change directory to the home directory. " }, { "code": null, "e": 1130, "s": 1123, "text": "$ cd ~" }, { "code": null, "e": 1148, "s": 1130, "text": " or " }, { "code": null, "e": 1154, "s": 1148, "text": "$ cd " }, { "code": null, "e": 1205, "s": 1154, "text": "cd : this command also work same as cd ~ command. " }, { "code": null, "e": 1382, "s": 1205, "text": "cd .. : this command is used to move to the parent directory of current directory, or the directory one level up from the current directory. “..” represents parent directory. " }, { "code": null, "e": 1391, "s": 1382, "text": "$ cd .. " }, { "code": null, "e": 1563, "s": 1391, "text": "cd “dir name”: This command is used to navigate to a directory with white spaces.Instead of using double quotes we can use single quotes then also this command will work. " }, { "code": null, "e": 1579, "s": 1563, "text": "$ cd \"dir name\"" }, { "code": null, "e": 1674, "s": 1579, "text": "In above example, we have navigated the My songs directory by using cd “My songs” command. or " }, { "code": null, "e": 1691, "s": 1674, "text": "$ cd dir\\ name :" }, { "code": null, "e": 1741, "s": 1691, "text": "this command work same as cd “dir name” command. " }, { "code": null, "e": 1754, "s": 1741, "text": "simmytarika5" }, { "code": null, "e": 1768, "s": 1754, "text": "linux-command" }, { "code": null, "e": 1793, "s": 1768, "text": "Linux-directory-commands" }, { "code": null, "e": 1800, "s": 1793, "text": "Picked" }, { "code": null, "e": 1811, "s": 1800, "text": "Linux-Unix" } ]
How To Visualize Sparse Matrix in Python using Matplotlib?
27 Apr, 2020 Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack. Spy is a function used to visualize the array as an image similar to matplotlib imshow function, but it is used in case of sparse matrix instead of dense matrix. A sparse matrix is a matrix where most of the elements are zero. Sparse matrix and its representation Spy function uses two plotting styles to visualize the array, these are: Image style Marker style Both the styles can be used for full arrays but in case of spmatrix instances only the marker style works. If marker or markersize is None then imshow function is used, and all the remaining keyword arguments are passed to this function; else, a Line2D object will be returned with the value of marker determining the marker type, and any remaining keyword arguments passed to plot function. Syntax: matplotlib.pyplot.spy(Z, precision=0, marker=None, markersize=None, aspect=’equal’, origin=’upper’, \*\*kwargs) Return value: The return type depends on the plotting style, i.e. AxesImage or Line2D. Parameters: ‘equal’: Ensures an aspect ratio of 1. Pixels will be square. ‘auto’: The axes is kept fixed and the aspect is adjusted so that the data fit in the axes. In general, this will result in non-square pixels. None: Use rcParams[“image.aspect”] Other parameters: **kwargs These are the additional parameters that helps to get different plotting styles. Example 1: # Implementation of matplotlib spy functionimport matplotlib.pyplot as pltimport numpy as np x = np.random.randn(50, 50) x[15, :] = 0.x[:, 40] = 0. plt.spy(x) Output: Example 2: # Implementation of matplotlib spy functionimport matplotlib.pyplot as pltimport numpy as np x = np.random.randn(50, 50)x[15, :] = 0.x[:, 40] = 0. plt.spy(x, precision = 0.1, markersize = 5) Output: Matplotlib Pyplot-class Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Rotate axis tick labels in Seaborn and Matplotlib Enumerate() in Python Deque in Python Stack in Python Python Dictionary sum() function in Python Print lists in Python (5 Different Ways) Different ways to create Pandas Dataframe Queue in Python Defaultdict in Python
[ { "code": null, "e": 52, "s": 24, "text": "\n27 Apr, 2020" }, { "code": null, "e": 264, "s": 52, "text": "Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack." }, { "code": null, "e": 491, "s": 264, "text": "Spy is a function used to visualize the array as an image similar to matplotlib imshow function, but it is used in case of sparse matrix instead of dense matrix. A sparse matrix is a matrix where most of the elements are zero." }, { "code": null, "e": 528, "s": 491, "text": "Sparse matrix and its representation" }, { "code": null, "e": 601, "s": 528, "text": "Spy function uses two plotting styles to visualize the array, these are:" }, { "code": null, "e": 613, "s": 601, "text": "Image style" }, { "code": null, "e": 626, "s": 613, "text": "Marker style" }, { "code": null, "e": 1018, "s": 626, "text": "Both the styles can be used for full arrays but in case of spmatrix instances only the marker style works. If marker or markersize is None then imshow function is used, and all the remaining keyword arguments are passed to this function; else, a Line2D object will be returned with the value of marker determining the marker type, and any remaining keyword arguments passed to plot function." }, { "code": null, "e": 1138, "s": 1018, "text": "Syntax: matplotlib.pyplot.spy(Z, precision=0, marker=None, markersize=None, aspect=’equal’, origin=’upper’, \\*\\*kwargs)" }, { "code": null, "e": 1152, "s": 1138, "text": "Return value:" }, { "code": null, "e": 1225, "s": 1152, "text": "The return type depends on the plotting style, i.e. AxesImage or Line2D." }, { "code": null, "e": 1237, "s": 1225, "text": "Parameters:" }, { "code": null, "e": 1299, "s": 1237, "text": "‘equal’: Ensures an aspect ratio of 1. Pixels will be square." }, { "code": null, "e": 1442, "s": 1299, "text": "‘auto’: The axes is kept fixed and the aspect is adjusted so that the data fit in the axes. In general, this will result in non-square pixels." }, { "code": null, "e": 1477, "s": 1442, "text": "None: Use rcParams[“image.aspect”]" }, { "code": null, "e": 1504, "s": 1477, "text": "Other parameters: **kwargs" }, { "code": null, "e": 1585, "s": 1504, "text": "These are the additional parameters that helps to get different plotting styles." }, { "code": null, "e": 1596, "s": 1585, "text": "Example 1:" }, { "code": "# Implementation of matplotlib spy functionimport matplotlib.pyplot as pltimport numpy as np x = np.random.randn(50, 50) x[15, :] = 0.x[:, 40] = 0. plt.spy(x)", "e": 1760, "s": 1596, "text": null }, { "code": null, "e": 1768, "s": 1760, "text": "Output:" }, { "code": null, "e": 1779, "s": 1768, "text": "Example 2:" }, { "code": "# Implementation of matplotlib spy functionimport matplotlib.pyplot as pltimport numpy as np x = np.random.randn(50, 50)x[15, :] = 0.x[:, 40] = 0. plt.spy(x, precision = 0.1, markersize = 5)", "e": 1972, "s": 1779, "text": null }, { "code": null, "e": 1980, "s": 1972, "text": "Output:" }, { "code": null, "e": 2004, "s": 1980, "text": "Matplotlib Pyplot-class" }, { "code": null, "e": 2022, "s": 2004, "text": "Python-matplotlib" }, { "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": 2177, "s": 2127, "text": "Rotate axis tick labels in Seaborn and Matplotlib" }, { "code": null, "e": 2199, "s": 2177, "text": "Enumerate() in Python" }, { "code": null, "e": 2215, "s": 2199, "text": "Deque in Python" }, { "code": null, "e": 2231, "s": 2215, "text": "Stack in Python" }, { "code": null, "e": 2249, "s": 2231, "text": "Python Dictionary" }, { "code": null, "e": 2274, "s": 2249, "text": "sum() function in Python" }, { "code": null, "e": 2315, "s": 2274, "text": "Print lists in Python (5 Different Ways)" }, { "code": null, "e": 2357, "s": 2315, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2373, "s": 2357, "text": "Queue in Python" } ]
Difference between Keyword and Identifier
23 May, 2022 Keywords: Keywords are specific reserved words in C each of which has a specific feature associated with it. Almost all of the words which help us use the functionality of the C language are included in the list of keywords. So you can imagine that the list of keywords is not going to be a small one! There are a total of 32 keywords in C: auto break case char const continue default do double else enum extern float for goto if int long register return short signed sizeof static struct switch typedef union unsigned void volatile while Identifiers: Identifiers are used as the general terminology for naming of variables, functions and arrays. These are user defined names consisting of arbitrarily long sequence of letters and digits with either a letter or the underscore(_) as a first character. Identifier names must differ in spelling and case from any keywords. You cannot use keywords as identifiers; they are reserved for special use. Once declared, you can use the identifier in later program statements to refer to the associated value. A special kind of identifier, called a statement label, can be used in goto statements. Difference between Keyword and Identifier: mitalibhola94 C Basics school-programming Difference Between 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 Difference Between Method Overloading and Method Overriding in Java Similarities and Difference between Java and C++ Difference between Internal and External fragmentation Difference between Compile-time and Run-time Polymorphism in Java Differences and Applications of List, Tuple, Set and Dictionary in Python Difference between DELETE and TRUNCATE Difference between FDMA, TDMA and CDMA Difference between MANET and VANET Differences Between .NET Core and .NET Framework
[ { "code": null, "e": 53, "s": 25, "text": "\n23 May, 2022" }, { "code": null, "e": 394, "s": 53, "text": "Keywords: Keywords are specific reserved words in C each of which has a specific feature associated with it. Almost all of the words which help us use the functionality of the C language are included in the list of keywords. So you can imagine that the list of keywords is not going to be a small one! There are a total of 32 keywords in C:" }, { "code": null, "e": 703, "s": 394, "text": " auto break case char const continue\n default do double else enum extern\n float for goto if int long\n register return short signed sizeof static\n struct switch typedef union unsigned void\n volatile while " }, { "code": null, "e": 1345, "s": 703, "text": "Identifiers: Identifiers are used as the general terminology for naming of variables, functions and arrays. These are user defined names consisting of arbitrarily long sequence of letters and digits with either a letter or the underscore(_) as a first character. Identifier names must differ in spelling and case from any keywords. You cannot use keywords as identifiers; they are reserved for special use. Once declared, you can use the identifier in later program statements to refer to the associated value. A special kind of identifier, called a statement label, can be used in goto statements. Difference between Keyword and Identifier:" }, { "code": null, "e": 1359, "s": 1345, "text": "mitalibhola94" }, { "code": null, "e": 1368, "s": 1359, "text": "C Basics" }, { "code": null, "e": 1387, "s": 1368, "text": "school-programming" }, { "code": null, "e": 1406, "s": 1387, "text": "Difference Between" }, { "code": null, "e": 1504, "s": 1406, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1565, "s": 1504, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 1633, "s": 1565, "text": "Difference Between Method Overloading and Method Overriding in Java" }, { "code": null, "e": 1682, "s": 1633, "text": "Similarities and Difference between Java and C++" }, { "code": null, "e": 1737, "s": 1682, "text": "Difference between Internal and External fragmentation" }, { "code": null, "e": 1803, "s": 1737, "text": "Difference between Compile-time and Run-time Polymorphism in Java" }, { "code": null, "e": 1877, "s": 1803, "text": "Differences and Applications of List, Tuple, Set and Dictionary in Python" }, { "code": null, "e": 1916, "s": 1877, "text": "Difference between DELETE and TRUNCATE" }, { "code": null, "e": 1955, "s": 1916, "text": "Difference between FDMA, TDMA and CDMA" }, { "code": null, "e": 1990, "s": 1955, "text": "Difference between MANET and VANET" } ]
How to create Python dictionary by enumerate function?
Python enumerate() function takes any iterable as argument and returns enumerate object using which the iterable can be traversed. It contains index and corresponding item in the iterable object like list, tuple or string. Such enumerate object with index and value is then converted to a dictionary using dictionary comprehension. >>> l1=['aa','bb','cc','dd'] >>> enum=enumerate(l1) >>> enum >>> d=dict((i,j) for i,j in enum) >>> d {0: 'aa', 1: 'bb', 2: 'cc', 3: 'dd'}
[ { "code": null, "e": 1410, "s": 1187, "text": "Python enumerate() function takes any iterable as argument and returns enumerate object using which the iterable can be traversed. It contains index and corresponding item in the iterable object like list, tuple or string." }, { "code": null, "e": 1519, "s": 1410, "text": "Such enumerate object with index and value is then converted to a dictionary using dictionary comprehension." }, { "code": null, "e": 1658, "s": 1519, "text": ">>> l1=['aa','bb','cc','dd']\n>>> enum=enumerate(l1)\n>>> enum\n\n>>> d=dict((i,j) for i,j in enum)\n>>> d\n{0: 'aa', 1: 'bb', 2: 'cc', 3: 'dd'}" } ]
JavaScript Boolean
24 Nov, 2021 Below is the example of JavaScript Boolean method. Example: javascript <script> function gfg() {document.write(Boolean(12)); } gfg();</script> Output: true Boolean is a datatype that returns either of two values i.e. true or false. In JavaScript, Boolean is used as a function to get the value of a variable, object, conditions, expressions, etc. in terms of true or false.Example: Here a1 and a2 stores the boolean value i.e. true and false respectively. var a1 = true; var a2 = false; Note: Below variables are initialized with strings not boolean values. var a1 ="true"; var a2 ="false"; Boolean() function in JavaScript: Boolean function returns the boolean value of variable. It can also be used to find boolean result of a condition, expression etc.Syntax: Boolean(variable/expression) Note: A variable or object which has value are treated as true boolean values. ‘0’, ‘NaN’, empty string, ‘undefined’, ‘null’ are treated as false boolean values.JavaScripts to show the working of boolean values Code #1: Below program will give true values as output. javascript <!DOCTYPE html><html> <body> <script> document.write('Boolean(10) is ' + Boolean(10)); document.write('<br>'); document.write('Boolean("GeeksforGeeks") is ' + Boolean("GeeksforGeeks")); document.write('<br>'); document.write('Boolean(2.74) is ' + Boolean(2.74)); document.write('<br>'); document.write('Boolean(-1) is ' + Boolean(-1)); document.write('<br>'); document.write("Boolean('true') is " + Boolean('true')); document.write('<br>'); document.write("Boolean('false') is " + Boolean('false')); document.write('<br>'); document.write('Boolean(3 * 2 + 1.11) is ' + Boolean(3 * 2 + 1.11)); document.write('<br>'); document.write('Boolean(1<2) is ' + Boolean(1 < 2)); </script> </body></html> Output: Boolean(10) is true Boolean("GeeksforGeeks") is true Boolean(2.74) is true Boolean(-1) is true Boolean('true') is true Boolean('false') is true Boolean(3 * 2 + 1.11) is true Boolean(1<2) is true Code #2: Below program will give false values as output. javascript <!DOCTYPE html><html> <body> <script> var e; //undefined document.write('Boolean(0) is ' + Boolean(0)); document.write('<br>'); document.write('Boolean("") is ' + Boolean("")); document.write('<br>'); document.write('Boolean(e) undefined is ' + Boolean(e)); document.write('<br>'); document.write('Boolean(-0) is ' + Boolean(-0)); document.write('<br>'); document.write('Boolean(false) is ' + Boolean(false)); document.write('<br>'); document.write('Boolean(NaN) is ' + Boolean(NaN)); document.write('<br>'); document.write('Boolean(null) is ' + Boolean(null)); document.write('<br>'); document.write('Boolean(1>2) is ' + Boolean(1 > 2)); </script></body> </html> Output: Boolean(0) is false Boolean("") is false Boolean(e) undefined is false Boolean(-0) is false Boolean(false) is false Boolean(NaN) is false Boolean(null) is false Boolean(1>2) is false JavaScript Boolean object: The boolean object in javascript is an object wrapper for boolean values. Booleans in JavaScript can also be defined using the new keyword. Syntax: new Boolean(value) Code #3: javascript <!DOCTYPE html><html> <body> <script> var v1 = false; var v2 = new Boolean(false); var v3 = new Boolean(""); var v4 = new Boolean(0); var v5 = new Boolean(true); var v6 = new Boolean("GeeksforGeeks"); document.write('v1 = ' + v1); document.write("<br>"); document.write('v2 = ' + v2); document.write("<br>"); document.write('v3 = ' + v3); document.write("<br>"); document.write('v4 = ' + v4); document.write("<br>"); document.write('v5 = ' + v5); document.write("<br>"); document.write('v6 = ' + v6); </script></body></html> Output: v1 = false v2 = false v3 = false v4 = false v5 = true v6 = true Code #4: javascript <!DOCTYPE html><html> <body> <script> var v1 = true; var v2 = new Boolean(true); document.write('v1 = = v2 is ' + (v1 == v2)); document.write("<br>"); document.write('v1 = = = v2 is ' + (v1 === v2)); </script></body></html> Output: v1 = = v2 is true v1 = = = v2 is false Note: v1 = = = v2 is not true as the type of v1 and v2(object) is not same.Supported Browsers: Google Chrome 6 and above Edge 12 and above Firefox 4 and above Internet Explorer 9 and above Opera 12 and above Safari 5.1 and above ysachin2314 JavaScript-Boolean Picked JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Nov, 2021" }, { "code": null, "e": 81, "s": 28, "text": "Below is the example of JavaScript Boolean method. " }, { "code": null, "e": 92, "s": 81, "text": "Example: " }, { "code": null, "e": 103, "s": 92, "text": "javascript" }, { "code": "<script> function gfg() {document.write(Boolean(12)); } gfg();</script>", "e": 184, "s": 103, "text": null }, { "code": null, "e": 194, "s": 184, "text": "Output: " }, { "code": null, "e": 199, "s": 194, "text": "true" }, { "code": null, "e": 501, "s": 199, "text": "Boolean is a datatype that returns either of two values i.e. true or false. In JavaScript, Boolean is used as a function to get the value of a variable, object, conditions, expressions, etc. in terms of true or false.Example: Here a1 and a2 stores the boolean value i.e. true and false respectively. " }, { "code": null, "e": 532, "s": 501, "text": "var a1 = true;\nvar a2 = false;" }, { "code": null, "e": 605, "s": 532, "text": "Note: Below variables are initialized with strings not boolean values. " }, { "code": null, "e": 638, "s": 605, "text": "var a1 =\"true\";\nvar a2 =\"false\";" }, { "code": null, "e": 812, "s": 638, "text": "Boolean() function in JavaScript: Boolean function returns the boolean value of variable. It can also be used to find boolean result of a condition, expression etc.Syntax: " }, { "code": null, "e": 842, "s": 812, "text": "Boolean(variable/expression) " }, { "code": null, "e": 1111, "s": 842, "text": "Note: A variable or object which has value are treated as true boolean values. ‘0’, ‘NaN’, empty string, ‘undefined’, ‘null’ are treated as false boolean values.JavaScripts to show the working of boolean values Code #1: Below program will give true values as output. " }, { "code": null, "e": 1122, "s": 1111, "text": "javascript" }, { "code": "<!DOCTYPE html><html> <body> <script> document.write('Boolean(10) is ' + Boolean(10)); document.write('<br>'); document.write('Boolean(\"GeeksforGeeks\") is ' + Boolean(\"GeeksforGeeks\")); document.write('<br>'); document.write('Boolean(2.74) is ' + Boolean(2.74)); document.write('<br>'); document.write('Boolean(-1) is ' + Boolean(-1)); document.write('<br>'); document.write(\"Boolean('true') is \" + Boolean('true')); document.write('<br>'); document.write(\"Boolean('false') is \" + Boolean('false')); document.write('<br>'); document.write('Boolean(3 * 2 + 1.11) is ' + Boolean(3 * 2 + 1.11)); document.write('<br>'); document.write('Boolean(1<2) is ' + Boolean(1 < 2)); </script> </body></html> ", "e": 1970, "s": 1122, "text": null }, { "code": null, "e": 1980, "s": 1970, "text": "Output: " }, { "code": null, "e": 2175, "s": 1980, "text": "Boolean(10) is true\nBoolean(\"GeeksforGeeks\") is true\nBoolean(2.74) is true\nBoolean(-1) is true\nBoolean('true') is true\nBoolean('false') is true\nBoolean(3 * 2 + 1.11) is true\nBoolean(1<2) is true" }, { "code": null, "e": 2234, "s": 2175, "text": "Code #2: Below program will give false values as output. " }, { "code": null, "e": 2245, "s": 2234, "text": "javascript" }, { "code": "<!DOCTYPE html><html> <body> <script> var e; //undefined document.write('Boolean(0) is ' + Boolean(0)); document.write('<br>'); document.write('Boolean(\"\") is ' + Boolean(\"\")); document.write('<br>'); document.write('Boolean(e) undefined is ' + Boolean(e)); document.write('<br>'); document.write('Boolean(-0) is ' + Boolean(-0)); document.write('<br>'); document.write('Boolean(false) is ' + Boolean(false)); document.write('<br>'); document.write('Boolean(NaN) is ' + Boolean(NaN)); document.write('<br>'); document.write('Boolean(null) is ' + Boolean(null)); document.write('<br>'); document.write('Boolean(1>2) is ' + Boolean(1 > 2)); </script></body> </html> ", "e": 3057, "s": 2245, "text": null }, { "code": null, "e": 3067, "s": 3057, "text": "Output: " }, { "code": null, "e": 3250, "s": 3067, "text": "Boolean(0) is false\nBoolean(\"\") is false\nBoolean(e) undefined is false\nBoolean(-0) is false\nBoolean(false) is false\nBoolean(NaN) is false\nBoolean(null) is false\nBoolean(1>2) is false" }, { "code": null, "e": 3427, "s": 3250, "text": "JavaScript Boolean object: The boolean object in javascript is an object wrapper for boolean values. Booleans in JavaScript can also be defined using the new keyword. Syntax: " }, { "code": null, "e": 3446, "s": 3427, "text": "new Boolean(value)" }, { "code": null, "e": 3457, "s": 3446, "text": "Code #3: " }, { "code": null, "e": 3468, "s": 3457, "text": "javascript" }, { "code": "<!DOCTYPE html><html> <body> <script> var v1 = false; var v2 = new Boolean(false); var v3 = new Boolean(\"\"); var v4 = new Boolean(0); var v5 = new Boolean(true); var v6 = new Boolean(\"GeeksforGeeks\"); document.write('v1 = ' + v1); document.write(\"<br>\"); document.write('v2 = ' + v2); document.write(\"<br>\"); document.write('v3 = ' + v3); document.write(\"<br>\"); document.write('v4 = ' + v4); document.write(\"<br>\"); document.write('v5 = ' + v5); document.write(\"<br>\"); document.write('v6 = ' + v6); </script></body></html>", "e": 4118, "s": 3468, "text": null }, { "code": null, "e": 4128, "s": 4118, "text": "Output: " }, { "code": null, "e": 4192, "s": 4128, "text": "v1 = false\nv2 = false\nv3 = false\nv4 = false\nv5 = true\nv6 = true" }, { "code": null, "e": 4203, "s": 4192, "text": "Code #4: " }, { "code": null, "e": 4214, "s": 4203, "text": "javascript" }, { "code": "<!DOCTYPE html><html> <body> <script> var v1 = true; var v2 = new Boolean(true); document.write('v1 = = v2 is ' + (v1 == v2)); document.write(\"<br>\"); document.write('v1 = = = v2 is ' + (v1 === v2)); </script></body></html>", "e": 4480, "s": 4214, "text": null }, { "code": null, "e": 4490, "s": 4480, "text": "Output: " }, { "code": null, "e": 4529, "s": 4490, "text": "v1 = = v2 is true\nv1 = = = v2 is false" }, { "code": null, "e": 4626, "s": 4529, "text": "Note: v1 = = = v2 is not true as the type of v1 and v2(object) is not same.Supported Browsers: " }, { "code": null, "e": 4652, "s": 4626, "text": "Google Chrome 6 and above" }, { "code": null, "e": 4670, "s": 4652, "text": "Edge 12 and above" }, { "code": null, "e": 4690, "s": 4670, "text": "Firefox 4 and above" }, { "code": null, "e": 4720, "s": 4690, "text": "Internet Explorer 9 and above" }, { "code": null, "e": 4739, "s": 4720, "text": "Opera 12 and above" }, { "code": null, "e": 4760, "s": 4739, "text": "Safari 5.1 and above" }, { "code": null, "e": 4774, "s": 4762, "text": "ysachin2314" }, { "code": null, "e": 4793, "s": 4774, "text": "JavaScript-Boolean" }, { "code": null, "e": 4800, "s": 4793, "text": "Picked" }, { "code": null, "e": 4811, "s": 4800, "text": "JavaScript" }, { "code": null, "e": 4828, "s": 4811, "text": "Web Technologies" } ]
How to handle orientation change android?
This example demonstrate about How to handle orientation change android Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version = "1.0" encoding = "utf-8"?> <LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android" xmlns:app = "http://schemas.android.com/apk/res-auto" xmlns:tools = "http://schemas.android.com/tools" android:layout_width = "match_parent" android:gravity = "center" android:layout_height = "match_parent" tools:context = ".MainActivity" android:orientation = "vertical"> <TextView android:id = "@+id/actionEvent" android:textSize = "40sp" android:layout_marginTop = "30dp" android:layout_width = "wrap_content" android:layout_height = "match_parent" /> </LinearLayout> In the above code, we have taken text view to show orientation changes. Step 3 − Add the following code to src/MainActivity.java package com.example.myapplication; import android.content.res.Configuration; import android.os.Build; import android.os.Bundle; import android.support.annotation.RequiresApi; import android.support.v7.app.AppCompatActivity; import android.widget.TextView; public class MainActivity extends AppCompatActivity { TextView actionEvent; @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); actionEvent = findViewById(R.id.actionEvent); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) { actionEvent.setText("ORIENTATION LANDSCAPE"); } else { actionEvent.setText("ORIENTATION PORTRAIT"); } } } Step 4 − Add the following code to manifest.xml <?xml version = "1.0" encoding = "utf-8"?> <manifest xmlns:android = "http://schemas.android.com/apk/res/android" package = "com.example.myapplication"> <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" android:configChanges = "keyboardHidden|orientation|screenSize"> <intent-filter> <action android:name = "android.intent.action.MAIN" /> <action android:name = "android.net.conn.CONNECTIVITY_CHANGE" /> <category android:name = "android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen – Now rotate the screen as shown below – Click here to download the project code
[ { "code": null, "e": 1259, "s": 1187, "text": "This example demonstrate about How to handle orientation change android" }, { "code": null, "e": 1388, "s": 1259, "text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project." }, { "code": null, "e": 1453, "s": 1388, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2096, "s": 1453, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<LinearLayout xmlns:android = \"http://schemas.android.com/apk/res/android\"\n xmlns:app = \"http://schemas.android.com/apk/res-auto\"\n xmlns:tools = \"http://schemas.android.com/tools\"\n android:layout_width = \"match_parent\"\n android:gravity = \"center\"\n android:layout_height = \"match_parent\"\n tools:context = \".MainActivity\"\n android:orientation = \"vertical\">\n <TextView\n android:id = \"@+id/actionEvent\"\n android:textSize = \"40sp\"\n android:layout_marginTop = \"30dp\"\n android:layout_width = \"wrap_content\"\n android:layout_height = \"match_parent\" />\n</LinearLayout>" }, { "code": null, "e": 2168, "s": 2096, "text": "In the above code, we have taken text view to show orientation changes." }, { "code": null, "e": 2225, "s": 2168, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 3165, "s": 2225, "text": "package com.example.myapplication;\nimport android.content.res.Configuration;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.support.annotation.RequiresApi;\nimport android.support.v7.app.AppCompatActivity;\nimport android.widget.TextView;\n\npublic class MainActivity extends AppCompatActivity {\n TextView actionEvent;\n @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n actionEvent = findViewById(R.id.actionEvent);\n }\n @Override\n public void onConfigurationChanged(Configuration newConfig) {\n super.onConfigurationChanged(newConfig);\n if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {\n actionEvent.setText(\"ORIENTATION LANDSCAPE\");\n } else {\n actionEvent.setText(\"ORIENTATION PORTRAIT\");\n }\n }\n}" }, { "code": null, "e": 3213, "s": 3165, "text": "Step 4 − Add the following code to manifest.xml" }, { "code": null, "e": 4073, "s": 3213, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<manifest xmlns:android = \"http://schemas.android.com/apk/res/android\"\n package = \"com.example.myapplication\">\n <application\n android:allowBackup = \"true\"\n android:icon = \"@mipmap/ic_launcher\"\n android:label = \"@string/app_name\"\n android:roundIcon = \"@mipmap/ic_launcher_round\"\n android:supportsRtl = \"true\"\n android:theme = \"@style/AppTheme\">\n <activity android:name = \".MainActivity\"\n android:configChanges = \"keyboardHidden|orientation|screenSize\">\n <intent-filter>\n <action android:name = \"android.intent.action.MAIN\" />\n <action android:name = \"android.net.conn.CONNECTIVITY_CHANGE\" />\n <category android:name = \"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 4420, "s": 4073, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –" }, { "code": null, "e": 4459, "s": 4420, "text": "Now rotate the screen as shown below –" }, { "code": null, "e": 4499, "s": 4459, "text": "Click here to download the project code" } ]
PHP | Check if a number is prime
10 Jul, 2021 Given a number, we need to check whether it is prime or not in PHP. General approach for prime check is discussed here. In this article we will learn about how to check if a number is prime or not in PHP. Examples: Input : 21 Output : Not Prime Input : 31 Output : Prime Simple Method: A simple solution is to iterate through all numbers from 2 to n/2 and for every number check if it divides n. If we find any number that divides, we return 0 (false) otherwise we will return 1 (true). Below is the implementation of this approach in PHP: PHP <?php// PHP code to check whether a number is prime or Not// function to check the number is Prime or Notfunction primeCheck($number){ if ($number == 1) return 0; for ($i = 2; $i <= $number/2; $i++){ if ($number % $i == 0) return 0; } return 1;} // Driver Code$number = 31;$flag = primeCheck($number);if ($flag == 1) echo "Prime";else echo "Not Prime"?> Output: Prime Time Complexity: O(n) Efficient Method: We can optimize the above approach by observing that, instead of checking till n, we can check till sqrt(n) because a larger factor of n must be a multiple of smaller factor that has been already checked.So, we will traverse in the range [2,sqrt(number)] to check if the number is divisible by any number or not. If it is divisible the its not a prime number. Below is the implementation of this approach in PHP: PHP <?php// PHP code to check whether a number is prime or Not// function to check the number is Prime or Notfunction primeCheck($number){ if ($number == 1) return 0; for ($i = 2; $i <= sqrt($number); $i++){ if ($number % $i == 0) return 0; } return 1;} // Driver Code$number = 31;$flag = primeCheck($number);if ($flag == 1) echo "Prime";else echo "Not Prime"?> Output: Prime Time Complexity: O(sqrt(n)) simranarora5sos anikakapoor PHP-basics school-programming PHP Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Insert Form Data into Database using PHP ? How to convert array to string in PHP ? How to Upload Image into Database and Display it using PHP ? How to check whether an array is empty using PHP? PHP | Converting string to Date and DateTime 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": "\n10 Jul, 2021" }, { "code": null, "e": 233, "s": 28, "text": "Given a number, we need to check whether it is prime or not in PHP. General approach for prime check is discussed here. In this article we will learn about how to check if a number is prime or not in PHP." }, { "code": null, "e": 244, "s": 233, "text": "Examples: " }, { "code": null, "e": 303, "s": 244, "text": "Input : 21\nOutput : Not Prime\n\nInput : 31\nOutput : Prime\n " }, { "code": null, "e": 520, "s": 303, "text": "Simple Method: A simple solution is to iterate through all numbers from 2 to n/2 and for every number check if it divides n. If we find any number that divides, we return 0 (false) otherwise we will return 1 (true). " }, { "code": null, "e": 575, "s": 520, "text": "Below is the implementation of this approach in PHP: " }, { "code": null, "e": 579, "s": 575, "text": "PHP" }, { "code": "<?php// PHP code to check whether a number is prime or Not// function to check the number is Prime or Notfunction primeCheck($number){ if ($number == 1) return 0; for ($i = 2; $i <= $number/2; $i++){ if ($number % $i == 0) return 0; } return 1;} // Driver Code$number = 31;$flag = primeCheck($number);if ($flag == 1) echo \"Prime\";else echo \"Not Prime\"?>", "e": 972, "s": 579, "text": null }, { "code": null, "e": 981, "s": 972, "text": "Output: " }, { "code": null, "e": 987, "s": 981, "text": "Prime" }, { "code": null, "e": 1009, "s": 987, "text": "Time Complexity: O(n)" }, { "code": null, "e": 1387, "s": 1009, "text": "Efficient Method: We can optimize the above approach by observing that, instead of checking till n, we can check till sqrt(n) because a larger factor of n must be a multiple of smaller factor that has been already checked.So, we will traverse in the range [2,sqrt(number)] to check if the number is divisible by any number or not. If it is divisible the its not a prime number." }, { "code": null, "e": 1442, "s": 1387, "text": "Below is the implementation of this approach in PHP: " }, { "code": null, "e": 1446, "s": 1442, "text": "PHP" }, { "code": "<?php// PHP code to check whether a number is prime or Not// function to check the number is Prime or Notfunction primeCheck($number){ if ($number == 1) return 0; for ($i = 2; $i <= sqrt($number); $i++){ if ($number % $i == 0) return 0; } return 1;} // Driver Code$number = 31;$flag = primeCheck($number);if ($flag == 1) echo \"Prime\";else echo \"Not Prime\"?>", "e": 1848, "s": 1446, "text": null }, { "code": null, "e": 1857, "s": 1848, "text": "Output: " }, { "code": null, "e": 1863, "s": 1857, "text": "Prime" }, { "code": null, "e": 1892, "s": 1863, "text": "Time Complexity: O(sqrt(n)) " }, { "code": null, "e": 1908, "s": 1892, "text": "simranarora5sos" }, { "code": null, "e": 1920, "s": 1908, "text": "anikakapoor" }, { "code": null, "e": 1931, "s": 1920, "text": "PHP-basics" }, { "code": null, "e": 1950, "s": 1931, "text": "school-programming" }, { "code": null, "e": 1954, "s": 1950, "text": "PHP" }, { "code": null, "e": 1971, "s": 1954, "text": "Web Technologies" }, { "code": null, "e": 1975, "s": 1971, "text": "PHP" }, { "code": null, "e": 2073, "s": 1975, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2123, "s": 2073, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 2163, "s": 2123, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 2224, "s": 2163, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 2274, "s": 2224, "text": "How to check whether an array is empty using PHP?" }, { "code": null, "e": 2319, "s": 2274, "text": "PHP | Converting string to Date and DateTime" }, { "code": null, "e": 2352, "s": 2319, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2414, "s": 2352, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2475, "s": 2414, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2525, "s": 2475, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Sum of the series (1*2) + (2*3) + (3*4) + ...... upto n terms
22 Jun, 2022 Given a value n, the task is to find sum of the series (1*2) + (2*3) + (3*4) + ......+ n termsExamples: Input: n = 2 Output: 8 Explanation: (1*2) + (2*3) = 2 + 6 = 8 Input: n = 3 Output: 20 Explanation: (1*2) + (2*3) + (2*4) = 2 + 6 + 12 = 20 Simple Solution One by one add elements recursively.Below is the implementation C++ Java Python3 C# PHP Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return sumint sum(int n){ if (n == 1) { return 2; } else { return (n * (n + 1) + sum(n - 1)); }} // Driver codeint main(){ int n = 2; cout << sum(n);} // Java implementation of the approach class Solution { // Function to return a the required result static int sum(int n) { if (n == 1) { return 2; } else { return (n * (n + 1) + sum(n - 1)); } } // Driver code public static void main(String args[]) { int n = 2; System.out.println(sum(n)); }} # Python3 implementation of the approach # Function to return sumdef sum(n): if (n == 1): return 2; else: return (n * (n + 1) + sum(n - 1)); # Driver code n = 2;print(sum(n)); # This code is contributed by mits // Csharp implementation of the approach using System; class Solution { // Function to return a the required result static int sum(int n) { if (n == 1) { return 2; } else { return (n * (n + 1) + sum(n - 1)); } } // Driver code public static void Main() { int n = 2; Console.WrieLine(sum(n)); }} <?php// PHP implementation of the approach // Function to return sumfunction sum($n){ if ($n == 1) { return 2; } else { return ($n * ($n + 1) + sum($n - 1)); }} // Driver code$n = 2;echo sum($n); // This code is contributed by mits?> <script> // JavaScript implementation of the approach // Function to return sumfunction sum(n){ if (n == 1) { return 2; } else { return (n * (n + 1) + sum(n - 1)); }} // Driver coden = 2;document.write(sum(n)); // This code is contributed by rutvik_56. </script> 8 Time Complexity: O(n) Auxiliary Space: O(n)Efficient Solution We can solve this problem using direct formula. Sum can be written as below ∑(n * (n+1)) ∑(n*n + n) = ∑(n*n) + ∑(n)We can apply the formulas for sum squares of natural number and sum of natural numbers.= n(n+1)(2n+1)/6 + n*(n+1)/2 = n * (n + 1) * (n + 2) / 3 C++ Java Python3 C# PHP Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return sumint sum(int n){ return n * (n + 1) * (n + 2) / 3;} // Driver codeint main(){ int n = 2; cout << sum(n);} // Java implementation of the approachclass GFG{ // Function to return sumstatic int sum(int n){ return n * (n + 1) * (n + 2) / 3;} // Driver codepublic static void main(String[] args){ int n = 2; System.out.println(sum(n));}} // This code is contributed by Code_Mech # Python3 implementation of the approach. # Function to return sumdef Sum(n): return n * (n + 1) * (n + 2) // 3 # Driver codeif __name__ == "__main__": n = 2; print(Sum(n)) # This code is contributed# by Rituraj Jain // C# implementation of the approachusing System; class GFG{ // Function to return sumstatic int sum(int n){ return n * (n + 1) * (n + 2) / 3;} // Driver codepublic static void Main(String[] args){ int n = 2; Console.WriteLine(sum(n));}}// This code contributed by Rajput-Ji <?php// PHP implementation of the approach // Function to return sumfunction sum($n){ return $n * ($n + 1) * ($n + 2) / 3;} // Driver code$n = 2;echo sum($n); // This code is contributed// by 29AjayKumar?> <script>// Javascript implementation of the approach // Function to return sumfunction sum(n){ return n * (n + 1) * (n + 2) / 3;} // Driver codevar n = 2;document.write(sum(n)); // This code is contributed by noob2000.</script> 8 Time Complexity: O(1)Auxiliary Space: O(1) Mithun Kumar rituraj_jain Code_Mech Rajput-Ji 29AjayKumar rutvik_56 noob2000 subham348 series-sum Mathematical Recursion Mathematical Recursion Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Algorithm to solve Rubik's Cube Program to print prime numbers from 1 to N. Merge two sorted arrays with O(1) extra space Segment Tree | Set 1 (Sum of given range) 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 Print all subsequences of a string
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Jun, 2022" }, { "code": null, "e": 134, "s": 28, "text": "Given a value n, the task is to find sum of the series (1*2) + (2*3) + (3*4) + ......+ n termsExamples: " }, { "code": null, "e": 274, "s": 134, "text": "Input: n = 2\nOutput: 8\nExplanation:\n(1*2) + (2*3)\n= 2 + 6\n= 8\n\nInput: n = 3\nOutput: 20\nExplanation:\n(1*2) + (2*3) + (2*4)\n= 2 + 6 + 12\n= 20" }, { "code": null, "e": 358, "s": 276, "text": "Simple Solution One by one add elements recursively.Below is the implementation " }, { "code": null, "e": 362, "s": 358, "text": "C++" }, { "code": null, "e": 367, "s": 362, "text": "Java" }, { "code": null, "e": 375, "s": 367, "text": "Python3" }, { "code": null, "e": 378, "s": 375, "text": "C#" }, { "code": null, "e": 382, "s": 378, "text": "PHP" }, { "code": null, "e": 393, "s": 382, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return sumint sum(int n){ if (n == 1) { return 2; } else { return (n * (n + 1) + sum(n - 1)); }} // Driver codeint main(){ int n = 2; cout << sum(n);}", "e": 674, "s": 393, "text": null }, { "code": "// Java implementation of the approach class Solution { // Function to return a the required result static int sum(int n) { if (n == 1) { return 2; } else { return (n * (n + 1) + sum(n - 1)); } } // Driver code public static void main(String args[]) { int n = 2; System.out.println(sum(n)); }}", "e": 1057, "s": 674, "text": null }, { "code": "# Python3 implementation of the approach # Function to return sumdef sum(n): if (n == 1): return 2; else: return (n * (n + 1) + sum(n - 1)); # Driver code n = 2;print(sum(n)); # This code is contributed by mits", "e": 1289, "s": 1057, "text": null }, { "code": "// Csharp implementation of the approach using System; class Solution { // Function to return a the required result static int sum(int n) { if (n == 1) { return 2; } else { return (n * (n + 1) + sum(n - 1)); } } // Driver code public static void Main() { int n = 2; Console.WrieLine(sum(n)); }}", "e": 1673, "s": 1289, "text": null }, { "code": "<?php// PHP implementation of the approach // Function to return sumfunction sum($n){ if ($n == 1) { return 2; } else { return ($n * ($n + 1) + sum($n - 1)); }} // Driver code$n = 2;echo sum($n); // This code is contributed by mits?>", "e": 1956, "s": 1673, "text": null }, { "code": "<script> // JavaScript implementation of the approach // Function to return sumfunction sum(n){ if (n == 1) { return 2; } else { return (n * (n + 1) + sum(n - 1)); }} // Driver coden = 2;document.write(sum(n)); // This code is contributed by rutvik_56. </script>", "e": 2245, "s": 1956, "text": null }, { "code": null, "e": 2247, "s": 2245, "text": "8" }, { "code": null, "e": 2271, "s": 2249, "text": "Time Complexity: O(n)" }, { "code": null, "e": 2571, "s": 2271, "text": "Auxiliary Space: O(n)Efficient Solution We can solve this problem using direct formula. Sum can be written as below ∑(n * (n+1)) ∑(n*n + n) = ∑(n*n) + ∑(n)We can apply the formulas for sum squares of natural number and sum of natural numbers.= n(n+1)(2n+1)/6 + n*(n+1)/2 = n * (n + 1) * (n + 2) / 3 " }, { "code": null, "e": 2575, "s": 2571, "text": "C++" }, { "code": null, "e": 2580, "s": 2575, "text": "Java" }, { "code": null, "e": 2588, "s": 2580, "text": "Python3" }, { "code": null, "e": 2591, "s": 2588, "text": "C#" }, { "code": null, "e": 2595, "s": 2591, "text": "PHP" }, { "code": null, "e": 2606, "s": 2595, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return sumint sum(int n){ return n * (n + 1) * (n + 2) / 3;} // Driver codeint main(){ int n = 2; cout << sum(n);}", "e": 2827, "s": 2606, "text": null }, { "code": "// Java implementation of the approachclass GFG{ // Function to return sumstatic int sum(int n){ return n * (n + 1) * (n + 2) / 3;} // Driver codepublic static void main(String[] args){ int n = 2; System.out.println(sum(n));}} // This code is contributed by Code_Mech", "e": 3108, "s": 2827, "text": null }, { "code": "# Python3 implementation of the approach. # Function to return sumdef Sum(n): return n * (n + 1) * (n + 2) // 3 # Driver codeif __name__ == \"__main__\": n = 2; print(Sum(n)) # This code is contributed# by Rituraj Jain", "e": 3336, "s": 3108, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{ // Function to return sumstatic int sum(int n){ return n * (n + 1) * (n + 2) / 3;} // Driver codepublic static void Main(String[] args){ int n = 2; Console.WriteLine(sum(n));}}// This code contributed by Rajput-Ji", "e": 3630, "s": 3336, "text": null }, { "code": "<?php// PHP implementation of the approach // Function to return sumfunction sum($n){ return $n * ($n + 1) * ($n + 2) / 3;} // Driver code$n = 2;echo sum($n); // This code is contributed// by 29AjayKumar?>", "e": 3839, "s": 3630, "text": null }, { "code": "<script>// Javascript implementation of the approach // Function to return sumfunction sum(n){ return n * (n + 1) * (n + 2) / 3;} // Driver codevar n = 2;document.write(sum(n)); // This code is contributed by noob2000.</script>", "e": 4070, "s": 3839, "text": null }, { "code": null, "e": 4072, "s": 4070, "text": "8" }, { "code": null, "e": 4119, "s": 4074, "text": " Time Complexity: O(1)Auxiliary Space: O(1) " }, { "code": null, "e": 4132, "s": 4119, "text": "Mithun Kumar" }, { "code": null, "e": 4145, "s": 4132, "text": "rituraj_jain" }, { "code": null, "e": 4155, "s": 4145, "text": "Code_Mech" }, { "code": null, "e": 4165, "s": 4155, "text": "Rajput-Ji" }, { "code": null, "e": 4177, "s": 4165, "text": "29AjayKumar" }, { "code": null, "e": 4187, "s": 4177, "text": "rutvik_56" }, { "code": null, "e": 4196, "s": 4187, "text": "noob2000" }, { "code": null, "e": 4206, "s": 4196, "text": "subham348" }, { "code": null, "e": 4217, "s": 4206, "text": "series-sum" }, { "code": null, "e": 4230, "s": 4217, "text": "Mathematical" }, { "code": null, "e": 4240, "s": 4230, "text": "Recursion" }, { "code": null, "e": 4253, "s": 4240, "text": "Mathematical" }, { "code": null, "e": 4263, "s": 4253, "text": "Recursion" }, { "code": null, "e": 4361, "s": 4263, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4393, "s": 4361, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 4437, "s": 4393, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 4483, "s": 4437, "text": "Merge two sorted arrays with O(1) extra space" }, { "code": null, "e": 4525, "s": 4483, "text": "Segment Tree | Set 1 (Sum of given range)" }, { "code": null, "e": 4550, "s": 4525, "text": "Fizz Buzz Implementation" }, { "code": null, "e": 4635, "s": 4550, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 4645, "s": 4635, "text": "Recursion" }, { "code": null, "e": 4672, "s": 4645, "text": "Program for Tower of Hanoi" }, { "code": null, "e": 4700, "s": 4672, "text": "Backtracking | Introduction" } ]
How to Deploy Django project on PythonAnywhere?
26 Nov, 2020 Django has become one of popular frameworks over the past few years. Often, after creating your django project, you are confused, how to share it with people around you. This article revolves around how you can host your django application on pythonanywhere for free. So let’s get started ..!! Let’s create a simple application in Django for showing the deployment. Initialize your Django Project django-admin startproject deploy_on_pythonanywhere Open project in your editor and under settings.py make: ALLOWED_HOSTS = ['*'] Create requirements.txt file using the command pip3 freeze > requirements.txt File structure of our project looks like this: deploy_on_pythonanywhere ├── db.sqlite3 ├── deploy_on_pythonanywhere │ ├── asgi.py │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-38.pyc │ │ ├── settings.cpython-38.pyc │ │ ├── urls.cpython-38.pyc │ │ └── wsgi.cpython-38.pyc │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── manage.py └── requirements.txt Let’s Start our Django Server cd deploy_on_pythonanywhere python3 manage.py runserver Yahooooo, your server is running on localhost But wait, wait... that’s not over, let’s make it live for the world Follow this link to push the project on github – How to Upload a Project on Github? Create an account on pythonanywhere – Click Here After Register, you can see the page like this Now click on Console then select Bash you’ll see like this Run following commands on bash: Clone GitHub repo git clone https://github.com/Prakhar-Mangal/deploy_on_pythonanywhere.git Now create and setup environment variables python3 -m venv env #create virtual environment source env/bin/activate #activate virtual environment cd deploy_on_pythonanywhere #navigate inside your project pip install -r requirements.txt #installing dependencies using requirements.txt Now copy the path of your directories which you installed on bash Type command on bash cd ls # get list of directories pwd #copy the path for future use Here it looks like: Hurree, we set up our project successfully : ) But wait wait, follow the final process and we’re ready to go Now click on Web then select Add a new web app Click on next and follow the procedure select Django as the framework Select python3.8 (latest) and click on next till last. Now under the Web section open the WSGI configuration file Edit WSGI configuration file on line no. 12 and 17 remove the word mysite with your project name which you cloned from GitHub, in my case it is deploy_on_pythonanywhere Now it looks like this and then click on save: Select Virtualenv section under Web: Enter the path of Virtualenv as we created using bash (refer above pwd command for path) Click on Reload under the Web section and visit the link Python Django Python Framework Technical Scripter 2020 Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to iterate through Excel rows in Python? Rotate axis tick labels in Seaborn and Matplotlib Deque in Python Queue in Python Defaultdict in Python Check if element exists in list in Python Python Classes and Objects Bar Plot in Matplotlib reduce() in Python Python | Get unique values from a list
[ { "code": null, "e": 54, "s": 26, "text": "\n26 Nov, 2020" }, { "code": null, "e": 348, "s": 54, "text": "Django has become one of popular frameworks over the past few years. Often, after creating your django project, you are confused, how to share it with people around you. This article revolves around how you can host your django application on pythonanywhere for free. So let’s get started ..!!" }, { "code": null, "e": 421, "s": 348, "text": "Let’s create a simple application in Django for showing the deployment. " }, { "code": null, "e": 453, "s": 421, "text": "Initialize your Django Project " }, { "code": null, "e": 506, "s": 453, "text": "django-admin startproject deploy_on_pythonanywhere\n\n" }, { "code": null, "e": 562, "s": 506, "text": "Open project in your editor and under settings.py make:" }, { "code": null, "e": 585, "s": 562, "text": "ALLOWED_HOSTS = ['*']\n" }, { "code": null, "e": 632, "s": 585, "text": "Create requirements.txt file using the command" }, { "code": null, "e": 665, "s": 632, "text": "pip3 freeze > requirements.txt\n\n" }, { "code": null, "e": 712, "s": 665, "text": "File structure of our project looks like this:" }, { "code": null, "e": 1062, "s": 712, "text": "deploy_on_pythonanywhere\n├── db.sqlite3\n├── deploy_on_pythonanywhere\n│ ├── asgi.py\n│ ├── __init__.py\n│ ├── __pycache__\n│ │ ├── __init__.cpython-38.pyc\n│ │ ├── settings.cpython-38.pyc\n│ │ ├── urls.cpython-38.pyc\n│ │ └── wsgi.cpython-38.pyc\n│ ├── settings.py\n│ ├── urls.py\n│ └── wsgi.py\n├── manage.py\n└── requirements.txt\n\n" }, { "code": null, "e": 1092, "s": 1062, "text": "Let’s Start our Django Server" }, { "code": null, "e": 1149, "s": 1092, "text": "cd deploy_on_pythonanywhere\npython3 manage.py runserver\n" }, { "code": null, "e": 1264, "s": 1149, "text": "Yahooooo, your server is running on localhost But wait, wait... that’s not over, let’s make it live for the world" }, { "code": null, "e": 1348, "s": 1264, "text": "Follow this link to push the project on github – How to Upload a Project on Github?" }, { "code": null, "e": 1398, "s": 1348, "text": "Create an account on pythonanywhere – Click Here" }, { "code": null, "e": 1445, "s": 1398, "text": "After Register, you can see the page like this" }, { "code": null, "e": 1504, "s": 1445, "text": "Now click on Console then select Bash you’ll see like this" }, { "code": null, "e": 1536, "s": 1504, "text": "Run following commands on bash:" }, { "code": null, "e": 1554, "s": 1536, "text": "Clone GitHub repo" }, { "code": null, "e": 1628, "s": 1554, "text": "git clone https://github.com/Prakhar-Mangal/deploy_on_pythonanywhere.git\n" }, { "code": null, "e": 1671, "s": 1628, "text": "Now create and setup environment variables" }, { "code": null, "e": 1913, "s": 1671, "text": "python3 -m venv env #create virtual environment\nsource env/bin/activate #activate virtual environment\ncd deploy_on_pythonanywhere #navigate inside your project \npip install -r requirements.txt #installing dependencies using requirements.txt\n" }, { "code": null, "e": 1979, "s": 1913, "text": "Now copy the path of your directories which you installed on bash" }, { "code": null, "e": 2000, "s": 1979, "text": "Type command on bash" }, { "code": null, "e": 2068, "s": 2000, "text": "cd\nls # get list of directories\npwd #copy the path for future use\n\n" }, { "code": null, "e": 2088, "s": 2068, "text": "Here it looks like:" }, { "code": null, "e": 2197, "s": 2088, "text": "Hurree, we set up our project successfully : ) But wait wait, follow the final process and we’re ready to go" }, { "code": null, "e": 2244, "s": 2197, "text": "Now click on Web then select Add a new web app" }, { "code": null, "e": 2283, "s": 2244, "text": "Click on next and follow the procedure" }, { "code": null, "e": 2314, "s": 2283, "text": "select Django as the framework" }, { "code": null, "e": 2370, "s": 2314, "text": "Select python3.8 (latest) and click on next till last. " }, { "code": null, "e": 2429, "s": 2370, "text": "Now under the Web section open the WSGI configuration file" }, { "code": null, "e": 2598, "s": 2429, "text": "Edit WSGI configuration file on line no. 12 and 17 remove the word mysite with your project name which you cloned from GitHub, in my case it is deploy_on_pythonanywhere" }, { "code": null, "e": 2645, "s": 2598, "text": "Now it looks like this and then click on save:" }, { "code": null, "e": 2682, "s": 2645, "text": "Select Virtualenv section under Web:" }, { "code": null, "e": 2771, "s": 2682, "text": "Enter the path of Virtualenv as we created using bash (refer above pwd command for path)" }, { "code": null, "e": 2828, "s": 2771, "text": "Click on Reload under the Web section and visit the link" }, { "code": null, "e": 2844, "s": 2830, "text": "Python Django" }, { "code": null, "e": 2861, "s": 2844, "text": "Python Framework" }, { "code": null, "e": 2885, "s": 2861, "text": "Technical Scripter 2020" }, { "code": null, "e": 2892, "s": 2885, "text": "Python" }, { "code": null, "e": 2911, "s": 2892, "text": "Technical Scripter" }, { "code": null, "e": 3009, "s": 2911, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3054, "s": 3009, "text": "How to iterate through Excel rows in Python?" }, { "code": null, "e": 3104, "s": 3054, "text": "Rotate axis tick labels in Seaborn and Matplotlib" }, { "code": null, "e": 3120, "s": 3104, "text": "Deque in Python" }, { "code": null, "e": 3136, "s": 3120, "text": "Queue in Python" }, { "code": null, "e": 3158, "s": 3136, "text": "Defaultdict in Python" }, { "code": null, "e": 3200, "s": 3158, "text": "Check if element exists in list in Python" }, { "code": null, "e": 3227, "s": 3200, "text": "Python Classes and Objects" }, { "code": null, "e": 3250, "s": 3227, "text": "Bar Plot in Matplotlib" }, { "code": null, "e": 3269, "s": 3250, "text": "reduce() in Python" } ]
Handling Missing Values in R Programming
08 Nov, 2021 As the name indicates, Missing values are those elements which are not known. NA or NaN are reserved words that indicate a missing value in R Programming language for q arithmetical operations that are undefined. Missing values are practical in life. For example, some cells in spreadsheets are empty. If an insensible or impossible arithmetic operation is tried then NAs occur. Missing Values in R, are handled with the use of some pre-defined functions: A logical vector is returned by this function that indicates all the NA values present. It returns a Boolean value. If NA is present in a vector it returns TRUE else FALSE. R x<- c(NA, 3, 4, NA, NA, NA)is.na(x) Output: [1] TRUE FALSE FALSE TRUE TRUE TRUE A logical vector is returned by this function that indicates all the NaN values present. It returns a Boolean value. If NaN is present in a vector it returns TRUE else FALSE. R x<- c(NA, 3, 4, NA, NA, 0 / 0, 0 / 0)is.nan(x) Output: [1] FALSE FALSE FALSE FALSE FALSE TRUE TRUE For testing objects that are NA use is.na() For testing objects that are NaN use is.nan() There are classes under which NA comes. Hence integer class has integer type NA, the character class has character type NA, etc. A NaN value is counted in NA but the reverse is not valid. The creation of a vector with one or multiple NAs is also possible. R x<- c(NA, 3, 4, NA, NA, NA)x Output: [1] NA 3 4 NA NA NA There are two ways to remove missing values: Example 1: R x <- c(1, 2, NA, 3, NA, 4)d <- is.na(x)x[! d] Output: [1] 1 2 3 4 Example 2: R x <- c(1, 2, 0 / 0, 3, NA, 4, 0 / 0)xx[! is.na(x)] Output: [1] 1 2 NaN 3 NA 4 NaN [1] 1 2 3 4 Function called complete.cases() can also be used. This function also works on data frames. The modeling functions in R language acknowledge a na.action argument which provides instructions to the function regarding its response if NA comes in its way. And hence this way the function calls one of the missing value filter functions. Missing Value Filter Functions alter the data set and in the new data set the value of NAs has been changed. The default Missing Value Filter Function is na.omit. It omits every row containing even one NA. Some other Missing Value Filter Functions are: na.omit– omits every row containing even one NA na.fail– halts and does not proceed if NA is encountered na.exclude– excludes every row containing even one NA but keeps a record of their original position na.pass– it just ignores NA and passes through it R # Creating a data framedf <- data.frame (c1 = 1:8, c2 = factor (c("B", "A", "B", "C", "A", "C", "B", "A"))) # Filling some NA in data framedf[4, 1] <- df[6, 2] <- NA # Printing all the levels(NA is not considered one)levels(df$c2) # fails if NA is encounteredna.fail (df) # excludes every row containing even one NAna.exclude (a) Output: [1] "A" "B" "C" Error in na.fail.default(df) : missing values in object Calls: na.fail -> na.fail.default Execution halted Factor Vectors– is the symbol displayed in factor vectors for missing values. NaN – This is a special case of NA only. It is displayed when an arithmetic operation yields a result which is not a number. For example, dividing zero by zero produces NaN. kumar_satyam R-basics R-Factors R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change Color of Bars in Barchart using ggplot2 in R How to Split Column Into Multiple Columns in R DataFrame? Group by function in R using Dplyr How to Change Axis Scales in R Plots? How to filter R DataFrame by values in a column? R - if statement Logistic Regression in R Programming Replace Specific Characters in String in R How to import an Excel File into R ? Joining of Dataframes in R Programming
[ { "code": null, "e": 28, "s": 0, "text": "\n08 Nov, 2021" }, { "code": null, "e": 242, "s": 28, "text": "As the name indicates, Missing values are those elements which are not known. NA or NaN are reserved words that indicate a missing value in R Programming language for q arithmetical operations that are undefined. " }, { "code": null, "e": 409, "s": 242, "text": "Missing values are practical in life. For example, some cells in spreadsheets are empty. If an insensible or impossible arithmetic operation is tried then NAs occur. " }, { "code": null, "e": 487, "s": 409, "text": "Missing Values in R, are handled with the use of some pre-defined functions: " }, { "code": null, "e": 660, "s": 487, "text": "A logical vector is returned by this function that indicates all the NA values present. It returns a Boolean value. If NA is present in a vector it returns TRUE else FALSE." }, { "code": null, "e": 662, "s": 660, "text": "R" }, { "code": "x<- c(NA, 3, 4, NA, NA, NA)is.na(x)", "e": 698, "s": 662, "text": null }, { "code": null, "e": 707, "s": 698, "text": "Output: " }, { "code": null, "e": 747, "s": 707, "text": "[1] TRUE FALSE FALSE TRUE TRUE TRUE" }, { "code": null, "e": 922, "s": 747, "text": "A logical vector is returned by this function that indicates all the NaN values present. It returns a Boolean value. If NaN is present in a vector it returns TRUE else FALSE." }, { "code": null, "e": 924, "s": 922, "text": "R" }, { "code": "x<- c(NA, 3, 4, NA, NA, 0 / 0, 0 / 0)is.nan(x)", "e": 971, "s": 924, "text": null }, { "code": null, "e": 980, "s": 971, "text": "Output: " }, { "code": null, "e": 1026, "s": 980, "text": "[1] FALSE FALSE FALSE FALSE FALSE TRUE TRUE" }, { "code": null, "e": 1070, "s": 1026, "text": "For testing objects that are NA use is.na()" }, { "code": null, "e": 1116, "s": 1070, "text": "For testing objects that are NaN use is.nan()" }, { "code": null, "e": 1245, "s": 1116, "text": "There are classes under which NA comes. Hence integer class has integer type NA, the character class has character type NA, etc." }, { "code": null, "e": 1304, "s": 1245, "text": "A NaN value is counted in NA but the reverse is not valid." }, { "code": null, "e": 1372, "s": 1304, "text": "The creation of a vector with one or multiple NAs is also possible." }, { "code": null, "e": 1374, "s": 1372, "text": "R" }, { "code": "x<- c(NA, 3, 4, NA, NA, NA)x", "e": 1403, "s": 1374, "text": null }, { "code": null, "e": 1412, "s": 1403, "text": "Output: " }, { "code": null, "e": 1434, "s": 1412, "text": "[1] NA 3 4 NA NA NA" }, { "code": null, "e": 1480, "s": 1434, "text": "There are two ways to remove missing values: " }, { "code": null, "e": 1492, "s": 1480, "text": "Example 1: " }, { "code": null, "e": 1494, "s": 1492, "text": "R" }, { "code": "x <- c(1, 2, NA, 3, NA, 4)d <- is.na(x)x[! d]", "e": 1540, "s": 1494, "text": null }, { "code": null, "e": 1549, "s": 1540, "text": "Output: " }, { "code": null, "e": 1561, "s": 1549, "text": "[1] 1 2 3 4" }, { "code": null, "e": 1573, "s": 1561, "text": "Example 2: " }, { "code": null, "e": 1575, "s": 1573, "text": "R" }, { "code": "x <- c(1, 2, 0 / 0, 3, NA, 4, 0 / 0)xx[! is.na(x)]", "e": 1626, "s": 1575, "text": null }, { "code": null, "e": 1635, "s": 1626, "text": "Output: " }, { "code": null, "e": 1679, "s": 1635, "text": "[1] 1 2 NaN 3 NA 4 NaN\n[1] 1 2 3 4" }, { "code": null, "e": 1771, "s": 1679, "text": "Function called complete.cases() can also be used. This function also works on data frames." }, { "code": null, "e": 1932, "s": 1771, "text": "The modeling functions in R language acknowledge a na.action argument which provides instructions to the function regarding its response if NA comes in its way." }, { "code": null, "e": 2267, "s": 1932, "text": "And hence this way the function calls one of the missing value filter functions. Missing Value Filter Functions alter the data set and in the new data set the value of NAs has been changed. The default Missing Value Filter Function is na.omit. It omits every row containing even one NA. Some other Missing Value Filter Functions are: " }, { "code": null, "e": 2315, "s": 2267, "text": "na.omit– omits every row containing even one NA" }, { "code": null, "e": 2372, "s": 2315, "text": "na.fail– halts and does not proceed if NA is encountered" }, { "code": null, "e": 2472, "s": 2372, "text": "na.exclude– excludes every row containing even one NA but keeps a record of their original position" }, { "code": null, "e": 2522, "s": 2472, "text": "na.pass– it just ignores NA and passes through it" }, { "code": null, "e": 2524, "s": 2522, "text": "R" }, { "code": "# Creating a data framedf <- data.frame (c1 = 1:8, c2 = factor (c(\"B\", \"A\", \"B\", \"C\", \"A\", \"C\", \"B\", \"A\"))) # Filling some NA in data framedf[4, 1] <- df[6, 2] <- NA # Printing all the levels(NA is not considered one)levels(df$c2) # fails if NA is encounteredna.fail (df) # excludes every row containing even one NAna.exclude (a)", "e": 2903, "s": 2524, "text": null }, { "code": null, "e": 2912, "s": 2903, "text": "Output: " }, { "code": null, "e": 3035, "s": 2912, "text": "[1] \"A\" \"B\" \"C\"\nError in na.fail.default(df) : missing values in object\nCalls: na.fail -> na.fail.default\nExecution halted" }, { "code": null, "e": 3113, "s": 3035, "text": "Factor Vectors– is the symbol displayed in factor vectors for missing values." }, { "code": null, "e": 3287, "s": 3113, "text": "NaN – This is a special case of NA only. It is displayed when an arithmetic operation yields a result which is not a number. For example, dividing zero by zero produces NaN." }, { "code": null, "e": 3300, "s": 3287, "text": "kumar_satyam" }, { "code": null, "e": 3309, "s": 3300, "text": "R-basics" }, { "code": null, "e": 3319, "s": 3309, "text": "R-Factors" }, { "code": null, "e": 3330, "s": 3319, "text": "R Language" }, { "code": null, "e": 3428, "s": 3330, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3480, "s": 3428, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 3538, "s": 3480, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 3573, "s": 3538, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 3611, "s": 3573, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 3660, "s": 3611, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 3677, "s": 3660, "text": "R - if statement" }, { "code": null, "e": 3714, "s": 3677, "text": "Logistic Regression in R Programming" }, { "code": null, "e": 3757, "s": 3714, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 3794, "s": 3757, "text": "How to import an Excel File into R ?" } ]
Neo4j - Count Function
Assume we have created a graph in the database with the following details. The count() function is used to count the number of rows. Following is the syntax of the count function. MATCH (n { name: 'A' })-->(x) RETURN n, count(*) Following is a sample Cypher Query which demonstrates the usage of the count() function. Match(n{name: "India", result: "Winners"})--(x) RETURN n, count(*) To execute the above query, carry out the following steps − Step 1 − Open the Neo4j desktop App and start the Neo4j Server. Open the built-in browser app of Neo4j using the URL http://localhost:7474/ as shown in the following screenshot. Step 2 − Copy and paste the desired query in the dollar prompt and press the play button (to execute the query) highlighted in the following screenshot. On executing, you will get the following result. The COUNT clause is also used to count the groups of relationship types. Following is a sample Cypher Query which counts and returns the number of nodes participating in each relation. Match(n{name: "India", result: "Winners"})-[r]-(x) RETURN type (r), count(*) To execute the above query, carry out the following steps − Step 1 − Open the Neo4j desktop App and start the Neo4j Server. Open the built-in browser app of Neo4j using the URL http://localhost:7474/ as shown in the following screenshot. Step 2 − Copy and paste the desired query in the dollar prompt and press the play button (to execute the query) highlighted in the following screenshot. On executing, you will get the following result.
[ { "code": null, "e": 2548, "s": 2473, "text": "Assume we have created a graph in the database with the following details." }, { "code": null, "e": 2606, "s": 2548, "text": "The count() function is used to count the number of rows." }, { "code": null, "e": 2653, "s": 2606, "text": "Following is the syntax of the count function." }, { "code": null, "e": 2705, "s": 2653, "text": "MATCH (n { name: 'A' })-->(x) \nRETURN n, count(*) \n" }, { "code": null, "e": 2794, "s": 2705, "text": "Following is a sample Cypher Query which demonstrates the usage of the count() function." }, { "code": null, "e": 2864, "s": 2794, "text": "Match(n{name: \"India\", result: \"Winners\"})--(x) \nRETURN n, count(*) " }, { "code": null, "e": 2924, "s": 2864, "text": "To execute the above query, carry out the following steps −" }, { "code": null, "e": 3102, "s": 2924, "text": "Step 1 − Open the Neo4j desktop App and start the Neo4j Server. Open the built-in browser app of Neo4j using the URL http://localhost:7474/ as shown in the following screenshot." }, { "code": null, "e": 3255, "s": 3102, "text": "Step 2 − Copy and paste the desired query in the dollar prompt and press the play button (to execute the query) highlighted in the following screenshot." }, { "code": null, "e": 3304, "s": 3255, "text": "On executing, you will get the following result." }, { "code": null, "e": 3377, "s": 3304, "text": "The COUNT clause is also used to count the groups of relationship types." }, { "code": null, "e": 3489, "s": 3377, "text": "Following is a sample Cypher Query which counts and returns the number of nodes participating in each relation." }, { "code": null, "e": 3569, "s": 3489, "text": "Match(n{name: \"India\", result: \"Winners\"})-[r]-(x) \nRETURN type (r), count(*) " }, { "code": null, "e": 3629, "s": 3569, "text": "To execute the above query, carry out the following steps −" }, { "code": null, "e": 3807, "s": 3629, "text": "Step 1 − Open the Neo4j desktop App and start the Neo4j Server. Open the built-in browser app of Neo4j using the URL http://localhost:7474/ as shown in the following screenshot." }, { "code": null, "e": 3960, "s": 3807, "text": "Step 2 − Copy and paste the desired query in the dollar prompt and press the play button (to execute the query) highlighted in the following screenshot." } ]
Print multiples of Unit Digit of Given Number
07 Jul, 2022 Given a number The task is to print the multiples of the unit digit of N from the unit digit of N to N. Note: If the unit digit is 0 then print the multiples of 10.Examples: Input : 39 Output : 9 18 27 36 Explanation : The unit digit of 39 is 9. So the multiples of 9 between 9 and 39 are: 9, 18, 27, 36 Input : 25 Output : 5 10 15 20 25 Simple Approach Find the unit digit of the input number. The unit digit of N will be (N%10), i.e., remainder upon dividing N by 10.Check if the unit digit is 0. If yes, then consider the multiple as 10.Print the multiples of unit digit until it is less than or equal to the input number. Find the unit digit of the input number. The unit digit of N will be (N%10), i.e., remainder upon dividing N by 10. Check if the unit digit is 0. If yes, then consider the multiple as 10. If yes, then consider the multiple as 10. Print the multiples of unit digit until it is less than or equal to the input number. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to print multiples of// Unit Digit of Given Number#include <iostream> using namespace std; // Function to print the multiples// of unit digitvoid printMultiples(int n){ // Find the unit digit of // the given number int unit_digit = n % 10; // if the unit digit is 0 then // change it to 10 if (unit_digit == 0) unit_digit = 10; // print the multiples of unit digit // until the multiple is less than // or equal to n for (int i = unit_digit; i <= n; i += unit_digit) cout << i << " ";} // Driver Codeint main(){ int n = 39; printMultiples(n); return 0;} // Java program to print multiples of// Unit Digit of Given Numberimport java.io.*; class GFG{ // Function to print the multiples// of unit digitstatic void printMultiples(int n){ // Find the unit digit of // the given number int unit_digit = n % 10; // if the unit digit is 0 then // change it to 10 if (unit_digit == 0) unit_digit = 10; // print the multiples of unit digit // until the multiple is less than // or equal to n for (int i = unit_digit; i <= n; i += unit_digit) System.out.print( i + " ");} // Driver Code public static void main (String[] args) { int n = 39; printMultiples(n); }} // This code is contributed by inder_mca # Python3 program to print multiples# of Unit Digit of Given Number # Function to print the multiples# of unit digitdef printMultiples(n): # Find the unit digit of # the given number unit_digit = n % 10 # if the unit digit is 0 then # change it to 10 if (unit_digit == 0): unit_digit = 10 # print the multiples of unit digit # until the multiple is less than # or equal to n for i in range(unit_digit, n + 1, unit_digit): print(i, end = " ") # Driver Coden = 39 printMultiples(n) # This code is contributed by Mohit Kumar // C# program to print multiples of// Unit Digit of Given Numberusing System; class GFG{ // Function to print the multiples // of unit digit static void printMultiples(int n) { // Find the unit digit of // the given number int unit_digit = n % 10; // if the unit digit is 0 then // change it to 10 if (unit_digit == 0) unit_digit = 10; // print the multiples of unit digit // until the multiple is less than // or equal to n for (int i = unit_digit; i <= n; i += unit_digit) Console.Write( i + " "); } // Driver Code public static void Main () { int n = 39; printMultiples(n); }} // This code is contributed by Ryuga <script> // JavaScript program to print multiples of // Unit Digit of Given Number // Function to print the multiples // of unit digit function printMultiples(n) { // Find the unit digit of // the given number var unit_digit = parseInt(n % 10); // if the unit digit is 0 then // change it to 10 if (unit_digit == 0) unit_digit = 10; // print the multiples of unit digit // until the multiple is less than // or equal to n for (var i = unit_digit; i <= n; i += unit_digit) document.write(i + " "); } // Driver Code var n = 39; printMultiples(n); </script> 9 18 27 36 Time Complexity: O(N)Auxiliary Space: O(1) inderDuMCA ankthon mohit kumar 29 rdtank jayanth_mkv factor Technical Scripter 2018 C++ C++ Programs School Programming Technical Scripter CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n07 Jul, 2022" }, { "code": null, "e": 230, "s": 53, "text": "Given a number The task is to print the multiples of the unit digit of N from the unit digit of N to N. Note: If the unit digit is 0 then print the multiples of 10.Examples: " }, { "code": null, "e": 396, "s": 230, "text": "Input : 39 \nOutput : 9 18 27 36\nExplanation : The unit digit of 39 is 9.\nSo the multiples of 9 between 9 and 39 are:\n9, 18, 27, 36\n\nInput : 25\nOutput : 5 10 15 20 25" }, { "code": null, "e": 416, "s": 398, "text": "Simple Approach " }, { "code": null, "e": 688, "s": 416, "text": "Find the unit digit of the input number. The unit digit of N will be (N%10), i.e., remainder upon dividing N by 10.Check if the unit digit is 0. If yes, then consider the multiple as 10.Print the multiples of unit digit until it is less than or equal to the input number." }, { "code": null, "e": 804, "s": 688, "text": "Find the unit digit of the input number. The unit digit of N will be (N%10), i.e., remainder upon dividing N by 10." }, { "code": null, "e": 876, "s": 804, "text": "Check if the unit digit is 0. If yes, then consider the multiple as 10." }, { "code": null, "e": 918, "s": 876, "text": "If yes, then consider the multiple as 10." }, { "code": null, "e": 1004, "s": 918, "text": "Print the multiples of unit digit until it is less than or equal to the input number." }, { "code": null, "e": 1057, "s": 1004, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 1061, "s": 1057, "text": "C++" }, { "code": null, "e": 1066, "s": 1061, "text": "Java" }, { "code": null, "e": 1074, "s": 1066, "text": "Python3" }, { "code": null, "e": 1077, "s": 1074, "text": "C#" }, { "code": null, "e": 1088, "s": 1077, "text": "Javascript" }, { "code": "// C++ program to print multiples of// Unit Digit of Given Number#include <iostream> using namespace std; // Function to print the multiples// of unit digitvoid printMultiples(int n){ // Find the unit digit of // the given number int unit_digit = n % 10; // if the unit digit is 0 then // change it to 10 if (unit_digit == 0) unit_digit = 10; // print the multiples of unit digit // until the multiple is less than // or equal to n for (int i = unit_digit; i <= n; i += unit_digit) cout << i << \" \";} // Driver Codeint main(){ int n = 39; printMultiples(n); return 0;}", "e": 1714, "s": 1088, "text": null }, { "code": "// Java program to print multiples of// Unit Digit of Given Numberimport java.io.*; class GFG{ // Function to print the multiples// of unit digitstatic void printMultiples(int n){ // Find the unit digit of // the given number int unit_digit = n % 10; // if the unit digit is 0 then // change it to 10 if (unit_digit == 0) unit_digit = 10; // print the multiples of unit digit // until the multiple is less than // or equal to n for (int i = unit_digit; i <= n; i += unit_digit) System.out.print( i + \" \");} // Driver Code public static void main (String[] args) { int n = 39; printMultiples(n); }} // This code is contributed by inder_mca", "e": 2426, "s": 1714, "text": null }, { "code": "# Python3 program to print multiples# of Unit Digit of Given Number # Function to print the multiples# of unit digitdef printMultiples(n): # Find the unit digit of # the given number unit_digit = n % 10 # if the unit digit is 0 then # change it to 10 if (unit_digit == 0): unit_digit = 10 # print the multiples of unit digit # until the multiple is less than # or equal to n for i in range(unit_digit, n + 1, unit_digit): print(i, end = \" \") # Driver Coden = 39 printMultiples(n) # This code is contributed by Mohit Kumar", "e": 3013, "s": 2426, "text": null }, { "code": "// C# program to print multiples of// Unit Digit of Given Numberusing System; class GFG{ // Function to print the multiples // of unit digit static void printMultiples(int n) { // Find the unit digit of // the given number int unit_digit = n % 10; // if the unit digit is 0 then // change it to 10 if (unit_digit == 0) unit_digit = 10; // print the multiples of unit digit // until the multiple is less than // or equal to n for (int i = unit_digit; i <= n; i += unit_digit) Console.Write( i + \" \"); } // Driver Code public static void Main () { int n = 39; printMultiples(n); }} // This code is contributed by Ryuga", "e": 3807, "s": 3013, "text": null }, { "code": "<script> // JavaScript program to print multiples of // Unit Digit of Given Number // Function to print the multiples // of unit digit function printMultiples(n) { // Find the unit digit of // the given number var unit_digit = parseInt(n % 10); // if the unit digit is 0 then // change it to 10 if (unit_digit == 0) unit_digit = 10; // print the multiples of unit digit // until the multiple is less than // or equal to n for (var i = unit_digit; i <= n; i += unit_digit) document.write(i + \" \"); } // Driver Code var n = 39; printMultiples(n); </script>", "e": 4509, "s": 3807, "text": null }, { "code": null, "e": 4520, "s": 4509, "text": "9 18 27 36" }, { "code": null, "e": 4565, "s": 4522, "text": "Time Complexity: O(N)Auxiliary Space: O(1)" }, { "code": null, "e": 4576, "s": 4565, "text": "inderDuMCA" }, { "code": null, "e": 4584, "s": 4576, "text": "ankthon" }, { "code": null, "e": 4599, "s": 4584, "text": "mohit kumar 29" }, { "code": null, "e": 4606, "s": 4599, "text": "rdtank" }, { "code": null, "e": 4618, "s": 4606, "text": "jayanth_mkv" }, { "code": null, "e": 4625, "s": 4618, "text": "factor" }, { "code": null, "e": 4649, "s": 4625, "text": "Technical Scripter 2018" }, { "code": null, "e": 4653, "s": 4649, "text": "C++" }, { "code": null, "e": 4666, "s": 4653, "text": "C++ Programs" }, { "code": null, "e": 4685, "s": 4666, "text": "School Programming" }, { "code": null, "e": 4704, "s": 4685, "text": "Technical Scripter" }, { "code": null, "e": 4708, "s": 4704, "text": "CPP" } ]
Maximum possible time that can be formed from four digits
02 Jul, 2022 Given an array arr[] having 4 integer digits only. The task is to return the maximum 24 hour time that can be formed using the digits from the array. Note that the minimum time in 24 hour format is 00:00, and the maximum is 23:59. If a valid time cannot be formed then return -1.Examples: Input: arr[] = {1, 2, 3, 4} Output: 23:41Input: arr[] = {5, 5, 6, 6} Output: -1 Approach: Create a HashMap and store the frequency of each digit in the map which can be used to know how many of such digits are available. Now, in order to generate a valid time following conditions must be satisfied: First digit of hours must be from the range [0, 2]. Start checking in decreasing order in order to maximize the time i.e. from 2 to 0. Once the digit is chosen, decrement its occurrence in the map by 1. Second digit of hours must be from the range [0, 3] if first digit was chosen as 2 else [0, 9]. Update the HashMap accordingly after choosing the digit. First digit of minutes must be from the range [0, 5] and second digit of minutes must be from the range [0, 9]. If any of the above condition fails i.e. no digit could be chosen at any point then print -1 else print the time.Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the updated frequency map// for the array passed as argumentmap<int, int> getFrequencyMap(int arr[], int n){ map<int, int> hashMap; for (int i = 0; i < n; i++) { hashMap[arr[i]]++; } return hashMap;} // Function that returns true if the passed digit is present// in the map after decrementing it's frequency by 1bool hasDigit(map<int, int>* hashMap, int digit){ // If map contains the digit if ((*hashMap)[digit]) { // Decrement the frequency of the digit by 1 (*hashMap)[digit]--; // True here indicates that the digit was found in the map return true; } // Digit not found return false;} // Function to return the maximum possible time_value in 24-Hours formatstring getMaxtime_value(int arr[], int n){ map<int, int> hashMap = getFrequencyMap(arr, n); int i; bool flag; string time_value = ""; flag = false; // First digit of hours can be from the range [0, 2] for (i = 2; i >= 0; i--) { if (hasDigit(&hashMap, i)) { flag = true; time_value += (char)i + 48; break; } } // If no valid digit found if (!flag) return "-1"; flag = false; // If first digit of hours was chosen as 2 then // the second digit of hours can be // from the range [0, 3] if (time_value[0] == '2') { for (i = 3; i >= 0; i--) { if (hasDigit(&hashMap, i)) { flag = true; time_value += (char)i + 48; break; } } } // Else it can be from the range [0, 9] else { for (i = 9; i >= 0; i--) { if (hasDigit(&hashMap, i)) { flag = true; time_value += (char)i + 48; break; } } } if (!flag) return "-1"; // Hours and minutes separator time_value += ":"; flag = false; // First digit of minutes can be from the range [0, 5] for (i = 5; i >= 0; i--) { if (hasDigit(&hashMap, i)) { flag = true; time_value += (char)i + 48; break; } } if (!flag) return "-1"; flag = false; // Second digit of minutes can be from the range [0, 9] for (i = 9; i >= 0; i--) { if (hasDigit(&hashMap, i)) { flag = true; time_value += (char)i + 48; break; } } if (!flag) return "-1"; // Return the maximum possible time_value return time_value;} // Driver codeint main(){ int arr[] = { 0, 0, 0, 9 }; int n = sizeof(arr) / sizeof(int); cout << (getMaxtime_value(arr, n)); return 0;}// contributed by Arnab Kundu // Java implementation of the approach import java.util.*; public class GFG { // Function to return the updated frequency map // for the array passed as argument static HashMap<Integer, Integer> getFrequencyMap(int arr[]) { HashMap<Integer, Integer> hashMap = new HashMap<>(); for (int i = 0; i < arr.length; i++) { if (hashMap.containsKey(arr[i])) { hashMap.put(arr[i], hashMap.get(arr[i]) + 1); } else { hashMap.put(arr[i], 1); } } return hashMap; } // Function that returns true if the passed digit is present // in the map after decrementing it's frequency by 1 static boolean hasDigit(HashMap<Integer, Integer> hashMap, int digit) { // If map contains the digit if (hashMap.containsKey(digit) && hashMap.get(digit) > 0) { // Decrement the frequency of the digit by 1 hashMap.put(digit, hashMap.get(digit) - 1); // True here indicates that the digit was found in the map return true; } // Digit not found return false; } // Function to return the maximum possible time in 24-Hours format static String getMaxTime(int arr[]) { HashMap<Integer, Integer> hashMap = getFrequencyMap(arr); int i; boolean flag; String time = ""; flag = false; // First digit of hours can be from the range [0, 2] for (i = 2; i >= 0; i--) { if (hasDigit(hashMap, i)) { flag = true; time += i; break; } } // If no valid digit found if (!flag) { return "-1"; } flag = false; // If first digit of hours was chosen as 2 then // the second digit of hours can be // from the range [0, 3] if (time.charAt(0) == '2') { for (i = 3; i >= 0; i--) { if (hasDigit(hashMap, i)) { flag = true; time += i; break; } } } // Else it can be from the range [0, 9] else { for (i = 9; i >= 0; i--) { if (hasDigit(hashMap, i)) { flag = true; time += i; break; } } } if (!flag) { return "-1"; } // Hours and minutes separator time += ":"; flag = false; // First digit of minutes can be from the range [0, 5] for (i = 5; i >= 0; i--) { if (hasDigit(hashMap, i)) { flag = true; time += i; break; } } if (!flag) { return "-1"; } flag = false; // Second digit of minutes can be from the range [0, 9] for (i = 9; i >= 0; i--) { if (hasDigit(hashMap, i)) { flag = true; time += i; break; } } if (!flag) { return "-1"; } // Return the maximum possible time return time; } // Driver code public static void main(String[] args) { int arr[] = { 0, 0, 0, 9 }; System.out.println(getMaxTime(arr)); }} # Python3 implementation of the approachfrom collections import defaultdict # Function to return the updated frequency# map for the array passed as argumentdef getFrequencyMap(arr, n): hashMap = defaultdict(lambda:0) for i in range(n): hashMap[arr[i]] += 1 return hashMap # Function that returns true if the passed# digit is present in the map after# decrementing it's frequency by 1def hasDigit(hashMap, digit): # If map contains the digit if hashMap[digit] > 0: # Decrement the frequency of # the digit by 1 hashMap[digit] -= 1 # True here indicates that the # digit was found in the map return True # Digit not found return False # Function to return the maximum possible# time_value in 24-Hours formatdef getMaxtime_value(arr, n): hashMap = getFrequencyMap(arr, n) flag = False time_value = "" # First digit of hours can be # from the range [0, 2] for i in range(2, -1, -1): if hasDigit(hashMap, i) == True: flag = True time_value += str(i) break # If no valid digit found if not flag: return "-1" flag = False # If first digit of hours was chosen as 2 then # the second digit of hours can be # from the range [0, 3] if(time_value[0] == '2'): for i in range(3, -1, -1): if hasDigit(hashMap, i) == True: flag = True time_value += str(i) break # Else it can be from the range [0, 9] else: for i in range(9, -1, -1): if hasDigit(hashMap, i) == True: flag = True time_value += str(i) break if not flag: return "-1" # Hours and minutes separator time_value += ":" flag = False # First digit of minutes can be # from the range [0, 5] for i in range(5, -1, -1): if hasDigit(hashMap, i) == True: flag = True time_value += str(i) break if not flag: return "-1" flag = False # Second digit of minutes can be # from the range [0, 9] for i in range(9, -1, -1): if hasDigit(hashMap, i) == True: flag = True time_value += str(i) break if not flag: return "-1" # Return the maximum possible # time_value return time_value # Driver codeif __name__ == "__main__": arr = [0, 0, 0, 9] n = len(arr) print(getMaxtime_value(arr, n)) # This code is contributed by# Rituraj Jain // C# implementation of the approachusing System;using System.Collections.Generic; class GFG{ // Function to return the updated frequency map // for the array passed as argument static Dictionary<int, int> getFrequencyMap(int []arr) { Dictionary<int, int> hashMap = new Dictionary<int, int>(); for (int i = 0; i < arr.Length; i++) { if (hashMap.ContainsKey(arr[i])) { hashMap[arr[i]] = hashMap[arr[i]] + 1; } else { hashMap.Add(arr[i], 1); } } return hashMap; } // Function that returns true if the passed digit is present // in the map after decrementing it's frequency by 1 static bool hasDigit(Dictionary<int, int> hashMap, int digit) { // If map contains the digit if (hashMap.ContainsKey(digit) && hashMap[digit] > 0) { // Decrement the frequency of the digit by 1 hashMap[digit] = hashMap[digit] - 1; // True here indicates that the // digit was found in the map return true; } // Digit not found return false; } // Function to return the maximum // possible time in 24-Hours format static String getMaxTime(int []arr) { Dictionary<int, int> hashMap = getFrequencyMap(arr); int i; bool flag; String time = ""; flag = false; // First digit of hours can be from the range [0, 2] for (i = 2; i >= 0; i--) { if (hasDigit(hashMap, i)) { flag = true; time += i; break; } } // If no valid digit found if (!flag) { return "-1"; } flag = false; // If first digit of hours was chosen as 2 then // the second digit of hours can be // from the range [0, 3] if (time[0] == '2') { for (i = 3; i >= 0; i--) { if (hasDigit(hashMap, i)) { flag = true; time += i; break; } } } // Else it can be from the range [0, 9] else { for (i = 9; i >= 0; i--) { if (hasDigit(hashMap, i)) { flag = true; time += i; break; } } } if (!flag) { return "-1"; } // Hours and minutes separator time += ":"; flag = false; // First digit of minutes can be from the range [0, 5] for (i = 5; i >= 0; i--) { if (hasDigit(hashMap, i)) { flag = true; time += i; break; } } if (!flag) { return "-1"; } flag = false; // Second digit of minutes can be from the range [0, 9] for (i = 9; i >= 0; i--) { if (hasDigit(hashMap, i)) { flag = true; time += i; break; } } if (!flag) { return "-1"; } // Return the maximum possible time return time; } // Driver code public static void Main(String[] args) { int []arr = { 0, 0, 0, 9 }; Console.WriteLine(getMaxTime(arr)); }} // This code is contributed by Rajput-Ji <script> // JavaScript implementation of the approach // Function to return the updated frequency map // for the array passed as argument function getFrequencyMap(arr) { var hashMap = {}; for (var i = 0; i < arr.length; i++) { if (hashMap.hasOwnProperty(arr[i])) { hashMap[arr[i]] = hashMap[arr[i]] + 1; } else { hashMap[arr[i]] = 1; } } return hashMap; } // Function that returns true if the passed digit is present // in the map after decrementing it's frequency by 1 function hasDigit(hashMap, digit) { // If map contains the digit if (hashMap.hasOwnProperty(digit) && hashMap[digit] > 0) { // Decrement the frequency of the digit by 1 hashMap[digit] = hashMap[digit] - 1; // True here indicates that the // digit was found in the map return true; } // Digit not found return false; } // Function to return the maximum // possible time in 24-Hours format function getMaxTime(arr) { var hashMap = getFrequencyMap(arr); var i; var flag; var time = ""; flag = false; // First digit of hours can be from the range [0, 2] for (i = 2; i >= 0; i--) { if (hasDigit(hashMap, i)) { flag = true; time += i; break; } } // If no valid digit found if (!flag) { return "-1"; } flag = false; // If first digit of hours was chosen as 2 then // the second digit of hours can be // from the range [0, 3] if (time[0] === "2") { for (i = 3; i >= 0; i--) { if (hasDigit(hashMap, i)) { flag = true; time += i; break; } } } // Else it can be from the range [0, 9] else { for (i = 9; i >= 0; i--) { if (hasDigit(hashMap, i)) { flag = true; time += i; break; } } } if (!flag) { return "-1"; } // Hours and minutes separator time += ":"; flag = false; // First digit of minutes can be from the range [0, 5] for (i = 5; i >= 0; i--) { if (hasDigit(hashMap, i)) { flag = true; time += i; break; } } if (!flag) { return "-1"; } flag = false; // Second digit of minutes can be from the range [0, 9] for (i = 9; i >= 0; i--) { if (hasDigit(hashMap, i)) { flag = true; time += i; break; } } if (!flag) { return "-1"; } // Return the maximum possible time return time; } // Driver code var arr = [0, 0, 0, 9]; document.write(getMaxTime(arr)); </script> 09:00 Time Complexity: O(n), since the loop runs from 0 to (n – 1). Auxiliary Space: O(n), since n extra space has been taken. andrew1234 rituraj_jain Rajput-Ji rdtank samim2000 subham348 Constructive Algorithms Java-HashMap Hash Mathematical Pattern Searching Hash Mathematical Pattern Searching Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. What is Hashing | A Complete Tutorial Longest Consecutive Subsequence Counting frequencies of array elements Sort string of characters Hashing | Set 2 (Separate Chaining) Set in C++ Standard Template Library (STL) Write a program to print all permutations of a given string C++ Data Types Merge two sorted arrays Operators in C / C++
[ { "code": null, "e": 54, "s": 26, "text": "\n02 Jul, 2022" }, { "code": null, "e": 345, "s": 54, "text": "Given an array arr[] having 4 integer digits only. The task is to return the maximum 24 hour time that can be formed using the digits from the array. Note that the minimum time in 24 hour format is 00:00, and the maximum is 23:59. If a valid time cannot be formed then return -1.Examples: " }, { "code": null, "e": 427, "s": 345, "text": "Input: arr[] = {1, 2, 3, 4} Output: 23:41Input: arr[] = {5, 5, 6, 6} Output: -1 " }, { "code": null, "e": 651, "s": 429, "text": "Approach: Create a HashMap and store the frequency of each digit in the map which can be used to know how many of such digits are available. Now, in order to generate a valid time following conditions must be satisfied: " }, { "code": null, "e": 854, "s": 651, "text": "First digit of hours must be from the range [0, 2]. Start checking in decreasing order in order to maximize the time i.e. from 2 to 0. Once the digit is chosen, decrement its occurrence in the map by 1." }, { "code": null, "e": 1007, "s": 854, "text": "Second digit of hours must be from the range [0, 3] if first digit was chosen as 2 else [0, 9]. Update the HashMap accordingly after choosing the digit." }, { "code": null, "e": 1119, "s": 1007, "text": "First digit of minutes must be from the range [0, 5] and second digit of minutes must be from the range [0, 9]." }, { "code": null, "e": 1285, "s": 1119, "text": "If any of the above condition fails i.e. no digit could be chosen at any point then print -1 else print the time.Below is the implementation of the above approach: " }, { "code": null, "e": 1289, "s": 1285, "text": "C++" }, { "code": null, "e": 1294, "s": 1289, "text": "Java" }, { "code": null, "e": 1302, "s": 1294, "text": "Python3" }, { "code": null, "e": 1305, "s": 1302, "text": "C#" }, { "code": null, "e": 1316, "s": 1305, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the updated frequency map// for the array passed as argumentmap<int, int> getFrequencyMap(int arr[], int n){ map<int, int> hashMap; for (int i = 0; i < n; i++) { hashMap[arr[i]]++; } return hashMap;} // Function that returns true if the passed digit is present// in the map after decrementing it's frequency by 1bool hasDigit(map<int, int>* hashMap, int digit){ // If map contains the digit if ((*hashMap)[digit]) { // Decrement the frequency of the digit by 1 (*hashMap)[digit]--; // True here indicates that the digit was found in the map return true; } // Digit not found return false;} // Function to return the maximum possible time_value in 24-Hours formatstring getMaxtime_value(int arr[], int n){ map<int, int> hashMap = getFrequencyMap(arr, n); int i; bool flag; string time_value = \"\"; flag = false; // First digit of hours can be from the range [0, 2] for (i = 2; i >= 0; i--) { if (hasDigit(&hashMap, i)) { flag = true; time_value += (char)i + 48; break; } } // If no valid digit found if (!flag) return \"-1\"; flag = false; // If first digit of hours was chosen as 2 then // the second digit of hours can be // from the range [0, 3] if (time_value[0] == '2') { for (i = 3; i >= 0; i--) { if (hasDigit(&hashMap, i)) { flag = true; time_value += (char)i + 48; break; } } } // Else it can be from the range [0, 9] else { for (i = 9; i >= 0; i--) { if (hasDigit(&hashMap, i)) { flag = true; time_value += (char)i + 48; break; } } } if (!flag) return \"-1\"; // Hours and minutes separator time_value += \":\"; flag = false; // First digit of minutes can be from the range [0, 5] for (i = 5; i >= 0; i--) { if (hasDigit(&hashMap, i)) { flag = true; time_value += (char)i + 48; break; } } if (!flag) return \"-1\"; flag = false; // Second digit of minutes can be from the range [0, 9] for (i = 9; i >= 0; i--) { if (hasDigit(&hashMap, i)) { flag = true; time_value += (char)i + 48; break; } } if (!flag) return \"-1\"; // Return the maximum possible time_value return time_value;} // Driver codeint main(){ int arr[] = { 0, 0, 0, 9 }; int n = sizeof(arr) / sizeof(int); cout << (getMaxtime_value(arr, n)); return 0;}// contributed by Arnab Kundu", "e": 4088, "s": 1316, "text": null }, { "code": "// Java implementation of the approach import java.util.*; public class GFG { // Function to return the updated frequency map // for the array passed as argument static HashMap<Integer, Integer> getFrequencyMap(int arr[]) { HashMap<Integer, Integer> hashMap = new HashMap<>(); for (int i = 0; i < arr.length; i++) { if (hashMap.containsKey(arr[i])) { hashMap.put(arr[i], hashMap.get(arr[i]) + 1); } else { hashMap.put(arr[i], 1); } } return hashMap; } // Function that returns true if the passed digit is present // in the map after decrementing it's frequency by 1 static boolean hasDigit(HashMap<Integer, Integer> hashMap, int digit) { // If map contains the digit if (hashMap.containsKey(digit) && hashMap.get(digit) > 0) { // Decrement the frequency of the digit by 1 hashMap.put(digit, hashMap.get(digit) - 1); // True here indicates that the digit was found in the map return true; } // Digit not found return false; } // Function to return the maximum possible time in 24-Hours format static String getMaxTime(int arr[]) { HashMap<Integer, Integer> hashMap = getFrequencyMap(arr); int i; boolean flag; String time = \"\"; flag = false; // First digit of hours can be from the range [0, 2] for (i = 2; i >= 0; i--) { if (hasDigit(hashMap, i)) { flag = true; time += i; break; } } // If no valid digit found if (!flag) { return \"-1\"; } flag = false; // If first digit of hours was chosen as 2 then // the second digit of hours can be // from the range [0, 3] if (time.charAt(0) == '2') { for (i = 3; i >= 0; i--) { if (hasDigit(hashMap, i)) { flag = true; time += i; break; } } } // Else it can be from the range [0, 9] else { for (i = 9; i >= 0; i--) { if (hasDigit(hashMap, i)) { flag = true; time += i; break; } } } if (!flag) { return \"-1\"; } // Hours and minutes separator time += \":\"; flag = false; // First digit of minutes can be from the range [0, 5] for (i = 5; i >= 0; i--) { if (hasDigit(hashMap, i)) { flag = true; time += i; break; } } if (!flag) { return \"-1\"; } flag = false; // Second digit of minutes can be from the range [0, 9] for (i = 9; i >= 0; i--) { if (hasDigit(hashMap, i)) { flag = true; time += i; break; } } if (!flag) { return \"-1\"; } // Return the maximum possible time return time; } // Driver code public static void main(String[] args) { int arr[] = { 0, 0, 0, 9 }; System.out.println(getMaxTime(arr)); }}", "e": 7430, "s": 4088, "text": null }, { "code": "# Python3 implementation of the approachfrom collections import defaultdict # Function to return the updated frequency# map for the array passed as argumentdef getFrequencyMap(arr, n): hashMap = defaultdict(lambda:0) for i in range(n): hashMap[arr[i]] += 1 return hashMap # Function that returns true if the passed# digit is present in the map after# decrementing it's frequency by 1def hasDigit(hashMap, digit): # If map contains the digit if hashMap[digit] > 0: # Decrement the frequency of # the digit by 1 hashMap[digit] -= 1 # True here indicates that the # digit was found in the map return True # Digit not found return False # Function to return the maximum possible# time_value in 24-Hours formatdef getMaxtime_value(arr, n): hashMap = getFrequencyMap(arr, n) flag = False time_value = \"\" # First digit of hours can be # from the range [0, 2] for i in range(2, -1, -1): if hasDigit(hashMap, i) == True: flag = True time_value += str(i) break # If no valid digit found if not flag: return \"-1\" flag = False # If first digit of hours was chosen as 2 then # the second digit of hours can be # from the range [0, 3] if(time_value[0] == '2'): for i in range(3, -1, -1): if hasDigit(hashMap, i) == True: flag = True time_value += str(i) break # Else it can be from the range [0, 9] else: for i in range(9, -1, -1): if hasDigit(hashMap, i) == True: flag = True time_value += str(i) break if not flag: return \"-1\" # Hours and minutes separator time_value += \":\" flag = False # First digit of minutes can be # from the range [0, 5] for i in range(5, -1, -1): if hasDigit(hashMap, i) == True: flag = True time_value += str(i) break if not flag: return \"-1\" flag = False # Second digit of minutes can be # from the range [0, 9] for i in range(9, -1, -1): if hasDigit(hashMap, i) == True: flag = True time_value += str(i) break if not flag: return \"-1\" # Return the maximum possible # time_value return time_value # Driver codeif __name__ == \"__main__\": arr = [0, 0, 0, 9] n = len(arr) print(getMaxtime_value(arr, n)) # This code is contributed by# Rituraj Jain", "e": 10081, "s": 7430, "text": null }, { "code": "// C# implementation of the approachusing System;using System.Collections.Generic; class GFG{ // Function to return the updated frequency map // for the array passed as argument static Dictionary<int, int> getFrequencyMap(int []arr) { Dictionary<int, int> hashMap = new Dictionary<int, int>(); for (int i = 0; i < arr.Length; i++) { if (hashMap.ContainsKey(arr[i])) { hashMap[arr[i]] = hashMap[arr[i]] + 1; } else { hashMap.Add(arr[i], 1); } } return hashMap; } // Function that returns true if the passed digit is present // in the map after decrementing it's frequency by 1 static bool hasDigit(Dictionary<int, int> hashMap, int digit) { // If map contains the digit if (hashMap.ContainsKey(digit) && hashMap[digit] > 0) { // Decrement the frequency of the digit by 1 hashMap[digit] = hashMap[digit] - 1; // True here indicates that the // digit was found in the map return true; } // Digit not found return false; } // Function to return the maximum // possible time in 24-Hours format static String getMaxTime(int []arr) { Dictionary<int, int> hashMap = getFrequencyMap(arr); int i; bool flag; String time = \"\"; flag = false; // First digit of hours can be from the range [0, 2] for (i = 2; i >= 0; i--) { if (hasDigit(hashMap, i)) { flag = true; time += i; break; } } // If no valid digit found if (!flag) { return \"-1\"; } flag = false; // If first digit of hours was chosen as 2 then // the second digit of hours can be // from the range [0, 3] if (time[0] == '2') { for (i = 3; i >= 0; i--) { if (hasDigit(hashMap, i)) { flag = true; time += i; break; } } } // Else it can be from the range [0, 9] else { for (i = 9; i >= 0; i--) { if (hasDigit(hashMap, i)) { flag = true; time += i; break; } } } if (!flag) { return \"-1\"; } // Hours and minutes separator time += \":\"; flag = false; // First digit of minutes can be from the range [0, 5] for (i = 5; i >= 0; i--) { if (hasDigit(hashMap, i)) { flag = true; time += i; break; } } if (!flag) { return \"-1\"; } flag = false; // Second digit of minutes can be from the range [0, 9] for (i = 9; i >= 0; i--) { if (hasDigit(hashMap, i)) { flag = true; time += i; break; } } if (!flag) { return \"-1\"; } // Return the maximum possible time return time; } // Driver code public static void Main(String[] args) { int []arr = { 0, 0, 0, 9 }; Console.WriteLine(getMaxTime(arr)); }} // This code is contributed by Rajput-Ji", "e": 13643, "s": 10081, "text": null }, { "code": "<script> // JavaScript implementation of the approach // Function to return the updated frequency map // for the array passed as argument function getFrequencyMap(arr) { var hashMap = {}; for (var i = 0; i < arr.length; i++) { if (hashMap.hasOwnProperty(arr[i])) { hashMap[arr[i]] = hashMap[arr[i]] + 1; } else { hashMap[arr[i]] = 1; } } return hashMap; } // Function that returns true if the passed digit is present // in the map after decrementing it's frequency by 1 function hasDigit(hashMap, digit) { // If map contains the digit if (hashMap.hasOwnProperty(digit) && hashMap[digit] > 0) { // Decrement the frequency of the digit by 1 hashMap[digit] = hashMap[digit] - 1; // True here indicates that the // digit was found in the map return true; } // Digit not found return false; } // Function to return the maximum // possible time in 24-Hours format function getMaxTime(arr) { var hashMap = getFrequencyMap(arr); var i; var flag; var time = \"\"; flag = false; // First digit of hours can be from the range [0, 2] for (i = 2; i >= 0; i--) { if (hasDigit(hashMap, i)) { flag = true; time += i; break; } } // If no valid digit found if (!flag) { return \"-1\"; } flag = false; // If first digit of hours was chosen as 2 then // the second digit of hours can be // from the range [0, 3] if (time[0] === \"2\") { for (i = 3; i >= 0; i--) { if (hasDigit(hashMap, i)) { flag = true; time += i; break; } } } // Else it can be from the range [0, 9] else { for (i = 9; i >= 0; i--) { if (hasDigit(hashMap, i)) { flag = true; time += i; break; } } } if (!flag) { return \"-1\"; } // Hours and minutes separator time += \":\"; flag = false; // First digit of minutes can be from the range [0, 5] for (i = 5; i >= 0; i--) { if (hasDigit(hashMap, i)) { flag = true; time += i; break; } } if (!flag) { return \"-1\"; } flag = false; // Second digit of minutes can be from the range [0, 9] for (i = 9; i >= 0; i--) { if (hasDigit(hashMap, i)) { flag = true; time += i; break; } } if (!flag) { return \"-1\"; } // Return the maximum possible time return time; } // Driver code var arr = [0, 0, 0, 9]; document.write(getMaxTime(arr)); </script>", "e": 16647, "s": 13643, "text": null }, { "code": null, "e": 16653, "s": 16647, "text": "09:00" }, { "code": null, "e": 16718, "s": 16655, "text": "Time Complexity: O(n), since the loop runs from 0 to (n – 1). " }, { "code": null, "e": 16777, "s": 16718, "text": "Auxiliary Space: O(n), since n extra space has been taken." }, { "code": null, "e": 16788, "s": 16777, "text": "andrew1234" }, { "code": null, "e": 16801, "s": 16788, "text": "rituraj_jain" }, { "code": null, "e": 16811, "s": 16801, "text": "Rajput-Ji" }, { "code": null, "e": 16818, "s": 16811, "text": "rdtank" }, { "code": null, "e": 16828, "s": 16818, "text": "samim2000" }, { "code": null, "e": 16838, "s": 16828, "text": "subham348" }, { "code": null, "e": 16862, "s": 16838, "text": "Constructive Algorithms" }, { "code": null, "e": 16875, "s": 16862, "text": "Java-HashMap" }, { "code": null, "e": 16880, "s": 16875, "text": "Hash" }, { "code": null, "e": 16893, "s": 16880, "text": "Mathematical" }, { "code": null, "e": 16911, "s": 16893, "text": "Pattern Searching" }, { "code": null, "e": 16916, "s": 16911, "text": "Hash" }, { "code": null, "e": 16929, "s": 16916, "text": "Mathematical" }, { "code": null, "e": 16947, "s": 16929, "text": "Pattern Searching" }, { "code": null, "e": 17045, "s": 16947, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 17083, "s": 17045, "text": "What is Hashing | A Complete Tutorial" }, { "code": null, "e": 17115, "s": 17083, "text": "Longest Consecutive Subsequence" }, { "code": null, "e": 17154, "s": 17115, "text": "Counting frequencies of array elements" }, { "code": null, "e": 17180, "s": 17154, "text": "Sort string of characters" }, { "code": null, "e": 17216, "s": 17180, "text": "Hashing | Set 2 (Separate Chaining)" }, { "code": null, "e": 17259, "s": 17216, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 17319, "s": 17259, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 17334, "s": 17319, "text": "C++ Data Types" }, { "code": null, "e": 17358, "s": 17334, "text": "Merge two sorted arrays" } ]
Path subpath() method in Java with Examples
20 Jun, 2022 The subpath(int beginIndex, int endIndex) method of java.nio.file.Path used to return a relative Path that is a subsequence of the name elements of this path. We will pass begin and end indexes to construct a subpath. The beginIndex and endIndex parameters specify the subsequence of name elements. The name element closest to the root in the directory hierarchy is index 0 and name element that is farthest from the root has index count-1. The returned subpath object has the name elements that begin at beginIndex and extend to the element at index endIndex-1. Syntax: Path subpath(int beginIndex, int endIndex) Parameters: This method accepts a two parameters: beginIndex which is the index of the first element, inclusive and endIndex which is the index of the last element, exclusive. Return value: This method returns a new Path object that is a subsequence of the name elements in this Path. Exception: This method throws IllegalArgumentException if beginIndex is negative, or greater than or equal to the number of elements. If endIndex is less than or equal to beginIndex, or larger than the number of elements. Below programs illustrate subpath() method: Program 1: Java // Java program to demonstrate// java.nio.file.Path.subpath() method import java.nio.file.Path;import java.nio.file.Paths;public class GFG { public static void main(String[] args) { // create an object of Path Path path = Paths.get("D:\\eclipse\\p2" + "\\org\\eclipse\\equinox\\p2\\core" + "\\cache\\binary"); // call subPath() to create a subPath which // begin at index 1 and ends at index 5 Path subPath = path.subpath(1, 5); // print result System.out.println("Subpath: " + subPath); }} Program 2: Java // Java program to demonstrate// java.nio.file.Path.subpath() method import java.nio.file.Path;import java.nio.file.Paths;public class GFG { public static void main(String[] args) { // create an object of Path Path path = Paths.get("D:\\Workspace" + "\\nEclipseWork" + "\\GFG\\bin\\defaultpackage"); System.out.println("Original Path:" + path); // call subPath() to create a subPath which // begin at index 0 and ends at index 2 Path subPath = path.subpath(0, 2); // print result System.out.println("Subpath: " + subPath); }} References: https://docs.oracle.com/javase/10/docs/api/java/nio/file/Path.html#subpath(int, int) simmytarika5 Java-Functions Java-Path java.nio.file package 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": 28, "s": 0, "text": "\n20 Jun, 2022" }, { "code": null, "e": 592, "s": 28, "text": "The subpath(int beginIndex, int endIndex) method of java.nio.file.Path used to return a relative Path that is a subsequence of the name elements of this path. We will pass begin and end indexes to construct a subpath. The beginIndex and endIndex parameters specify the subsequence of name elements. The name element closest to the root in the directory hierarchy is index 0 and name element that is farthest from the root has index count-1. The returned subpath object has the name elements that begin at beginIndex and extend to the element at index endIndex-1. " }, { "code": null, "e": 600, "s": 592, "text": "Syntax:" }, { "code": null, "e": 656, "s": 600, "text": "Path subpath(int beginIndex,\n int endIndex)" }, { "code": null, "e": 706, "s": 656, "text": "Parameters: This method accepts a two parameters:" }, { "code": null, "e": 772, "s": 706, "text": "beginIndex which is the index of the first element, inclusive and" }, { "code": null, "e": 832, "s": 772, "text": "endIndex which is the index of the last element, exclusive." }, { "code": null, "e": 942, "s": 832, "text": "Return value: This method returns a new Path object that is a subsequence of the name elements in this Path. " }, { "code": null, "e": 1165, "s": 942, "text": "Exception: This method throws IllegalArgumentException if beginIndex is negative, or greater than or equal to the number of elements. If endIndex is less than or equal to beginIndex, or larger than the number of elements. " }, { "code": null, "e": 1210, "s": 1165, "text": "Below programs illustrate subpath() method: " }, { "code": null, "e": 1222, "s": 1210, "text": "Program 1: " }, { "code": null, "e": 1227, "s": 1222, "text": "Java" }, { "code": "// Java program to demonstrate// java.nio.file.Path.subpath() method import java.nio.file.Path;import java.nio.file.Paths;public class GFG { public static void main(String[] args) { // create an object of Path Path path = Paths.get(\"D:\\\\eclipse\\\\p2\" + \"\\\\org\\\\eclipse\\\\equinox\\\\p2\\\\core\" + \"\\\\cache\\\\binary\"); // call subPath() to create a subPath which // begin at index 1 and ends at index 5 Path subPath = path.subpath(1, 5); // print result System.out.println(\"Subpath: \" + subPath); }}", "e": 1862, "s": 1227, "text": null }, { "code": null, "e": 1874, "s": 1862, "text": "Program 2: " }, { "code": null, "e": 1879, "s": 1874, "text": "Java" }, { "code": "// Java program to demonstrate// java.nio.file.Path.subpath() method import java.nio.file.Path;import java.nio.file.Paths;public class GFG { public static void main(String[] args) { // create an object of Path Path path = Paths.get(\"D:\\\\Workspace\" + \"\\\\nEclipseWork\" + \"\\\\GFG\\\\bin\\\\defaultpackage\"); System.out.println(\"Original Path:\" + path); // call subPath() to create a subPath which // begin at index 0 and ends at index 2 Path subPath = path.subpath(0, 2); // print result System.out.println(\"Subpath: \" + subPath); }}", "e": 2583, "s": 1879, "text": null }, { "code": null, "e": 2680, "s": 2583, "text": "References: https://docs.oracle.com/javase/10/docs/api/java/nio/file/Path.html#subpath(int, int)" }, { "code": null, "e": 2693, "s": 2680, "text": "simmytarika5" }, { "code": null, "e": 2708, "s": 2693, "text": "Java-Functions" }, { "code": null, "e": 2718, "s": 2708, "text": "Java-Path" }, { "code": null, "e": 2740, "s": 2718, "text": "java.nio.file package" }, { "code": null, "e": 2745, "s": 2740, "text": "Java" }, { "code": null, "e": 2750, "s": 2745, "text": "Java" }, { "code": null, "e": 2848, "s": 2750, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2863, "s": 2848, "text": "Stream In Java" }, { "code": null, "e": 2884, "s": 2863, "text": "Introduction to Java" }, { "code": null, "e": 2905, "s": 2884, "text": "Constructors in Java" }, { "code": null, "e": 2924, "s": 2905, "text": "Exceptions in Java" }, { "code": null, "e": 2941, "s": 2924, "text": "Generics in Java" }, { "code": null, "e": 2971, "s": 2941, "text": "Functional Interfaces in Java" }, { "code": null, "e": 2997, "s": 2971, "text": "Java Programming Examples" }, { "code": null, "e": 3013, "s": 2997, "text": "Strings in Java" }, { "code": null, "e": 3050, "s": 3013, "text": "Differences between JDK, JRE and JVM" } ]
How to use map() on an array in reverse order with JavaScript ?
31 Dec, 2019 Given a JavaScript array and the task is to apply the map() method but on the reverse of the array efficiently. Here are a few approaches discussed. If you don’t want to change the original array then you can create a shallow copy of the array after that you can perform the task. Approach 1: The idea is to use .reverse() method just after applying .slice() method. Then use the .map() method on the reversed array to perform the task. Example: This example implements the above approach.<!DOCTYPE HTML><html> <head> <title> How to use map() on an array in reverse order with JavaScript ? </title> <style> body { text-align: center; } h1 { color: green; } #geeks { font-weight: bold; } </style></head> <body> <h1>GeeksforGeeks</h1> <p> Click on the button to use <b>map()</b> on array in <b>reverse</b> order<br> Array = [1, 3, 5, 7, 9, 10]; </p> <button onclick="gfg_Run()"> Click Here </button> <p id="geeks"></p> <script> var el_down = document.getElementById("geeks"); var arr = [1, 3, 5, 7, 9, 10]; /* Main function */ function gfg_Run() { newArr = arr.slice(0).reverse().map( function(val, index) { return val * 2; } ); el_down.innerHTML = "New Array = [" + newArr + "]"; } </script></body> </html> <!DOCTYPE HTML><html> <head> <title> How to use map() on an array in reverse order with JavaScript ? </title> <style> body { text-align: center; } h1 { color: green; } #geeks { font-weight: bold; } </style></head> <body> <h1>GeeksforGeeks</h1> <p> Click on the button to use <b>map()</b> on array in <b>reverse</b> order<br> Array = [1, 3, 5, 7, 9, 10]; </p> <button onclick="gfg_Run()"> Click Here </button> <p id="geeks"></p> <script> var el_down = document.getElementById("geeks"); var arr = [1, 3, 5, 7, 9, 10]; /* Main function */ function gfg_Run() { newArr = arr.slice(0).reverse().map( function(val, index) { return val * 2; } ); el_down.innerHTML = "New Array = [" + newArr + "]"; } </script></body> </html> Output: Approach 2: In this approach we will use the .map() method and call a function inside this method with 2 arguments (value, index). Now we need to access the value, we will access it from reverse side (eg.. arr[arr.length – 1 – index]), this is immutable operation (It doesn’t change the original array). Example: This example implements the above approach.<!DOCTYPE HTML><html> <head> <title> How to use map() on an array in reverse order with JavaScript ? </title> <style> body { text-align: center; } h1 { color: green; } #geeks { font-weight: bold; } </style></head> <body> <h1>GeeksforGeeks</h1> <p> Click on the button to use <b>map()</b> on array in <b>reverse</b> order<br> Array = [8, 5, 15, 70, 9, 10]; </p> <button onclick="gfg_Run()"> Click Here </button> <p id="geeks"></p> <script> var el_down = document.getElementById("geeks"); var arr = [8, 5, 15, 70, 9, 10]; /* Main function */ function gfg_Run() { newArr = arr.map((val, index, array) => 1/2*arr[arr.length - 1 - index]); el_down.innerHTML = "New Array = [" + newArr + "]"; } </script></body> </html> <!DOCTYPE HTML><html> <head> <title> How to use map() on an array in reverse order with JavaScript ? </title> <style> body { text-align: center; } h1 { color: green; } #geeks { font-weight: bold; } </style></head> <body> <h1>GeeksforGeeks</h1> <p> Click on the button to use <b>map()</b> on array in <b>reverse</b> order<br> Array = [8, 5, 15, 70, 9, 10]; </p> <button onclick="gfg_Run()"> Click Here </button> <p id="geeks"></p> <script> var el_down = document.getElementById("geeks"); var arr = [8, 5, 15, 70, 9, 10]; /* Main function */ function gfg_Run() { newArr = arr.map((val, index, array) => 1/2*arr[arr.length - 1 - index]); el_down.innerHTML = "New Array = [" + newArr + "]"; } </script></body> </html> Output: javascript-array JavaScript-Misc 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 Remove elements from a JavaScript Array Roadmap to Learn JavaScript For Beginners Difference Between PUT and PATCH Request JavaScript | Promises Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n31 Dec, 2019" }, { "code": null, "e": 309, "s": 28, "text": "Given a JavaScript array and the task is to apply the map() method but on the reverse of the array efficiently. Here are a few approaches discussed. If you don’t want to change the original array then you can create a shallow copy of the array after that you can perform the task." }, { "code": null, "e": 465, "s": 309, "text": "Approach 1: The idea is to use .reverse() method just after applying .slice() method. Then use the .map() method on the reversed array to perform the task." }, { "code": null, "e": 1588, "s": 465, "text": "Example: This example implements the above approach.<!DOCTYPE HTML><html> <head> <title> How to use map() on an array in reverse order with JavaScript ? </title> <style> body { text-align: center; } h1 { color: green; } #geeks { font-weight: bold; } </style></head> <body> <h1>GeeksforGeeks</h1> <p> Click on the button to use <b>map()</b> on array in <b>reverse</b> order<br> Array = [1, 3, 5, 7, 9, 10]; </p> <button onclick=\"gfg_Run()\"> Click Here </button> <p id=\"geeks\"></p> <script> var el_down = document.getElementById(\"geeks\"); var arr = [1, 3, 5, 7, 9, 10]; /* Main function */ function gfg_Run() { newArr = arr.slice(0).reverse().map( function(val, index) { return val * 2; } ); el_down.innerHTML = \"New Array = [\" + newArr + \"]\"; } </script></body> </html>" }, { "code": "<!DOCTYPE HTML><html> <head> <title> How to use map() on an array in reverse order with JavaScript ? </title> <style> body { text-align: center; } h1 { color: green; } #geeks { font-weight: bold; } </style></head> <body> <h1>GeeksforGeeks</h1> <p> Click on the button to use <b>map()</b> on array in <b>reverse</b> order<br> Array = [1, 3, 5, 7, 9, 10]; </p> <button onclick=\"gfg_Run()\"> Click Here </button> <p id=\"geeks\"></p> <script> var el_down = document.getElementById(\"geeks\"); var arr = [1, 3, 5, 7, 9, 10]; /* Main function */ function gfg_Run() { newArr = arr.slice(0).reverse().map( function(val, index) { return val * 2; } ); el_down.innerHTML = \"New Array = [\" + newArr + \"]\"; } </script></body> </html>", "e": 2659, "s": 1588, "text": null }, { "code": null, "e": 2667, "s": 2659, "text": "Output:" }, { "code": null, "e": 2971, "s": 2667, "text": "Approach 2: In this approach we will use the .map() method and call a function inside this method with 2 arguments (value, index). Now we need to access the value, we will access it from reverse side (eg.. arr[arr.length – 1 – index]), this is immutable operation (It doesn’t change the original array)." }, { "code": null, "e": 4064, "s": 2971, "text": "Example: This example implements the above approach.<!DOCTYPE HTML><html> <head> <title> How to use map() on an array in reverse order with JavaScript ? </title> <style> body { text-align: center; } h1 { color: green; } #geeks { font-weight: bold; } </style></head> <body> <h1>GeeksforGeeks</h1> <p> Click on the button to use <b>map()</b> on array in <b>reverse</b> order<br> Array = [8, 5, 15, 70, 9, 10]; </p> <button onclick=\"gfg_Run()\"> Click Here </button> <p id=\"geeks\"></p> <script> var el_down = document.getElementById(\"geeks\"); var arr = [8, 5, 15, 70, 9, 10]; /* Main function */ function gfg_Run() { newArr = arr.map((val, index, array) => 1/2*arr[arr.length - 1 - index]); el_down.innerHTML = \"New Array = [\" + newArr + \"]\"; } </script></body> </html>" }, { "code": "<!DOCTYPE HTML><html> <head> <title> How to use map() on an array in reverse order with JavaScript ? </title> <style> body { text-align: center; } h1 { color: green; } #geeks { font-weight: bold; } </style></head> <body> <h1>GeeksforGeeks</h1> <p> Click on the button to use <b>map()</b> on array in <b>reverse</b> order<br> Array = [8, 5, 15, 70, 9, 10]; </p> <button onclick=\"gfg_Run()\"> Click Here </button> <p id=\"geeks\"></p> <script> var el_down = document.getElementById(\"geeks\"); var arr = [8, 5, 15, 70, 9, 10]; /* Main function */ function gfg_Run() { newArr = arr.map((val, index, array) => 1/2*arr[arr.length - 1 - index]); el_down.innerHTML = \"New Array = [\" + newArr + \"]\"; } </script></body> </html>", "e": 5105, "s": 4064, "text": null }, { "code": null, "e": 5113, "s": 5105, "text": "Output:" }, { "code": null, "e": 5130, "s": 5113, "text": "javascript-array" }, { "code": null, "e": 5146, "s": 5130, "text": "JavaScript-Misc" }, { "code": null, "e": 5157, "s": 5146, "text": "JavaScript" }, { "code": null, "e": 5174, "s": 5157, "text": "Web Technologies" }, { "code": null, "e": 5201, "s": 5174, "text": "Web technologies Questions" }, { "code": null, "e": 5299, "s": 5201, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5360, "s": 5299, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 5400, "s": 5360, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 5442, "s": 5400, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 5483, "s": 5442, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 5505, "s": 5483, "text": "JavaScript | Promises" }, { "code": null, "e": 5538, "s": 5505, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 5600, "s": 5538, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 5661, "s": 5600, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 5711, "s": 5661, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Python – Remove index ranges from String
02 Sep, 2020 Given a string and ranges list, remove all the characters that occur in ranges. Input : test_str = ‘geeksforgeeks is best for geeks’, range_list = [(3, 6), (7, 10)]Output : geeks is best for geeksExplanation : The required ranges removed. Input : test_str = ‘geeksforgeeks is best for geeks’, range_list = [(3, 6)]Output : georgeeks is best for geeksExplanation : The required ranges removed. Method #1 : Using loop In this, we check for each range, remake string, considering the index doesn’t lie in range checking using conditional statements. Python3 # Python3 code to demonstrate working of # Remove index ranges from String # Using loop # initializing stringstest_str1 = 'geeksforgeeks is best for geeks' # printing original stringprint("The original string 1 is : " + str(test_str1)) # initializing ranges list range_list = [(3, 6), (7, 10), (14, 17)] res = "" for idx, chr in enumerate(test_str1): for strt_idx, end_idx in range_list: # checking for ranges and appending if strt_idx <= idx + 1 <= end_idx: break else: res += chr # printing result print("The reconstructed string : " + str(res)) The original string 1 is : geeksforgeeks is best for geeks The reconstructed string : geeksbest for geeks Method #2 : Using any() + list comprehension + join() In this, we perform task of checking for indices for strings using any() and list comprehension is used to reconstruct string accordingly. Python3 # Python3 code to demonstrate working of # Remove index ranges from String # Using any() + list comprehension + join() # initializing stringstest_str1 = 'geeksforgeeks is best for geeks' # printing original stringprint("The original string 1 is : " + str(test_str1)) # initializing ranges list range_list = [(3, 6), (7, 10), (14, 17)] # using any() to check for strings in index rangesres = ''.join(chr for idx, chr in enumerate(test_str1, 1) if not any(strt_idx <= idx <= end_idx for strt_idx, end_idx in range_list)) # printing result print("The reconstructed string : " + str(res)) The original string 1 is : geeksforgeeks is best for geeks The reconstructed string : geeksbest for geeks Python string-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python Program for Fibonacci numbers Python | Convert string dictionary to dictionary
[ { "code": null, "e": 28, "s": 0, "text": "\n02 Sep, 2020" }, { "code": null, "e": 109, "s": 28, "text": "Given a string and ranges list, remove all the characters that occur in ranges. " }, { "code": null, "e": 268, "s": 109, "text": "Input : test_str = ‘geeksforgeeks is best for geeks’, range_list = [(3, 6), (7, 10)]Output : geeks is best for geeksExplanation : The required ranges removed." }, { "code": null, "e": 422, "s": 268, "text": "Input : test_str = ‘geeksforgeeks is best for geeks’, range_list = [(3, 6)]Output : georgeeks is best for geeksExplanation : The required ranges removed." }, { "code": null, "e": 445, "s": 422, "text": "Method #1 : Using loop" }, { "code": null, "e": 576, "s": 445, "text": "In this, we check for each range, remake string, considering the index doesn’t lie in range checking using conditional statements." }, { "code": null, "e": 584, "s": 576, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of # Remove index ranges from String # Using loop # initializing stringstest_str1 = 'geeksforgeeks is best for geeks' # printing original stringprint(\"The original string 1 is : \" + str(test_str1)) # initializing ranges list range_list = [(3, 6), (7, 10), (14, 17)] res = \"\" for idx, chr in enumerate(test_str1): for strt_idx, end_idx in range_list: # checking for ranges and appending if strt_idx <= idx + 1 <= end_idx: break else: res += chr # printing result print(\"The reconstructed string : \" + str(res)) ", "e": 1165, "s": 584, "text": null }, { "code": null, "e": 1272, "s": 1165, "text": "The original string 1 is : geeksforgeeks is best for geeks\nThe reconstructed string : geeksbest for geeks\n" }, { "code": null, "e": 1326, "s": 1272, "text": "Method #2 : Using any() + list comprehension + join()" }, { "code": null, "e": 1466, "s": 1326, "text": "In this, we perform task of checking for indices for strings using any() and list comprehension is used to reconstruct string accordingly. " }, { "code": null, "e": 1474, "s": 1466, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of # Remove index ranges from String # Using any() + list comprehension + join() # initializing stringstest_str1 = 'geeksforgeeks is best for geeks' # printing original stringprint(\"The original string 1 is : \" + str(test_str1)) # initializing ranges list range_list = [(3, 6), (7, 10), (14, 17)] # using any() to check for strings in index rangesres = ''.join(chr for idx, chr in enumerate(test_str1, 1) if not any(strt_idx <= idx <= end_idx for strt_idx, end_idx in range_list)) # printing result print(\"The reconstructed string : \" + str(res)) ", "e": 2074, "s": 1474, "text": null }, { "code": null, "e": 2181, "s": 2074, "text": "The original string 1 is : geeksforgeeks is best for geeks\nThe reconstructed string : geeksbest for geeks\n" }, { "code": null, "e": 2204, "s": 2181, "text": "Python string-programs" }, { "code": null, "e": 2211, "s": 2204, "text": "Python" }, { "code": null, "e": 2227, "s": 2211, "text": "Python Programs" }, { "code": null, "e": 2325, "s": 2227, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2357, "s": 2325, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2384, "s": 2357, "text": "Python Classes and Objects" }, { "code": null, "e": 2405, "s": 2384, "text": "Python OOPs Concepts" }, { "code": null, "e": 2428, "s": 2405, "text": "Introduction To PYTHON" }, { "code": null, "e": 2484, "s": 2428, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2506, "s": 2484, "text": "Defaultdict in Python" }, { "code": null, "e": 2545, "s": 2506, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 2583, "s": 2545, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 2620, "s": 2583, "text": "Python Program for Fibonacci numbers" } ]
Test Execution Results in XML Format
We can generate the details of the test execution in an xml file. This xml file is mainly useful in cases where we have a dashboard that projects the test results. In such cases, the xml can be parsed to get the details of the execution. We will now execute the tests from test_multiplcation.py and generate the xml by running pytest test_multiplication.py -v --junitxml="result.xml" Now we can see result.xml is generated with the following data − <?xml version = "1.0" encoding = "utf-8"?> <testsuite errors = "0" failures = "1" name = "pytest" skips = "0" tests = "4" time = "0.061"> <testcase classname = "test_multiplication" file = "test_multiplication.py" line = "2" name = "test_multiplication_11[1-11]" time = "0.00117516517639> </testcase> <testcase classname = "test_multiplication" file = "test_multiplication.py" line = "2" name = "test_multiplication_11[2-22]" time = "0.00155973434448"> </testcase> <testcase classname = "test_multiplication" file = "test_multiplication.py" line = "2" name = "test_multiplication_11[3-35]" time = "0.00144290924072"> failure message = "assert (11 * 3) == 35">num = 3, output = 35 @pytest.mark.parametrize("num, output",[(1,11),(2,22),(3,35),(4,44)]) def test_multiplication_11(num, output):> assert 11*num == output E assert (11 * 3) == 35 test_multiplication.py:5: AssertionErro </failure> </testcase> <testcase classname = "test_multiplication" file = "test_multiplication.py" line = "2" name = "test_multiplication_11[4-44]" time = "0.000945091247559"> </testcase> </testsuite> Here, the tag <testsuit> summarises there were 4 tests and the number of failures are 1. The tag <testcase> gives the details of each executed test. The tag <testcase> gives the details of each executed test. <failure> tag gives the details of the failed test code. <failure> tag gives the details of the failed test code. 21 Lectures 4 hours Lucian Musat 22 Lectures 1.5 hours Fanuel Mapuwei 44 Lectures 3.5 hours Rohit Dharaviya Print Add Notes Bookmark this page
[ { "code": null, "e": 2280, "s": 2042, "text": "We can generate the details of the test execution in an xml file. This xml file is mainly useful in cases where we have a dashboard that projects the test results. In such cases, the xml can be parsed to get the details of the execution." }, { "code": null, "e": 2369, "s": 2280, "text": "We will now execute the tests from test_multiplcation.py and generate the xml by running" }, { "code": null, "e": 2426, "s": 2369, "text": "pytest test_multiplication.py -v --junitxml=\"result.xml\"" }, { "code": null, "e": 2491, "s": 2426, "text": "Now we can see result.xml is generated with the following data −" }, { "code": null, "e": 3766, "s": 2491, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<testsuite errors = \"0\" failures = \"1\"\nname = \"pytest\" skips = \"0\" tests = \"4\" time = \"0.061\">\n <testcase classname = \"test_multiplication\" \n file = \"test_multiplication.py\"\n line = \"2\" name = \"test_multiplication_11[1-11]\"\n time = \"0.00117516517639>\n </testcase>\n \n <testcase classname = \"test_multiplication\" \n file = \"test_multiplication.py\"\n line = \"2\" name = \"test_multiplication_11[2-22]\"\n time = \"0.00155973434448\">\n </testcase>\n\n <testcase classname = \"test_multiplication\" \n file = \"test_multiplication.py\"\n line = \"2\" name = \"test_multiplication_11[3-35]\" time = \"0.00144290924072\">\n failure message = \"assert (11 * 3) == 35\">num = 3, output = 35\n\n @pytest.mark.parametrize(\"num,\n output\",[(1,11),(2,22),(3,35),(4,44)])\n \n def test_multiplication_11(num, output):> \n assert 11*num == output\n E assert (11 * 3) == 35\n\n test_multiplication.py:5: AssertionErro\n </failure>\n </testcase>\n <testcase classname = \"test_multiplication\" \n file = \"test_multiplication.py\"\n line = \"2\" name = \"test_multiplication_11[4-44]\"\n time = \"0.000945091247559\">\n </testcase>\n</testsuite>\n" }, { "code": null, "e": 3855, "s": 3766, "text": "Here, the tag <testsuit> summarises there were 4 tests and the number of failures are\n1." }, { "code": null, "e": 3915, "s": 3855, "text": "The tag <testcase> gives the details of each executed test." }, { "code": null, "e": 3975, "s": 3915, "text": "The tag <testcase> gives the details of each executed test." }, { "code": null, "e": 4032, "s": 3975, "text": "<failure> tag gives the details of the failed test code." }, { "code": null, "e": 4089, "s": 4032, "text": "<failure> tag gives the details of the failed test code." }, { "code": null, "e": 4122, "s": 4089, "text": "\n 21 Lectures \n 4 hours \n" }, { "code": null, "e": 4136, "s": 4122, "text": " Lucian Musat" }, { "code": null, "e": 4171, "s": 4136, "text": "\n 22 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4187, "s": 4171, "text": " Fanuel Mapuwei" }, { "code": null, "e": 4222, "s": 4187, "text": "\n 44 Lectures \n 3.5 hours \n" }, { "code": null, "e": 4239, "s": 4222, "text": " Rohit Dharaviya" }, { "code": null, "e": 4246, "s": 4239, "text": " Print" }, { "code": null, "e": 4257, "s": 4246, "text": " Add Notes" } ]