title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Python | Get last N elements from given list - GeeksforGeeks
01 Jul, 2021 Accessing elements in a list has many types and variations. These are an essential part of Python programming and one must have the knowledge to perform the same. This article discusses ways to fetch the last N elements of list. Let’s discuss certain solution to perform this task.Method #1 : Using list slicingThis problem can be performed in 1 line rather than using a loop using the list slicing functionality provided by Python. Minus operator specifies slicing to be done from rear end. Python3 # Python3 code to demonstrate# Get last N elements from list# using list slicing # initializing listtest_list = [4, 5, 2, 6, 7, 8, 10] # printing original listprint("The original list : " + str(test_list)) # initializing NN = 5 # using list slicing# Get last N elements from listres = test_list[-N:] # print resultprint("The last N elements of list are : " + str(res)) The original list : [4, 5, 2, 6, 7, 8, 10] The last N elements of list are : [2, 6, 7, 8, 10] Method #2 : Using islice() + reversed()The inbuilt functions can also be used to perform this particular task. The islice function can be used to get the sliced list and reversed function is used to get the elements from rear end. Python3 # Python3 code to demonstrate# Get last N elements from list# using islice() + reversed()from itertools import islice # initializing listtest_list = [4, 5, 2, 6, 7, 8, 10] # printing original listprint("The original list : " + str(test_list)) # initializing NN = 5 # using islice() + reversed()# Get last N elements from listres = list(islice(reversed(test_list), 0, N))res.reverse() # print resultprint("The last N elements of list are : " + str(res)) The original list : [4, 5, 2, 6, 7, 8, 10] The last N elements of list are : [2, 6, 7, 8, 10] gabaa406 Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Python OOPs Concepts Defaultdict in Python Python | Split string into list of characters Python program to check whether a number is Prime or not Python | Get dictionary keys as a list Python | Convert a list to dictionary
[ { "code": null, "e": 24418, "s": 24390, "text": "\n01 Jul, 2021" }, { "code": null, "e": 24911, "s": 24418, "text": "Accessing elements in a list has many types and variations. These are an essential part of Python programming and one must have the knowledge to perform the same. This article discusses ways to fetch the last N elements of list. Let’s discuss certain solution to perform this task.Method #1 : Using list slicingThis problem can be performed in 1 line rather than using a loop using the list slicing functionality provided by Python. Minus operator specifies slicing to be done from rear end. " }, { "code": null, "e": 24919, "s": 24911, "text": "Python3" }, { "code": "# Python3 code to demonstrate# Get last N elements from list# using list slicing # initializing listtest_list = [4, 5, 2, 6, 7, 8, 10] # printing original listprint(\"The original list : \" + str(test_list)) # initializing NN = 5 # using list slicing# Get last N elements from listres = test_list[-N:] # print resultprint(\"The last N elements of list are : \" + str(res))", "e": 25288, "s": 24919, "text": null }, { "code": null, "e": 25382, "s": 25288, "text": "The original list : [4, 5, 2, 6, 7, 8, 10]\nThe last N elements of list are : [2, 6, 7, 8, 10]" }, { "code": null, "e": 25617, "s": 25384, "text": " Method #2 : Using islice() + reversed()The inbuilt functions can also be used to perform this particular task. The islice function can be used to get the sliced list and reversed function is used to get the elements from rear end. " }, { "code": null, "e": 25625, "s": 25617, "text": "Python3" }, { "code": "# Python3 code to demonstrate# Get last N elements from list# using islice() + reversed()from itertools import islice # initializing listtest_list = [4, 5, 2, 6, 7, 8, 10] # printing original listprint(\"The original list : \" + str(test_list)) # initializing NN = 5 # using islice() + reversed()# Get last N elements from listres = list(islice(reversed(test_list), 0, N))res.reverse() # print resultprint(\"The last N elements of list are : \" + str(res))", "e": 26078, "s": 25625, "text": null }, { "code": null, "e": 26172, "s": 26078, "text": "The original list : [4, 5, 2, 6, 7, 8, 10]\nThe last N elements of list are : [2, 6, 7, 8, 10]" }, { "code": null, "e": 26183, "s": 26174, "text": "gabaa406" }, { "code": null, "e": 26204, "s": 26183, "text": "Python list-programs" }, { "code": null, "e": 26211, "s": 26204, "text": "Python" }, { "code": null, "e": 26227, "s": 26211, "text": "Python Programs" }, { "code": null, "e": 26325, "s": 26227, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26334, "s": 26325, "text": "Comments" }, { "code": null, "e": 26347, "s": 26334, "text": "Old Comments" }, { "code": null, "e": 26365, "s": 26347, "text": "Python Dictionary" }, { "code": null, "e": 26397, "s": 26365, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26419, "s": 26397, "text": "Enumerate() in Python" }, { "code": null, "e": 26461, "s": 26419, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 26482, "s": 26461, "text": "Python OOPs Concepts" }, { "code": null, "e": 26504, "s": 26482, "text": "Defaultdict in Python" }, { "code": null, "e": 26550, "s": 26504, "text": "Python | Split string into list of characters" }, { "code": null, "e": 26607, "s": 26550, "text": "Python program to check whether a number is Prime or not" }, { "code": null, "e": 26646, "s": 26607, "text": "Python | Get dictionary keys as a list" } ]
Program to print the DFS traversal step-wise using C++
In this tutorial, we will be discussing a program to print the steps of the traversal using Depth First Search in a given binary tree. This would include every step that occurs in the depth-first search including the backtracking procedure as well. During DFS, we will be traversing each node and simultaneously storing the parent node and the edge used. During the traversal, if the adjacent edge has been visited, then the exact node can be printed as a step in the depth-first search. #include <bits/stdc++.h> using namespace std; const int N = 1000; vector<int> adj[N]; //printing the steps in DFS traversal void dfs_steps(int u, int node, bool visited[], vector<pair<int, int< > path_used, int parent, int it){ int c = 0; for (int i = 0; i < node; i++) if (visited[i]) c++; if (c == node) return; //marking the node as visited visited[u] = true; path_used.push_back({ parent, u }); cout << u << " "; for (int x : adj[u]){ if (!visited[x]) dfs_steps(x, node, visited, path_used, u, it + 1); } for (auto y : path_used) if (y.second == u) dfs_steps(y.first, node, visited, path_used, u, it + 1); } void dfs(int node){ bool visited[node]; vector<pair<int, int> > path_used; for (int i = 0; i < node; i++) visited[i] = false; dfs_steps(0, node, visited, path_used, -1, 0); } void add_edge(int u, int v){ adj[u].push_back(v); adj[v].push_back(u); } int main(){ int node = 11, edge = 13; add_edge(0, 1); add_edge(0, 2); add_edge(1, 5); add_edge(1, 6); add_edge(2, 4); add_edge(2, 9); add_edge(6, 7); add_edge(6, 8); add_edge(7, 8); add_edge(2, 3); add_edge(3, 9); add_edge(3, 10); add_edge(9, 10); dfs(node); return 0; } 0 1 5 1 6 7 8 7 6 1 0 2 4 2 9 3 10
[ { "code": null, "e": 1197, "s": 1062, "text": "In this tutorial, we will be discussing a program to print the steps of the traversal using Depth First Search in a given binary tree." }, { "code": null, "e": 1311, "s": 1197, "text": "This would include every step that occurs in the depth-first search including the backtracking procedure as well." }, { "code": null, "e": 1550, "s": 1311, "text": "During DFS, we will be traversing each node and simultaneously storing the parent node and the edge used. During the traversal, if the adjacent edge has been visited, then the exact node can be printed as a step in the depth-first search." }, { "code": null, "e": 2819, "s": 1550, "text": "#include <bits/stdc++.h>\nusing namespace std;\nconst int N = 1000;\nvector<int> adj[N];\n//printing the steps in DFS traversal\nvoid dfs_steps(int u, int node, bool visited[],\nvector<pair<int, int< > path_used, int parent, int it){\n int c = 0;\n for (int i = 0; i < node; i++)\n if (visited[i])\n c++;\n if (c == node)\n return;\n//marking the node as visited\n visited[u] = true;\n path_used.push_back({ parent, u });\n cout << u << \" \";\n for (int x : adj[u]){\n if (!visited[x])\n dfs_steps(x, node, visited, path_used, u, it + 1);\n }\n for (auto y : path_used)\n if (y.second == u)\n dfs_steps(y.first, node, visited,\n path_used, u, it + 1);\n}\nvoid dfs(int node){\n bool visited[node];\n vector<pair<int, int> > path_used;\n for (int i = 0; i < node; i++)\n visited[i] = false;\n dfs_steps(0, node, visited, path_used, -1, 0);\n }\nvoid add_edge(int u, int v){\n adj[u].push_back(v);\n adj[v].push_back(u);\n}\nint main(){\n int node = 11, edge = 13;\n add_edge(0, 1);\n add_edge(0, 2);\n add_edge(1, 5);\n add_edge(1, 6);\n add_edge(2, 4);\n add_edge(2, 9);\n add_edge(6, 7);\n add_edge(6, 8);\n add_edge(7, 8);\n add_edge(2, 3);\n add_edge(3, 9);\n add_edge(3, 10);\n add_edge(9, 10);\n dfs(node);\n return 0;\n}" }, { "code": null, "e": 2854, "s": 2819, "text": "0 1 5 1 6 7 8 7 6 1 0 2 4 2 9 3 10" } ]
Flow control in try catch finally in C#
The flow control in try, catch, and finally can be understood using the following example. Here, we are dividing two numbers − Live Demo using System; namespace ErrorHandlingApplication { class DivNumbers { int result; DivNumbers() { result = 0; } public void division(int num1, int num2) { try { result = num1 / num2; } catch (DivideByZeroException e) { Console.WriteLine("Exception caught: {0}", e); } finally { Console.WriteLine("Result: {0}", result); } } static void Main(string[] args) { DivNumbers d = new DivNumbers(); d.division(25, 0); Console.ReadKey(); } } } Exception caught: System.DivideByZeroException: Attempted to divide by zero. at ErrorHandlingApplication.DivNumbers.division (System.Int32 num1, System.Int32 num2) [0x00000] in :0 Result: 0 The following shows the flow control in exceptions handling using try catch finally in C# If an exception occurs in try block, then the control transfers to the catch block. After the catch block finish, then the finally block works. If no exception occurs, then firstly the try occurs and then the flow control to finally block
[ { "code": null, "e": 1189, "s": 1062, "text": "The flow control in try, catch, and finally can be understood using the following example. Here, we are dividing two numbers −" }, { "code": null, "e": 1200, "s": 1189, "text": " Live Demo" }, { "code": null, "e": 1791, "s": 1200, "text": "using System;\n\nnamespace ErrorHandlingApplication {\n class DivNumbers {\n int result;\n DivNumbers() {\n result = 0;\n }\n public void division(int num1, int num2) {\n try {\n result = num1 / num2;\n } catch (DivideByZeroException e) {\n Console.WriteLine(\"Exception caught: {0}\", e);\n } finally {\n Console.WriteLine(\"Result: {0}\", result);\n }\n }\n static void Main(string[] args) {\n DivNumbers d = new DivNumbers();\n d.division(25, 0);\n Console.ReadKey();\n }\n }\n}" }, { "code": null, "e": 1981, "s": 1791, "text": "Exception caught: System.DivideByZeroException: Attempted to divide by zero.\nat ErrorHandlingApplication.DivNumbers.division (System.Int32 num1, System.Int32 num2) [0x00000] in :0\nResult: 0" }, { "code": null, "e": 2071, "s": 1981, "text": "The following shows the flow control in exceptions handling using try catch finally in C#" }, { "code": null, "e": 2155, "s": 2071, "text": "If an exception occurs in try block, then the control transfers to the catch block." }, { "code": null, "e": 2215, "s": 2155, "text": "After the catch block finish, then the finally block works." }, { "code": null, "e": 2310, "s": 2215, "text": "If no exception occurs, then firstly the try occurs and then the flow control to finally block" } ]
Working with Recycler View in Android App
This example demonstrates about Working with Recycler View in Android App 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" android:id="@+id/rlMain" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="16dp" android:orientation="vertical"> <androidx.recyclerview.widget.RecyclerView android:id="@+id/recyclerView" android:layout_width="match_parent" android:layout_height="match_parent" /> </LinearLayout> Step 3 − Add the following code to src/MainActivity.java package app.com.sample; import android.os.Bundle; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.DefaultItemAnimator; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity { private List<MovieModel> movieList = new ArrayList<>(); private MoviesAdapter mAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); RecyclerView recyclerView = findViewById(R.id.recyclerView); mAdapter = new MoviesAdapter(movieList); LinearLayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext()); recyclerView.setLayoutManager(mLayoutManager); recyclerView.setItemAnimator(new DefaultItemAnimator()); recyclerView.setAdapter(mAdapter); prepareMovieData(); } private void prepareMovieData() { MovieModel movie = new MovieModel("Mad Max: Fury Road", "Action & Adventure", "2015"); movieList.add(movie); movie = new MovieModel("Inside Out", "Animation, Kids & Family", "2015"); movieList.add(movie); movie = new MovieModel("Star Wars: Episode VII - The Force Awakens", "Action", "2015"); movieList.add(movie); movie = new MovieModel("Shaun the Sheep", "Animation", "2015"); movieList.add(movie); movie = new MovieModel("The Martian", "Science Fiction & Fantasy", "2015"); movieList.add(movie); movie = new MovieModel("Mission: Impossible Rogue Nation", "Action", "2015"); movieList.add(movie); movie = new MovieModel("Up", "Animation", "2009"); movieList.add(movie); movie = new MovieModel("Star Trek", "Science Fiction", "2009"); movieList.add(movie); movie = new MovieModel("The LEGO MovieModel", "Animation", "2014"); movieList.add(movie); movie = new MovieModel("Iron Man", "Action & Adventure", "2008"); movieList.add(movie); movie = new MovieModel("Aliens", "Science Fiction", "1986"); movieList.add(movie); movie = new MovieModel("Chicken Run", "Animation", "2000"); movieList.add(movie); movie = new MovieModel("Back to the Future", "Science Fiction", "1985"); movieList.add(movie); movie = new MovieModel("Raiders of the Lost Ark", "Action & Adventure", "1981"); movieList.add(movie); movie = new MovieModel("Goldfinger", "Action & Adventure", "1965"); movieList.add(movie); movie = new MovieModel("Guardians of the Galaxy", "Science Fiction & Fantasy", "2014"); movieList.add(movie); mAdapter.notifyDataSetChanged(); } } Step 4 − Add the following code to src/MovieModel.java package app.com.sample; public class MovieModel { private String title, genre, year; public MovieModel() { } public MovieModel(String title, String genre, String year) { this.title = title; this.genre = genre; this.year = year; } public String getTitle() { return title; } public void setTitle(String name) { this.title = name; } public String getYear() { return year; } public void setYear(String year) { this.year = year; } public String getGenre() { return genre; } public void setGenre(String genre) { this.genre = genre; } } Step 5 − Add the following code to res/layout/movies_list.xml. <?xml version="1.0" encoding="utf-8"?> <androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width=" match_parent" android:layout_height="100dp" android:layout_margin="8dp"> <RelativeLayout android:layout_width="match_parent" android:layout_height="match_parent" android:padding="8dp"> <TextView android:id="@+id/title" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentStart="true" android:layout_toStartOf="@+id/year" android:textColor="#222222" android:textSize="16sp" android:textStyle="bold" /> <TextView android:id="@+id/year" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentEnd="true" android:textColor="#999999" /> <TextView android:id="@+id/genre" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true" /> </RelativeLayout> </androidx.cardview.widget.CardView> Step 6 − Add the following code to src/MoviesAdapter.java package app.com.sample; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import java.util.List; public class MoviesAdapter extends RecyclerView.Adapter<MoviesAdapter.MyViewHolder> { private List<MovieModel> moviesList; class MyViewHolder extends RecyclerView.ViewHolder { TextView title, year, genre; MyViewHolder(View view) { super(view); title = view.findViewById(R.id.title); genre = view.findViewById(R.id.genre); year = view.findViewById(R.id.year); } } public MoviesAdapter(List<MovieModel> moviesList) { this.moviesList = moviesList; } @NonNull @Override public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View itemView = LayoutInflater.from(parent.getContext()) .inflate(R.layout.movie_list, parent, false); return new MyViewHolder(itemView); } @Override public void onBindViewHolder(MyViewHolder holder, int position) { MovieModel movie = moviesList.get(position); holder.title.setText(movie.getTitle()); holder.genre.setText(movie.getGenre()); holder.year.setText(movie.getYear()); } @Override public int getItemCount() { return moviesList.size(); } } Step 7 − Add the following code to androidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and Click Run Icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen – Click here to download the project code.
[ { "code": null, "e": 1136, "s": 1062, "text": "This example demonstrates about Working with Recycler View in Android App" }, { "code": null, "e": 1266, "s": 1136, "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": 1332, "s": 1266, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 1805, "s": 1332, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:id=\"@+id/rlMain\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:layout_margin=\"16dp\"\n android:orientation=\"vertical\">\n <androidx.recyclerview.widget.RecyclerView\n android:id=\"@+id/recyclerView\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\" />\n</LinearLayout>" }, { "code": null, "e": 1863, "s": 1805, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 4651, "s": 1863, "text": "package app.com.sample;\nimport android.os.Bundle;\nimport androidx.appcompat.app.AppCompatActivity;\nimport androidx.recyclerview.widget.DefaultItemAnimator;\nimport androidx.recyclerview.widget.LinearLayoutManager;\nimport androidx.recyclerview.widget.RecyclerView;\nimport java.util.ArrayList;\nimport java.util.List;\npublic class MainActivity extends AppCompatActivity {\n private List<MovieModel> movieList = new ArrayList<>();\n private MoviesAdapter mAdapter;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n RecyclerView recyclerView = findViewById(R.id.recyclerView);\n mAdapter = new MoviesAdapter(movieList);\n LinearLayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());\n recyclerView.setLayoutManager(mLayoutManager);\n recyclerView.setItemAnimator(new DefaultItemAnimator());\n recyclerView.setAdapter(mAdapter);\n prepareMovieData();\n }\n private void prepareMovieData() {\n MovieModel movie = new MovieModel(\"Mad Max: Fury Road\", \"Action & Adventure\", \"2015\");\n movieList.add(movie);\n movie = new MovieModel(\"Inside Out\", \"Animation, Kids & Family\", \"2015\");\n movieList.add(movie);\n movie = new MovieModel(\"Star Wars: Episode VII - The Force Awakens\", \"Action\", \"2015\");\n movieList.add(movie);\n movie = new MovieModel(\"Shaun the Sheep\", \"Animation\", \"2015\");\n movieList.add(movie);\n movie = new MovieModel(\"The Martian\", \"Science Fiction & Fantasy\", \"2015\");\n movieList.add(movie);\n movie = new MovieModel(\"Mission: Impossible Rogue Nation\", \"Action\", \"2015\");\n movieList.add(movie);\n movie = new MovieModel(\"Up\", \"Animation\", \"2009\");\n movieList.add(movie);\n movie = new MovieModel(\"Star Trek\", \"Science Fiction\", \"2009\");\n movieList.add(movie);\n movie = new MovieModel(\"The LEGO MovieModel\", \"Animation\", \"2014\");\n movieList.add(movie);\n movie = new MovieModel(\"Iron Man\", \"Action & Adventure\", \"2008\");\n movieList.add(movie);\n movie = new MovieModel(\"Aliens\", \"Science Fiction\", \"1986\");\n movieList.add(movie);\n movie = new MovieModel(\"Chicken Run\", \"Animation\", \"2000\");\n movieList.add(movie);\n movie = new MovieModel(\"Back to the Future\", \"Science Fiction\", \"1985\");\n movieList.add(movie);\n movie = new MovieModel(\"Raiders of the Lost Ark\", \"Action & Adventure\", \"1981\");\n movieList.add(movie);\n movie = new MovieModel(\"Goldfinger\", \"Action & Adventure\", \"1965\");\n movieList.add(movie);\n movie = new MovieModel(\"Guardians of the Galaxy\", \"Science Fiction & Fantasy\", \"2014\");\n movieList.add(movie);\n mAdapter.notifyDataSetChanged();\n }\n}" }, { "code": null, "e": 4707, "s": 4651, "text": "Step 4 − Add the following code to src/MovieModel.java" }, { "code": null, "e": 5342, "s": 4707, "text": "package app.com.sample;\npublic class MovieModel {\n private String title, genre, year;\n public MovieModel() {\n }\n public MovieModel(String title, String genre, String year) {\n this.title = title;\n this.genre = genre;\n this.year = year;\n }\n public String getTitle() {\n return title;\n }\n public void setTitle(String name) {\n this.title = name;\n }\n public String getYear() {\n return year;\n }\n public void setYear(String year) {\n this.year = year;\n }\n public String getGenre() {\n return genre;\n }\n public void setGenre(String genre) {\n this.genre = genre;\n }\n}" }, { "code": null, "e": 5406, "s": 5342, "text": "Step 5 − Add the following code to res/layout/movies_list.xml." }, { "code": null, "e": 6593, "s": 5406, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<androidx.cardview.widget.CardView xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:layout_width=\" match_parent\"\n android:layout_height=\"100dp\"\n android:layout_margin=\"8dp\">\n <RelativeLayout\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:padding=\"8dp\">\n <TextView\n android:id=\"@+id/title\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:layout_alignParentStart=\"true\"\n android:layout_toStartOf=\"@+id/year\"\n android:textColor=\"#222222\"\n android:textSize=\"16sp\"\n android:textStyle=\"bold\" />\n <TextView\n android:id=\"@+id/year\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_alignParentEnd=\"true\"\n android:textColor=\"#999999\" />\n <TextView\n android:id=\"@+id/genre\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:layout_alignParentBottom=\"true\" />\n </RelativeLayout>\n</androidx.cardview.widget.CardView>" }, { "code": null, "e": 6652, "s": 6593, "text": "Step 6 − Add the following code to src/MoviesAdapter.java" }, { "code": null, "e": 8051, "s": 6652, "text": "package app.com.sample;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.TextView;\nimport androidx.annotation.NonNull;\nimport androidx.recyclerview.widget.RecyclerView;\nimport java.util.List;\npublic class MoviesAdapter extends RecyclerView.Adapter<MoviesAdapter.MyViewHolder> {\n private List<MovieModel> moviesList;\n class MyViewHolder extends RecyclerView.ViewHolder {\n TextView title, year, genre;\n MyViewHolder(View view) {\n super(view);\n title = view.findViewById(R.id.title);\n genre = view.findViewById(R.id.genre);\n year = view.findViewById(R.id.year);\n }\n }\n public MoviesAdapter(List<MovieModel> moviesList) {\n this.moviesList = moviesList;\n }\n @NonNull\n @Override\n public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {\n View itemView = LayoutInflater.from(parent.getContext())\n .inflate(R.layout.movie_list, parent, false);\n return new MyViewHolder(itemView);\n }\n @Override\n public void onBindViewHolder(MyViewHolder holder, int position) {\n MovieModel movie = moviesList.get(position);\n holder.title.setText(movie.getTitle());\n holder.genre.setText(movie.getGenre());\n holder.year.setText(movie.getYear());\n }\n @Override\n public int getItemCount() {\n return moviesList.size();\n }\n}" }, { "code": null, "e": 8107, "s": 8051, "text": "Step 7 − Add the following code to androidManifest.xml" }, { "code": null, "e": 8780, "s": 8107, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"app.com.sample\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 9127, "s": 8780, "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": 9168, "s": 9127, "text": "Click here to download the project code." } ]
How to generate a random number in C++?
Let us see how to generate random numbers using C++. Here we are generating a random number in range 0 to some value. (In this program the max value is 100). To perform this operation we are using the srand() function. This is in the C library. The function void srand(unsigned int seed) seeds the random number generator used by the function rand. The declaration of srand() is like below − void srand(unsigned int seed) It takes a parameter called seed. This is an integer value to be used as seed by the pseudorandom number generator algorithm. This function returns nothing. To get the number we need the rand() method. To get the number in range 0 to max, we are using modulus operator to get the remainder. For the seed value we are providing the time(0) function result into the srand() function. #include<iostream> #include<cstdlib> #include<ctime> using namespace std; main(){ int max; max = 100; //set the upper bound to generate the random number srand(time(0)); cout >> "The random number is: ">>rand()%max; } The random number is: 51 The random number is: 29 The random number is: 47
[ { "code": null, "e": 1220, "s": 1062, "text": "Let us see how to generate random numbers using C++. Here we are generating a random number in range 0 to some value. (In this program the max value is 100)." }, { "code": null, "e": 1411, "s": 1220, "text": "To perform this operation we are using the srand() function. This is in the C library. The function void srand(unsigned int seed) seeds the random number generator used by the function rand." }, { "code": null, "e": 1454, "s": 1411, "text": "The declaration of srand() is like below −" }, { "code": null, "e": 1484, "s": 1454, "text": "void srand(unsigned int seed)" }, { "code": null, "e": 1641, "s": 1484, "text": "It takes a parameter called seed. This is an integer value to be used as seed by the pseudorandom number generator algorithm. This function returns nothing." }, { "code": null, "e": 1775, "s": 1641, "text": "To get the number we need the rand() method. To get the number in range 0 to max, we are using modulus operator to get the remainder." }, { "code": null, "e": 1866, "s": 1775, "text": "For the seed value we are providing the time(0) function result into the srand() function." }, { "code": null, "e": 2096, "s": 1866, "text": "#include<iostream>\n#include<cstdlib>\n#include<ctime>\nusing namespace std;\nmain(){\n int max;\n max = 100; //set the upper bound to generate the random number\n srand(time(0));\n cout >> \"The random number is: \">>rand()%max;\n}" }, { "code": null, "e": 2121, "s": 2096, "text": "The random number is: 51" }, { "code": null, "e": 2146, "s": 2121, "text": "The random number is: 29" }, { "code": null, "e": 2171, "s": 2146, "text": "The random number is: 47" } ]
How to swap two numbers without using the third or a temporary variable using C Programming?
With the help of addition and subtraction operations, we can swap two numbers from one memory location to another memory location. The algorithm is explained below − Step 1: Declare 2 variables x and y. Step 2: Read two numbers from keyboard. Step 3: Swap numbers. //Apply addition and subtraction operations to swap the numbers. i. x=x+y ii. y=x-y iii. x=x-y Step 4: Print x and y values. Following is the C program which explains swapping of two numbers without using third variable or a temporary variable − #include<stdio.h> int main(){ int x,y; printf("enter x and y values:"); scanf("%d%d",&x,&y);// lets take x as 20 and y as 30 x=x+y;// x=20+30=50 y=x-y;//y=50-30=20 x=x-y;//x=50-20=30 printf("After swap x=%d and y=%d",x,y); return 0; } You will get the following output − enter x and y values:20 30 After swap x=30 and y=20 Note − We can swap two numbers by using multiplication and division and bitwise XOR operators without taking third variable help. Consider another example which explains how to swap two numbers by using multiplication and division operators. Following is the C program to demonstrate the respective functioning of swapping two numbers − #include<stdio.h> int main(){ int x,y; printf("enter x and y values:"); scanf("%d%d",&x,&y); x=x*y; y=x/y; x=x/y; printf("After swap x=%d and y=%d",x,y); return 0; } When you execute the above program, you will get the following output − enter x and y values:120 250 After swap x=250 and y=120
[ { "code": null, "e": 1193, "s": 1062, "text": "With the help of addition and subtraction operations, we can swap two numbers from one memory location to another memory location." }, { "code": null, "e": 1228, "s": 1193, "text": "The algorithm is explained below −" }, { "code": null, "e": 1461, "s": 1228, "text": "Step 1: Declare 2 variables x and y.\nStep 2: Read two numbers from keyboard.\nStep 3: Swap numbers.\n//Apply addition and subtraction operations to swap the numbers.\n i. x=x+y\n ii. y=x-y\n iii. x=x-y\nStep 4: Print x and y values." }, { "code": null, "e": 1582, "s": 1461, "text": "Following is the C program which explains swapping of two numbers without using third variable or a temporary variable −" }, { "code": null, "e": 1841, "s": 1582, "text": "#include<stdio.h>\nint main(){\n int x,y;\n printf(\"enter x and y values:\");\n scanf(\"%d%d\",&x,&y);// lets take x as 20 and y as 30\n x=x+y;// x=20+30=50\n y=x-y;//y=50-30=20\n x=x-y;//x=50-20=30\n printf(\"After swap x=%d and y=%d\",x,y);\n return 0;\n}" }, { "code": null, "e": 1877, "s": 1841, "text": "You will get the following output −" }, { "code": null, "e": 1929, "s": 1877, "text": "enter x and y values:20 30\nAfter swap x=30 and y=20" }, { "code": null, "e": 2059, "s": 1929, "text": "Note − We can swap two numbers by using multiplication and division and bitwise XOR operators without taking third variable help." }, { "code": null, "e": 2171, "s": 2059, "text": "Consider another example which explains how to swap two numbers by using multiplication and division operators." }, { "code": null, "e": 2266, "s": 2171, "text": "Following is the C program to demonstrate the respective functioning of swapping two numbers −" }, { "code": null, "e": 2456, "s": 2266, "text": "#include<stdio.h>\nint main(){\n int x,y;\n printf(\"enter x and y values:\");\n scanf(\"%d%d\",&x,&y);\n x=x*y;\n y=x/y;\n x=x/y;\n printf(\"After swap x=%d and y=%d\",x,y);\n return 0;\n}" }, { "code": null, "e": 2528, "s": 2456, "text": "When you execute the above program, you will get the following output −" }, { "code": null, "e": 2584, "s": 2528, "text": "enter x and y values:120 250\nAfter swap x=250 and y=120" } ]
Passing an array to a query using WHERE clause in MySQL?
We can pass an array with the help of where IN clause. Let us first create a new table for our example. mysql> create table PassingAnArrayDemo -> ( -> id int, -> Firstname varchar(100) -> ); Query OK, 0 rows affected (1.60 sec) Let us now insert records. mysql> insert into PassingAnArrayDemo values(1,'John'),(2,'Carol'),(3,'Smith'),(4,'Bob'),(5,'Johnson'),(6,'David'),(7,'Sam'),(8,'Jessica'); Query OK, 8 rows affected (0.32 sec) Records: 8 Duplicates: 0 Warnings: 0 To display all records. mysql> select *from PassingAnArrayDemo; The following is the output. +------+-----------+ | id | Firstname | +------+-----------+ | 1 | John | | 2 | Carol | | 3 | Smith | | 4 | Bob | | 5 | Johnson | | 6 | David | | 7 | Sam | | 8 | Jessica | +------+-----------+ 8 rows in set (0.00 sec) The following is the syntax to send an array parameter with the help of where IN clause. mysql> SELECT * -> FROM PassingAnArrayDemo where id IN(1,3,6); The following is the output. +------+-----------+ | id | Firstname | +------+-----------+ | 1 | John | | 3 | Smith | | 6 | David | +------+-----------+ 3 rows in set (0.04 sec)
[ { "code": null, "e": 1166, "s": 1062, "text": "We can pass an array with the help of where IN clause. Let us first create a new table for our example." }, { "code": null, "e": 1302, "s": 1166, "text": "mysql> create table PassingAnArrayDemo\n -> (\n -> id int,\n -> Firstname varchar(100)\n -> );\nQuery OK, 0 rows affected (1.60 sec)" }, { "code": null, "e": 1329, "s": 1302, "text": "Let us now insert records." }, { "code": null, "e": 1545, "s": 1329, "text": "mysql> insert into PassingAnArrayDemo values(1,'John'),(2,'Carol'),(3,'Smith'),(4,'Bob'),(5,'Johnson'),(6,'David'),(7,'Sam'),(8,'Jessica');\nQuery OK, 8 rows affected (0.32 sec)\nRecords: 8 Duplicates: 0 Warnings: 0" }, { "code": null, "e": 1569, "s": 1545, "text": "To display all records." }, { "code": null, "e": 1609, "s": 1569, "text": "mysql> select *from PassingAnArrayDemo;" }, { "code": null, "e": 1638, "s": 1609, "text": "The following is the output." }, { "code": null, "e": 1916, "s": 1638, "text": "+------+-----------+\n| id | Firstname |\n+------+-----------+\n| 1 | John |\n| 2 | Carol |\n| 3 | Smith |\n| 4 | Bob |\n| 5 | Johnson |\n| 6 | David |\n| 7 | Sam |\n| 8 | Jessica |\n+------+-----------+\n8 rows in set (0.00 sec)\n" }, { "code": null, "e": 2005, "s": 1916, "text": "The following is the syntax to send an array parameter with the help of where IN clause." }, { "code": null, "e": 2071, "s": 2005, "text": "mysql> SELECT *\n -> FROM PassingAnArrayDemo where id IN(1,3,6);" }, { "code": null, "e": 2100, "s": 2071, "text": "The following is the output." }, { "code": null, "e": 2273, "s": 2100, "text": "+------+-----------+\n| id | Firstname |\n+------+-----------+\n| 1 | John |\n| 3 | Smith |\n| 6 | David |\n+------+-----------+\n3 rows in set (0.04 sec)\n" } ]
C++ String Library - length
It returns the length of the string, in terms of bytes. Following is the declaration for std::string::length. size_t length() const; size_t length() const noexcept; none It returns the length of the string, in terms of bytes. Never throw any exceptions. In below example for std::string::length. #include <iostream> #include <string> int main () { std::string str ("Sairamkrishna Mammahe"); std::cout << "The size of str is " << str.length() << " bytes.\n"; return 0; } The sample output should be like this − The size of str is 21 bytes. Print Add Notes Bookmark this page
[ { "code": null, "e": 2659, "s": 2603, "text": "It returns the length of the string, in terms of bytes." }, { "code": null, "e": 2713, "s": 2659, "text": "Following is the declaration for std::string::length." }, { "code": null, "e": 2736, "s": 2713, "text": "size_t length() const;" }, { "code": null, "e": 2768, "s": 2736, "text": "size_t length() const noexcept;" }, { "code": null, "e": 2773, "s": 2768, "text": "none" }, { "code": null, "e": 2829, "s": 2773, "text": "It returns the length of the string, in terms of bytes." }, { "code": null, "e": 2857, "s": 2829, "text": "Never throw any exceptions." }, { "code": null, "e": 2899, "s": 2857, "text": "In below example for std::string::length." }, { "code": null, "e": 3083, "s": 2899, "text": "#include <iostream>\n#include <string>\n\nint main () {\n std::string str (\"Sairamkrishna Mammahe\");\n std::cout << \"The size of str is \" << str.length() << \" bytes.\\n\";\n return 0;\n}" }, { "code": null, "e": 3123, "s": 3083, "text": "The sample output should be like this −" }, { "code": null, "e": 3153, "s": 3123, "text": "The size of str is 21 bytes.\n" }, { "code": null, "e": 3160, "s": 3153, "text": " Print" }, { "code": null, "e": 3171, "s": 3160, "text": " Add Notes" } ]
How to display the Engine of a MySQL table?
To know whether a MySQL table is using MyISAM or InnoDB engine then you can use below syntax. The below syntax can be used for multiple tables − show table status from yourDatabaseName; Here is the syntax that can be used for a specific table i.e. to know the engine of a table − show table status from yourDatabaseName Like ‘yourTableName’. The following is the query to display engine of all the tables − mysql> show table status from sampleTest; The following is the output − +--------------+--------+---------+------------+------+----------------+-------------+-----------------+--------------+-----------+----------------+---------------------+---------------------+------------+--------------------+----------+----------------+---------+ | Name | Engine | Version | Row_format | Rows | Avg_row_length | Data_length | Max_data_length | Index_length | Data_free | Auto_increment | Create_time | Update_time | Check_time | Collation | Checksum | Create_options | Comment | +--------------+--------+---------+------------+------+----------------+-------------+-----------------+--------------+-----------+----------------+---------------------+---------------------+------------+--------------------+----------+----------------+---------+ | datetimedemo | InnoDB | 10 | Dynamic | 0 | 0 | 16384 | 0 | 0 | 0 | NULL | 2018-12-05 09:22:54 | NULL | NULL | utf8mb4_0900_ai_ci | NULL | | | | primarydemo | InnoDB | 10 | Dynamic | 0 | 0 | 16384 | 0 | 0 | 0 | NULL | 2018-12-05 09:23:34 | NULL | NULL | utf8mb4_0900_ai_ci | NULL | | | | student | MyISAM | 10 | Dynamic | 0 | 0 | | 281474976710655 | 1024 | 0 | 1 | 2018-12-05 09:22:22 | 2018-12-05 09:22:23 | NULL | utf8mb4_0900_ai_ci | NULL | | | +--------------+--------+---------+------------+------+----------------+-------------+-----------------+--------------+-----------+----------------+---------------------+---------------------+------------+--------------------+----------+----------------+---------+ 3 rows in set (0.19 sec) The following is the query to display engine type for a specific table − mysql> show table status from sampletest Like 'student'; The following is the output that displays the engine for only “student” table − +---------+--------+---------+------------+------+----------------+-------------+-----------------+--------------+-----------+----------------+---------------------+---------------------+------------+--------------------+----------+----------------+---------+ | Name | Engine | Version | Row_format | Rows | Avg_row_length | Data_length | Max_data_length | Index_length | Data_free | Auto_increment | Create_time | Update_time | Check_time | Collation | Checksum | Create_options | Comment | +---------+--------+---------+------------+------+----------------+-------------+-----------------+--------------+-----------+----------------+---------------------+---------------------+------------+--------------------+----------+----------------+---------+ | student | MyISAM | 10 | Dynamic | 0 | 0 | 0 | 281474976710655 | 1024 | 0 | 1 | 2018-12-05 09:22:22 | 2018-12-05 09:22:23 | NULL | utf8mb4_0900_ai_ci | NULL | | | +---------+--------+---------+------------+------+----------------+-------------+-----------------+--------------+-----------+----------------+---------------------+---------------------+------------+--------------------+----------+----------------+---------+ 1 row in set (0.00 sec)
[ { "code": null, "e": 1156, "s": 1062, "text": "To know whether a MySQL table is using MyISAM or InnoDB engine then you can use below syntax." }, { "code": null, "e": 1207, "s": 1156, "text": "The below syntax can be used for multiple tables −" }, { "code": null, "e": 1248, "s": 1207, "text": "show table status from yourDatabaseName;" }, { "code": null, "e": 1342, "s": 1248, "text": "Here is the syntax that can be used for a specific table i.e. to know the engine of a table −" }, { "code": null, "e": 1404, "s": 1342, "text": "show table status from yourDatabaseName Like ‘yourTableName’." }, { "code": null, "e": 1469, "s": 1404, "text": "The following is the query to display engine of all the tables −" }, { "code": null, "e": 1511, "s": 1469, "text": "mysql> show table status from sampleTest;" }, { "code": null, "e": 1541, "s": 1511, "text": "The following is the output −" }, { "code": null, "e": 3341, "s": 1541, "text": "+--------------+--------+---------+------------+------+----------------+-------------+-----------------+--------------+-----------+----------------+---------------------+---------------------+------------+--------------------+----------+----------------+---------+\n| Name | Engine | Version | Row_format | Rows | Avg_row_length | Data_length | Max_data_length | Index_length | Data_free | Auto_increment | Create_time | Update_time | Check_time | Collation | Checksum | Create_options | Comment |\n+--------------+--------+---------+------------+------+----------------+-------------+-----------------+--------------+-----------+----------------+---------------------+---------------------+------------+--------------------+----------+----------------+---------+\n| datetimedemo | InnoDB | 10 | Dynamic | 0 | 0 | 16384 | 0 | 0 | 0 | NULL | 2018-12-05 09:22:54 | NULL | NULL | utf8mb4_0900_ai_ci | NULL | | |\n| primarydemo | InnoDB | 10 | Dynamic | 0 | 0 | 16384 | 0 | 0 | 0 | NULL | 2018-12-05 09:23:34 | NULL | NULL | utf8mb4_0900_ai_ci | NULL | | |\n| student | MyISAM | 10 | Dynamic | 0 | 0 | | 281474976710655 | 1024 | 0 | 1 | 2018-12-05 09:22:22 | 2018-12-05 09:22:23 | NULL | utf8mb4_0900_ai_ci | NULL | | |\n+--------------+--------+---------+------------+------+----------------+-------------+-----------------+--------------+-----------+----------------+---------------------+---------------------+------------+--------------------+----------+----------------+---------+\n3 rows in set (0.19 sec)" }, { "code": null, "e": 3414, "s": 3341, "text": "The following is the query to display engine type for a specific table −" }, { "code": null, "e": 3471, "s": 3414, "text": "mysql> show table status from sampletest Like 'student';" }, { "code": null, "e": 3551, "s": 3471, "text": "The following is the output that displays the engine for only “student” table −" }, { "code": null, "e": 4803, "s": 3551, "text": "+---------+--------+---------+------------+------+----------------+-------------+-----------------+--------------+-----------+----------------+---------------------+---------------------+------------+--------------------+----------+----------------+---------+\n| Name | Engine | Version | Row_format | Rows | Avg_row_length | Data_length | Max_data_length | Index_length | Data_free | Auto_increment | Create_time | Update_time | Check_time | Collation | Checksum | Create_options | Comment |\n+---------+--------+---------+------------+------+----------------+-------------+-----------------+--------------+-----------+----------------+---------------------+---------------------+------------+--------------------+----------+----------------+---------+\n| student | MyISAM | 10 | Dynamic | 0 | 0 | 0 | 281474976710655 | 1024 | 0 | 1 | 2018-12-05 09:22:22 | 2018-12-05 09:22:23 | NULL | utf8mb4_0900_ai_ci | NULL | | |\n+---------+--------+---------+------------+------+----------------+-------------+-----------------+--------------+-----------+----------------+---------------------+---------------------+------------+--------------------+----------+----------------+---------+\n1 row in set (0.00 sec)" } ]
Inference for Categorical Data with Python | Towards Data Science
In a series of weekly articles, I will cover some important statistics topics with a twist. The goal is to use Python to help us get intuition on complex concepts, empirically test theoretical proofs, or build algorithms from scratch. In this series, you will find articles covering topics such as random variables, sampling distributions, confidence intervals, significance tests, and more. At the end of each article, you can find exercises to test your knowledge. The solutions will be shared in the article of the following week. Articles published so far: Bernoulli and Binomial Random Variables with Python From Binomial to Geometric and Poisson Random Variables with Python Sampling Distribution of a Sample Proportion with Python Confidence Intervals with Python Significance Tests with Python Two-sample Inference for the Difference Between Groups with Python Inference for Categorical Data Advanced Regression Analysis of Variance — ANOVA As usual, the code is available on my GitHub. Let’s start by defining a standard normal distribution Random Variable (RV) X_1. To define our first Chi-square RV, we sample from our standard normal distribution X_1 and square the result. Since we are taking the sum of one standard normally distributed variable, we define the number of degrees of freedom of our Chi-square distribution to be one. To define a Chi-square RV with 2 degrees of freedom, we follow the same idea. This time we sample from two independently standard normally distributed RVs, take the square of the respective samples, and finally sum the result. from scipy.stats import norm, chi2import matplotlib.pyplot as pltimport mathimport numpy as npimport seaborn as snsfrom scipy import statsimport tabulateimport pandas as pdfrom IPython.display import HTML, displayimport tabulatemu = 0variance = 1sigma = math.sqrt(variance)x = np.linspace(mu - 3*sigma, mu + 3*sigma, 100)sns.lineplot(x = x, y = norm.pdf(x, loc=mu, scale=sigma)); norm_dist = stats.norm(0, 1)x1 = norm_dist.rvs(size=100000)**2x2 = norm_dist.rvs(size=100000)**2x3 = norm_dist.rvs(size=100000)**2x = [x1, x2, x3]_, ax = plt.subplots(1, 3, figsize=(18, 7))f = np.zeros(100000)for i in range(3): x_ = x[i] f += x_ ax[i].hist(f, 60, density=True, label=f'Sum of {i+1} standard Gaussian RV') d = np.arange(0, 10, .05) ax[i].plot(d, stats.chi2.pdf(d, df=i+1), color='r', lw=2, label='Chi-Square dist.') ax[i].set_xlim(0, 10) ax[i].set_title(f'Chi-Square dist. with df={i+1}') ax[i].legend() Rui works remotely for a tech company. He likes to work in coffee shops if the number of people is not too high. A new coffee shop opened recently, and he wanted to understand the distribution of customers per day of the week. This way, he would choose the days with smaller percentages to work there. Based on his experience of similar places, he draws the distribution of the number of customers for each day of the week. To test this assumption, for the next 3 months, he randomly chose one sample of each of the days of the week and recorded the observed number of customers. table = [["Day",'M','T', 'W', 'T', 'F', 'S', 'S'], ["Expected (%)",10,10, 10, 20, 30, 15, 5], ["Observed",30, 14, 34, 45, 57, 20, 10]]display(HTML(tabulate.tabulate(table, tablefmt='html'))) Before moving any further, we need to ensure that Chi-square goodness-of-fit test conditions are met. Let’s enumerate them first: The sample has to be random The expected number of each category of outcomes has to be greater or equal to 5 (also called the large count's condition) The samples are required to be independent. The rule of thumb is that if you are sampling without replacement, your sample size should be less than 10% of the population size We were told that Rui randomly chose each of the days of the week, so the first criteria was fulfilled. For the large count's condition, let’s calculate the number of expected customers per day of the week. n = 7 # number of days in a weekalpha = 0.05table = np.asarray(table)[1:,1:]table = table.astype(np.float32)table[0] = table[0]/100total_number_customers = np.sum(table[1])expected_num = table[0]*total_number_customerstable = np.concatenate((table, expected_num.reshape(1,-1)))table[2]array([ 26.460001, 64.26 , 85.049995, 107.729996, 37.8 , 18.9 ], dtype=float32) Notice that we do not have any value less than 5. Finally, we have the independence condition. Rui selected each day from a population of 3 months, which gives us 12 possible values for each category. This means that Rui sampled less than 10% of the population size, and we can assume independence even though he sampled without replacement. With this data, Rui defined the following hypothesis test: To start, he has to calculate a statistic that compares the estimated and the observed number of customers. It follows approximately a chi-square distribution. Using this statistic, he can calculate the probability of observing that specific value or values even more extreme given that the distribution based on similar places is correct. If this probability is smaller than the significance level (let’s use α=0.05), we can reject H_0 and thus, accept the alternative hypothesis that the new coffee shop has a distribution of customers per day different from the similar places considered by Rui. chi_sq_statistic = np.sum((table[2]-table[1])**2/table[2])chi_sq_statistic19.246035(1-chi2.cdf(chi_sq_statistic, df=n-1))<alphaTrueif (1-chi2.cdf(chi_sq_statistic, df=n-1))<alpha: print('Reject H_0')Reject H_0 We rejected H_0 based on the observations that Rui had been collecting, which consisted of the number of customers of the new coffee shop per day. The fact that we rejected H_0 means that the new place does not follow the assumed distribution defined by Rui based on his experience on similar places. A government agency wanted to know if the vaccines against Covid-19 currently being administered produce any effect against the new Delta variant. They separated the sample of people into 3 different groups: the first one took Pfizer’s vaccine, the second took Janssen, and the third took a placebo. table = [['Sick', 15, 10, 30],['Not sick', 100, 110, 90]]alpha = 0.05df = pd.DataFrame(table)df.columns = ['Effect', 'Pfizer', 'Janssen', 'Placebo']df = df.set_index('Effect')df Let’s define our hypothesis test: Like in any hypothesis test, we will assume the null hypothesis as true and calculate the likelihood of getting the data collected above. If it is lower than the significance level, we reject the null hypothesis. arr = df.to_numpy()arr = np.concatenate((arr, (arr.sum(axis=1)[0]/arr.sum() * arr.sum(axis=0)).reshape(1,-1)))arr = np.concatenate((arr, (arr.sum(axis=1)[1]/arr.sum() * arr.sum(axis=0)).reshape(1,-1)))arrarray([[ 15. , 10. , 30. ], [100. , 110. , 90. ], [ 17.81690141, 18.5915493 , 18.5915493 ], [ 97.18309859, 101.4084507 , 101.4084507 ]])chi_sq_statistic = np.sum((arr[2] - arr[0])**2/arr[2]) + np.sum((arr[3] - arr[1])**2/arr[3]) The number of degrees of freedom that we should use equals the number of rows of our table minus one times the number of columns minus one. print('P-value = ' + str(np.round(1-chi2.cdf(chi_sq_statistic, df =2*1), 4)))P-value = 0.0012if 1-chi2.cdf(chi_sq_statistic, df =2*1) < alpha: print('Reject H_0')Reject H_0 We reject H_0, meaning that the vaccines produced some effect and impacted the number of sick people in our experiment. The same agency decided to test Pfizer’s vaccine, but the goal was to test the effect on men and women this time. This is a homogeneity test, which can be translated to the following hypothesis: table = [['Sick', 25, 12],['Not sick', 92, 88]]alpha = 0.05df = pd.DataFrame(table)df.columns = ['Effect', 'Men', 'Women']df = df.set_index('Effect')df arr = df.to_numpy()arr = np.concatenate((arr, (arr.sum(axis=1)[0]/arr.sum() * arr.sum(axis=0)).reshape(1,-1)))arr = np.concatenate((arr, (arr.sum(axis=1)[1]/arr.sum() * arr.sum(axis=0)).reshape(1,-1)))arrarray([[25. , 12. ], [92. , 88. ], [19.94930876, 17.05069124], [97.05069124, 82.94930876]])chi_sq_statistic = np.sum((arr[2] - arr[0])**2/arr[2]) + np.sum((arr[3] - arr[1])**2/arr[3])print('P-value = ' + str(np.round(1-chi2.cdf(chi_sq_statistic, df =1*1), 4)))P-value = 0.0674if 1-chi2.cdf(chi_sq_statistic, df =1*1) < alpha: print('Reject H_0')else: print('Fail to reject H_0')Fail to reject H_0 Notice that despite the probability of observing these values or even more extreme values being quite low (about 6.7%), we failed to reject H_0. It means that we do not have enough evidence to state that there is a difference in the effect of the vaccine on men and women. Finally, let’s build a chi-squared test for the association between two variables. In this case, we want to test if there is an association between a surfer’s height X and the maximum wave size he ever surfed Y. Notice that this particular test uses a random sample of a single population. table = [['x<1.6m', 25, 22, 28],['1.6m<=x<1.9m', 10, 21, 35], ['x>=1.9m', 5, 10, 34]]alpha = 0.05df = pd.DataFrame(table)df.columns = ['height', 'y<2m', '2m<=y<4m', 'y>=4m']df = df.set_index('height')df arr = df.to_numpy()for i in range(arr.shape[0]): arr = np.concatenate((arr, (arr.sum(axis=1)[i]/arr.sum() * arr.sum(axis=0)).reshape(1,-1)))arrarray([[25. , 22. , 28. ], [10. , 21. , 35. ], [ 5. , 10. , 34. ], [15.78947368, 20.92105263, 38.28947368], [13.89473684, 18.41052632, 33.69473684], [10.31578947, 13.66842105, 25.01578947]])chi_sq_statistic = np.sum((arr[3] - arr[0])**2/arr[3]) + np.sum((arr[4] - arr[1])**2/arr[4]) + np.sum((arr[5] - arr[2])**2/arr[5])print('P-value = ' + str(np.round(1-chi2.cdf(chi_sq_statistic, df =2*2), 4)))P-value = 0.0023if 1-chi2.cdf(chi_sq_statistic, df =2*2) < alpha: print('Reject H_0')else: print('Fail to reject H_0')Reject H_0 We reject H_0, i.e., there is evidence of an association between the surfer’s height and maximum wave size. This article covered part of the family of chi-square tests. They are useful to test hypotheses about distributions of categorical data. We assessed good-of-fit tests, where the sample data is tested to see if it fits a hypothesis distribution. We also saw different types of independence tests between two variables. In cases where we sampled our data from two different populations, we test homogeneity. In cases where we sampled from a single population, we test the association between the variables. You will get the solutions in next week’s article. According to a distributor of surfboards, 66% of the boards are common, 25% are uncommon, and 9% are rare. José wondered if the rarity levels of the boards he and his friends owned followed this distribution, so he took a random sample of 500 boards and recorded their rarity levels. The results are presented in the table below. Carry out a goodness-of-fit test to determine if the distribution of rarity levels of surfboards José and his friends own disagrees with the claimed percentages. According to a distributor of surfboards, 66% of the boards are common, 25% are uncommon, and 9% are rare. José wondered if the rarity levels of the boards he and his friends owned followed this distribution, so he took a random sample of 500 boards and recorded their rarity levels. The results are presented in the table below. Carry out a goodness-of-fit test to determine if the distribution of rarity levels of surfboards José and his friends own disagrees with the claimed percentages. table = [['Cards', 345, 125, 30]]alpha = 0.05df = pd.DataFrame(table)df.columns = ['Rarity level', 'Common', 'Uncommon', 'Rare']df = df.set_index('Rarity level')df Physicians hypothesized that the mean time spent in the hospital due to Covid-19 before and after the vaccine changed. A group of 1,000 patients was randomized between a treatment group and a control group. The treatment group had already taken the vaccine, while the control group did not. The results show that the treatment group's mean time spent in the hospital was 10 days less than the time spent by the control group. The table below summarizes the results for the 1,000 re-randomizations of the data. Based on the data, what is the probability that the treatment group’s mean is smaller than the one from the control group by 10 days or more? What can you conclude from the experiment’s result (assuming a 5% significance level)? Physicians hypothesized that the mean time spent in the hospital due to Covid-19 before and after the vaccine changed. A group of 1,000 patients was randomized between a treatment group and a control group. The treatment group had already taken the vaccine, while the control group did not. The results show that the treatment group's mean time spent in the hospital was 10 days less than the time spent by the control group. The table below summarizes the results for the 1,000 re-randomizations of the data. Based on the data, what is the probability that the treatment group’s mean is smaller than the one from the control group by 10 days or more? What can you conclude from the experiment’s result (assuming a 5% significance level)? diff = [[-17.5,1],[-15.0, 6],[-12.5, 15],[-10.0, 41],[-7.5, 82],[-5.0, 43],[-2.5, 150],[0., 167],[2.5, 132],[5.0, 127],[7.5, 173],[10.0, 38],[12.5, 18],[15.0, 6],[17.5, 1]]plt.bar(x = np.asarray(diff)[:,0], height = np.asarray(diff)[:,1], width=2, color='C0')plt.bar(x = np.asarray(diff)[:4,0], height = np.asarray(diff)[:4,1], width=2, color='C1'); diff = np.asarray(diff)np.sum(diff[diff[:,0]<=-10][:,1])/np.sum(diff[:,1]) < 0.05False Based on the significance level of 5%, the result is not significant. The difference that was measured in the experiment could have resulted from random chance alone.
[ { "code": null, "e": 139, "s": 47, "text": "In a series of weekly articles, I will cover some important statistics topics with a twist." }, { "code": null, "e": 439, "s": 139, "text": "The goal is to use Python to help us get intuition on complex concepts, empirically test theoretical proofs, or build algorithms from scratch. In this series, you will find articles covering topics such as random variables, sampling distributions, confidence intervals, significance tests, and more." }, { "code": null, "e": 581, "s": 439, "text": "At the end of each article, you can find exercises to test your knowledge. The solutions will be shared in the article of the following week." }, { "code": null, "e": 608, "s": 581, "text": "Articles published so far:" }, { "code": null, "e": 660, "s": 608, "text": "Bernoulli and Binomial Random Variables with Python" }, { "code": null, "e": 728, "s": 660, "text": "From Binomial to Geometric and Poisson Random Variables with Python" }, { "code": null, "e": 785, "s": 728, "text": "Sampling Distribution of a Sample Proportion with Python" }, { "code": null, "e": 818, "s": 785, "text": "Confidence Intervals with Python" }, { "code": null, "e": 849, "s": 818, "text": "Significance Tests with Python" }, { "code": null, "e": 916, "s": 849, "text": "Two-sample Inference for the Difference Between Groups with Python" }, { "code": null, "e": 947, "s": 916, "text": "Inference for Categorical Data" }, { "code": null, "e": 967, "s": 947, "text": "Advanced Regression" }, { "code": null, "e": 996, "s": 967, "text": "Analysis of Variance — ANOVA" }, { "code": null, "e": 1042, "s": 996, "text": "As usual, the code is available on my GitHub." }, { "code": null, "e": 1123, "s": 1042, "text": "Let’s start by defining a standard normal distribution Random Variable (RV) X_1." }, { "code": null, "e": 1620, "s": 1123, "text": "To define our first Chi-square RV, we sample from our standard normal distribution X_1 and square the result. Since we are taking the sum of one standard normally distributed variable, we define the number of degrees of freedom of our Chi-square distribution to be one. To define a Chi-square RV with 2 degrees of freedom, we follow the same idea. This time we sample from two independently standard normally distributed RVs, take the square of the respective samples, and finally sum the result." }, { "code": null, "e": 2000, "s": 1620, "text": "from scipy.stats import norm, chi2import matplotlib.pyplot as pltimport mathimport numpy as npimport seaborn as snsfrom scipy import statsimport tabulateimport pandas as pdfrom IPython.display import HTML, displayimport tabulatemu = 0variance = 1sigma = math.sqrt(variance)x = np.linspace(mu - 3*sigma, mu + 3*sigma, 100)sns.lineplot(x = x, y = norm.pdf(x, loc=mu, scale=sigma));" }, { "code": null, "e": 2548, "s": 2000, "text": "norm_dist = stats.norm(0, 1)x1 = norm_dist.rvs(size=100000)**2x2 = norm_dist.rvs(size=100000)**2x3 = norm_dist.rvs(size=100000)**2x = [x1, x2, x3]_, ax = plt.subplots(1, 3, figsize=(18, 7))f = np.zeros(100000)for i in range(3): x_ = x[i] f += x_ ax[i].hist(f, 60, density=True, label=f'Sum of {i+1} standard Gaussian RV') d = np.arange(0, 10, .05) ax[i].plot(d, stats.chi2.pdf(d, df=i+1), color='r', lw=2, label='Chi-Square dist.') ax[i].set_xlim(0, 10) ax[i].set_title(f'Chi-Square dist. with df={i+1}') ax[i].legend()" }, { "code": null, "e": 3128, "s": 2548, "text": "Rui works remotely for a tech company. He likes to work in coffee shops if the number of people is not too high. A new coffee shop opened recently, and he wanted to understand the distribution of customers per day of the week. This way, he would choose the days with smaller percentages to work there. Based on his experience of similar places, he draws the distribution of the number of customers for each day of the week. To test this assumption, for the next 3 months, he randomly chose one sample of each of the days of the week and recorded the observed number of customers." }, { "code": null, "e": 3335, "s": 3128, "text": "table = [[\"Day\",'M','T', 'W', 'T', 'F', 'S', 'S'], [\"Expected (%)\",10,10, 10, 20, 30, 15, 5], [\"Observed\",30, 14, 34, 45, 57, 20, 10]]display(HTML(tabulate.tabulate(table, tablefmt='html')))" }, { "code": null, "e": 3465, "s": 3335, "text": "Before moving any further, we need to ensure that Chi-square goodness-of-fit test conditions are met. Let’s enumerate them first:" }, { "code": null, "e": 3493, "s": 3465, "text": "The sample has to be random" }, { "code": null, "e": 3616, "s": 3493, "text": "The expected number of each category of outcomes has to be greater or equal to 5 (also called the large count's condition)" }, { "code": null, "e": 3791, "s": 3616, "text": "The samples are required to be independent. The rule of thumb is that if you are sampling without replacement, your sample size should be less than 10% of the population size" }, { "code": null, "e": 3998, "s": 3791, "text": "We were told that Rui randomly chose each of the days of the week, so the first criteria was fulfilled. For the large count's condition, let’s calculate the number of expected customers per day of the week." }, { "code": null, "e": 4384, "s": 3998, "text": "n = 7 # number of days in a weekalpha = 0.05table = np.asarray(table)[1:,1:]table = table.astype(np.float32)table[0] = table[0]/100total_number_customers = np.sum(table[1])expected_num = table[0]*total_number_customerstable = np.concatenate((table, expected_num.reshape(1,-1)))table[2]array([ 26.460001, 64.26 , 85.049995, 107.729996, 37.8 , 18.9 ], dtype=float32)" }, { "code": null, "e": 4726, "s": 4384, "text": "Notice that we do not have any value less than 5. Finally, we have the independence condition. Rui selected each day from a population of 3 months, which gives us 12 possible values for each category. This means that Rui sampled less than 10% of the population size, and we can assume independence even though he sampled without replacement." }, { "code": null, "e": 4785, "s": 4726, "text": "With this data, Rui defined the following hypothesis test:" }, { "code": null, "e": 5384, "s": 4785, "text": "To start, he has to calculate a statistic that compares the estimated and the observed number of customers. It follows approximately a chi-square distribution. Using this statistic, he can calculate the probability of observing that specific value or values even more extreme given that the distribution based on similar places is correct. If this probability is smaller than the significance level (let’s use α=0.05), we can reject H_0 and thus, accept the alternative hypothesis that the new coffee shop has a distribution of customers per day different from the similar places considered by Rui." }, { "code": null, "e": 5597, "s": 5384, "text": "chi_sq_statistic = np.sum((table[2]-table[1])**2/table[2])chi_sq_statistic19.246035(1-chi2.cdf(chi_sq_statistic, df=n-1))<alphaTrueif (1-chi2.cdf(chi_sq_statistic, df=n-1))<alpha: print('Reject H_0')Reject H_0" }, { "code": null, "e": 5898, "s": 5597, "text": "We rejected H_0 based on the observations that Rui had been collecting, which consisted of the number of customers of the new coffee shop per day. The fact that we rejected H_0 means that the new place does not follow the assumed distribution defined by Rui based on his experience on similar places." }, { "code": null, "e": 6198, "s": 5898, "text": "A government agency wanted to know if the vaccines against Covid-19 currently being administered produce any effect against the new Delta variant. They separated the sample of people into 3 different groups: the first one took Pfizer’s vaccine, the second took Janssen, and the third took a placebo." }, { "code": null, "e": 6376, "s": 6198, "text": "table = [['Sick', 15, 10, 30],['Not sick', 100, 110, 90]]alpha = 0.05df = pd.DataFrame(table)df.columns = ['Effect', 'Pfizer', 'Janssen', 'Placebo']df = df.set_index('Effect')df" }, { "code": null, "e": 6410, "s": 6376, "text": "Let’s define our hypothesis test:" }, { "code": null, "e": 6623, "s": 6410, "text": "Like in any hypothesis test, we will assume the null hypothesis as true and calculate the likelihood of getting the data collected above. If it is lower than the significance level, we reject the null hypothesis." }, { "code": null, "e": 7121, "s": 6623, "text": "arr = df.to_numpy()arr = np.concatenate((arr, (arr.sum(axis=1)[0]/arr.sum() * arr.sum(axis=0)).reshape(1,-1)))arr = np.concatenate((arr, (arr.sum(axis=1)[1]/arr.sum() * arr.sum(axis=0)).reshape(1,-1)))arrarray([[ 15. , 10. , 30. ], [100. , 110. , 90. ], [ 17.81690141, 18.5915493 , 18.5915493 ], [ 97.18309859, 101.4084507 , 101.4084507 ]])chi_sq_statistic = np.sum((arr[2] - arr[0])**2/arr[2]) + np.sum((arr[3] - arr[1])**2/arr[3])" }, { "code": null, "e": 7261, "s": 7121, "text": "The number of degrees of freedom that we should use equals the number of rows of our table minus one times the number of columns minus one." }, { "code": null, "e": 7437, "s": 7261, "text": "print('P-value = ' + str(np.round(1-chi2.cdf(chi_sq_statistic, df =2*1), 4)))P-value = 0.0012if 1-chi2.cdf(chi_sq_statistic, df =2*1) < alpha: print('Reject H_0')Reject H_0" }, { "code": null, "e": 7557, "s": 7437, "text": "We reject H_0, meaning that the vaccines produced some effect and impacted the number of sick people in our experiment." }, { "code": null, "e": 7671, "s": 7557, "text": "The same agency decided to test Pfizer’s vaccine, but the goal was to test the effect on men and women this time." }, { "code": null, "e": 7752, "s": 7671, "text": "This is a homogeneity test, which can be translated to the following hypothesis:" }, { "code": null, "e": 7904, "s": 7752, "text": "table = [['Sick', 25, 12],['Not sick', 92, 88]]alpha = 0.05df = pd.DataFrame(table)df.columns = ['Effect', 'Men', 'Women']df = df.set_index('Effect')df" }, { "code": null, "e": 8557, "s": 7904, "text": "arr = df.to_numpy()arr = np.concatenate((arr, (arr.sum(axis=1)[0]/arr.sum() * arr.sum(axis=0)).reshape(1,-1)))arr = np.concatenate((arr, (arr.sum(axis=1)[1]/arr.sum() * arr.sum(axis=0)).reshape(1,-1)))arrarray([[25. , 12. ], [92. , 88. ], [19.94930876, 17.05069124], [97.05069124, 82.94930876]])chi_sq_statistic = np.sum((arr[2] - arr[0])**2/arr[2]) + np.sum((arr[3] - arr[1])**2/arr[3])print('P-value = ' + str(np.round(1-chi2.cdf(chi_sq_statistic, df =1*1), 4)))P-value = 0.0674if 1-chi2.cdf(chi_sq_statistic, df =1*1) < alpha: print('Reject H_0')else: print('Fail to reject H_0')Fail to reject H_0" }, { "code": null, "e": 8830, "s": 8557, "text": "Notice that despite the probability of observing these values or even more extreme values being quite low (about 6.7%), we failed to reject H_0. It means that we do not have enough evidence to state that there is a difference in the effect of the vaccine on men and women." }, { "code": null, "e": 9120, "s": 8830, "text": "Finally, let’s build a chi-squared test for the association between two variables. In this case, we want to test if there is an association between a surfer’s height X and the maximum wave size he ever surfed Y. Notice that this particular test uses a random sample of a single population." }, { "code": null, "e": 9323, "s": 9120, "text": "table = [['x<1.6m', 25, 22, 28],['1.6m<=x<1.9m', 10, 21, 35], ['x>=1.9m', 5, 10, 34]]alpha = 0.05df = pd.DataFrame(table)df.columns = ['height', 'y<2m', '2m<=y<4m', 'y>=4m']df = df.set_index('height')df" }, { "code": null, "e": 10094, "s": 9323, "text": "arr = df.to_numpy()for i in range(arr.shape[0]): arr = np.concatenate((arr, (arr.sum(axis=1)[i]/arr.sum() * arr.sum(axis=0)).reshape(1,-1)))arrarray([[25. , 22. , 28. ], [10. , 21. , 35. ], [ 5. , 10. , 34. ], [15.78947368, 20.92105263, 38.28947368], [13.89473684, 18.41052632, 33.69473684], [10.31578947, 13.66842105, 25.01578947]])chi_sq_statistic = np.sum((arr[3] - arr[0])**2/arr[3]) + np.sum((arr[4] - arr[1])**2/arr[4]) + np.sum((arr[5] - arr[2])**2/arr[5])print('P-value = ' + str(np.round(1-chi2.cdf(chi_sq_statistic, df =2*2), 4)))P-value = 0.0023if 1-chi2.cdf(chi_sq_statistic, df =2*2) < alpha: print('Reject H_0')else: print('Fail to reject H_0')Reject H_0" }, { "code": null, "e": 10202, "s": 10094, "text": "We reject H_0, i.e., there is evidence of an association between the surfer’s height and maximum wave size." }, { "code": null, "e": 10707, "s": 10202, "text": "This article covered part of the family of chi-square tests. They are useful to test hypotheses about distributions of categorical data. We assessed good-of-fit tests, where the sample data is tested to see if it fits a hypothesis distribution. We also saw different types of independence tests between two variables. In cases where we sampled our data from two different populations, we test homogeneity. In cases where we sampled from a single population, we test the association between the variables." }, { "code": null, "e": 10758, "s": 10707, "text": "You will get the solutions in next week’s article." }, { "code": null, "e": 11252, "s": 10758, "text": "According to a distributor of surfboards, 66% of the boards are common, 25% are uncommon, and 9% are rare. José wondered if the rarity levels of the boards he and his friends owned followed this distribution, so he took a random sample of 500 boards and recorded their rarity levels. The results are presented in the table below. Carry out a goodness-of-fit test to determine if the distribution of rarity levels of surfboards José and his friends own disagrees with the claimed percentages." }, { "code": null, "e": 11746, "s": 11252, "text": "According to a distributor of surfboards, 66% of the boards are common, 25% are uncommon, and 9% are rare. José wondered if the rarity levels of the boards he and his friends owned followed this distribution, so he took a random sample of 500 boards and recorded their rarity levels. The results are presented in the table below. Carry out a goodness-of-fit test to determine if the distribution of rarity levels of surfboards José and his friends own disagrees with the claimed percentages." }, { "code": null, "e": 11910, "s": 11746, "text": "table = [['Cards', 345, 125, 30]]alpha = 0.05df = pd.DataFrame(table)df.columns = ['Rarity level', 'Common', 'Uncommon', 'Rare']df = df.set_index('Rarity level')df" }, { "code": null, "e": 12649, "s": 11910, "text": "Physicians hypothesized that the mean time spent in the hospital due to Covid-19 before and after the vaccine changed. A group of 1,000 patients was randomized between a treatment group and a control group. The treatment group had already taken the vaccine, while the control group did not. The results show that the treatment group's mean time spent in the hospital was 10 days less than the time spent by the control group. The table below summarizes the results for the 1,000 re-randomizations of the data. Based on the data, what is the probability that the treatment group’s mean is smaller than the one from the control group by 10 days or more? What can you conclude from the experiment’s result (assuming a 5% significance level)?" }, { "code": null, "e": 13388, "s": 12649, "text": "Physicians hypothesized that the mean time spent in the hospital due to Covid-19 before and after the vaccine changed. A group of 1,000 patients was randomized between a treatment group and a control group. The treatment group had already taken the vaccine, while the control group did not. The results show that the treatment group's mean time spent in the hospital was 10 days less than the time spent by the control group. The table below summarizes the results for the 1,000 re-randomizations of the data. Based on the data, what is the probability that the treatment group’s mean is smaller than the one from the control group by 10 days or more? What can you conclude from the experiment’s result (assuming a 5% significance level)?" }, { "code": null, "e": 13738, "s": 13388, "text": "diff = [[-17.5,1],[-15.0, 6],[-12.5, 15],[-10.0, 41],[-7.5, 82],[-5.0, 43],[-2.5, 150],[0., 167],[2.5, 132],[5.0, 127],[7.5, 173],[10.0, 38],[12.5, 18],[15.0, 6],[17.5, 1]]plt.bar(x = np.asarray(diff)[:,0], height = np.asarray(diff)[:,1], width=2, color='C0')plt.bar(x = np.asarray(diff)[:4,0], height = np.asarray(diff)[:4,1], width=2, color='C1');" }, { "code": null, "e": 13825, "s": 13738, "text": "diff = np.asarray(diff)np.sum(diff[diff[:,0]<=-10][:,1])/np.sum(diff[:,1]) < 0.05False" } ]
Block swap algorithm for array rotation - GeeksforGeeks
10 Mar, 2022 Write a function rotate(ar[], d, n) that rotates arr[] of size n by d elements. Rotation of the above array by 2 will make array Algorithm : Initialize A = arr[0..d-1] and B = arr[d..n-1] 1) Do following until size of A is equal to size of B a) If A is shorter, divide B into Bl and Br such that Br is of same length as A. Swap A and Br to change ABlBr into BrBlA. Now A is at its final place, so recur on pieces of B. b) If A is longer, divide A into Al and Ar such that Al is of same length as B Swap Al and B to change AlArB into BArAl. Now B is at its final place, so recur on pieces of A. 2) Finally when A and B are of equal size, block swap them. Recursive Implementation: C++ C Java Python3 C# Javascript #include <bits/stdc++.h>using namespace std; /*Prototype for utility functions */void printArray(int arr[], int size);void swap(int arr[], int fi, int si, int d); void leftRotate(int arr[], int d, int n){ /* Return If number of elements to be rotated is zero or equal to array size */ if(d == 0 || d == n) return; /* If number of elements to be rotated is more than array size*/ if(d > n) d = d % n; /*If number of elements to be rotated is exactly half of array size */ if(n - d == d) { swap(arr, 0, n - d, d); return; } /* If A is shorter*/ if(d < n - d) { swap(arr, 0, n - d, d); leftRotate(arr, d, n - d); } else /* If B is shorter*/ { swap(arr, 0, d, n - d); leftRotate(arr + n - d, 2 * d - n, d); /*This is tricky*/ }} /*UTILITY FUNCTIONS*//* function to print an array */void printArray(int arr[], int size){ int i; for(i = 0; i < size; i++) cout << arr[i] << " "; cout << endl;} /*This function swaps d elements starting at index fiwith d elements starting at index si */void swap(int arr[], int fi, int si, int d){ int i, temp; for(i = 0; i < d; i++) { temp = arr[fi + i]; arr[fi + i] = arr[si + i]; arr[si + i] = temp; }} // Driver Codeint main(){ int arr[] = {1, 2, 3, 4, 5, 6, 7}; leftRotate(arr, 2, 7); printArray(arr, 7); return 0;} // This code is contributed by rathbhupendra #include<stdio.h> /*Prototype for utility functions */void printArray(int arr[], int size);void swap(int arr[], int fi, int si, int d); void leftRotate(int arr[], int d, int n){ /* Return If number of elements to be rotated is zero or equal to array size */ if(d == 0 || d == n) return; /*If number of elements to be rotated is exactly half of array size */ if(n-d == d) { swap(arr, 0, n-d, d); return; } /* If A is shorter*/ if(d < n-d) { swap(arr, 0, n-d, d); leftRotate(arr, d, n-d); } else /* If B is shorter*/ { swap(arr, 0, d, n-d); leftRotate(arr+n-d, 2*d-n, d); /*This is tricky*/ }} /*UTILITY FUNCTIONS*//* function to print an array */void printArray(int arr[], int size){ int i; for(i = 0; i < size; i++) printf("%d ", arr[i]); printf("\n ");} /*This function swaps d elements starting at index fi with d elements starting at index si */void swap(int arr[], int fi, int si, int d){ int i, temp; for(i = 0; i<d; i++) { temp = arr[fi + i]; arr[fi + i] = arr[si + i]; arr[si + i] = temp; } } /* Driver program to test above functions */int main(){ int arr[] = {1, 2, 3, 4, 5, 6, 7}; leftRotate(arr, 2, 7); printArray(arr, 7); getchar(); return 0;} import java.util.*; class GFG{ // Wrapper over the recursive function leftRotateRec() // It left rotates arr[] by d. public static void leftRotate(int arr[], int d, int n) { leftRotateRec(arr, 0, d, n); } public static void leftRotateRec(int arr[], int i, int d, int n) { /* Return If number of elements to be rotated is zero or equal to array size */ if(d == 0 || d == n) return; /*If number of elements to be rotated is exactly half of array size */ if(n - d == d) { swap(arr, i, n - d + i, d); return; } /* If A is shorter*/ if(d < n - d) { swap(arr, i, n - d + i, d); leftRotateRec(arr, i, d, n - d); } else /* If B is shorter*/ { swap(arr, i, d, n - d); leftRotateRec(arr, n - d + i, 2 * d - n, d); /*This is tricky*/ } } /*UTILITY FUNCTIONS*//* function to print an array */public static void printArray(int arr[], int size){ int i; for(i = 0; i < size; i++) System.out.print(arr[i] + " "); System.out.println();} /*This function swaps d elementsstarting at index fi with d elementsstarting at index si */public static void swap(int arr[], int fi, int si, int d){ int i, temp; for(i = 0; i < d; i++) { temp = arr[fi + i]; arr[fi + i] = arr[si + i]; arr[si + i] = temp; }} // Driver Codepublic static void main (String[] args){ int arr[] = {1, 2, 3, 4, 5, 6, 7}; leftRotate(arr, 2, 7); printArray(arr, 7); }} // This code is contributed by codeseeker # Wrapper over the recursive function leftRotateRec()# It left rotates arr by d.def leftRotate(arr, d, n): leftRotateRec(arr, 0, d, n); def leftRotateRec(arr, i, d, n): ''' * Return If number of elements to be rotated is zero or equal to array size ''' if (d == 0 or d == n): return; ''' * If number of elements to be rotated is exactly half of array size ''' if (n - d == d): swap(arr, i, n - d + i, d); return; ''' If A is shorter ''' if (d < n - d): swap(arr, i, n - d + i, d); leftRotateRec(arr, i, d, n - d); ''' If B is shorter ''' else: swap(arr, i, d, n - d); ''' This is tricky ''' leftRotateRec(arr, n - d + i, 2 * d - n, d); ''' UTILITY FUNCTIONS '''''' function to print an array '''def printArray(arr, size): for i in range(size): print(arr[i], end = " "); print(); ''' * This function swaps d elements starting at * index fi with d elements starting at index si '''def swap(arr, fi, si, d): for i in range(d): temp = arr[fi + i]; arr[fi + i] = arr[si + i]; arr[si + i] = temp; # Driver Codeif __name__ == '__main__': arr = [1, 2, 3, 4, 5, 6, 7]; leftRotate(arr, 2, 7); printArray(arr, 7); # This code is contributed by Rohit_ranjan using System; class GFG{ // Wrapper over the recursive function// leftRotateRec()// It left rotates []arr by d.public static void leftRotate(int []arr, int d, int n){ leftRotateRec(arr, 0, d, n);} public static void leftRotateRec(int []arr, int i, int d, int n){ // Return If number of elements // to be rotated is zero or equal // to array size if(d == 0 || d == n) return; // If number of elements to be rotated // is exactly half of array size if(n - d == d) { swap(arr, i, n - d + i, d); return; } // If A is shorter if(d < n - d) { swap(arr, i, n - d + i, d); leftRotateRec(arr, i, d, n - d); } // If B is shorter else { swap(arr, i, d, n - d); // This is tricky leftRotateRec(arr, n - d + i, 2 * d - n, d); }} // UTILITY FUNCTIONS// Function to print an arraypublic static void printArray(int []arr, int size){ int i; for(i = 0; i < size; i++) Console.Write(arr[i] + " "); Console.WriteLine();} // This function swaps d elements// starting at index fi with d elements// starting at index sipublic static void swap(int []arr, int fi, int si, int d){ int i, temp; for(i = 0; i < d; i++) { temp = arr[fi + i]; arr[fi + i] = arr[si + i]; arr[si + i] = temp; }} // Driver Codepublic static void Main(String[] args){ int []arr = { 1, 2, 3, 4, 5, 6, 7 }; leftRotate(arr, 2, 7); printArray(arr, 7); }} // This code is contributed by amal kumar choubey <script> let leftRotate = (arr, d, n) =>{ /* Return If number of elements to be rotated is zero or equal to array size */ if(d == 0 || d == n) return; /*If number of elements to be rotated is exactly half of array size */ if(n - d == d) { arr = swap(arr, 0, n - d, d); return; } /* If A is shorter*/ if(d < n - d) { arr = swap(arr, 0, n - d, d); leftRotate(arr, d, n - d); } else{ /* If B is shorter*/ arr = swap(arr, 0, d, n - d); /*This is tricky*/ leftRotate(arr + n - d, 2 * d - n, d); }} /*UTILITY FUNCTIONS*//* function to print an array */let printArray = (arr, size) =>{ ans = '' for(let i = 0; i < size; i++) ans += arr[i]+" "; document.write(ans)} /*This function swaps d elementsstarting at index fiwith d elements starting at index si */let swap = (arr, fi, si, d) =>{ for(let i = 0; i < d; i++) { let temp = arr[fi + i]; arr[fi + i] = arr[si + i]; arr[si + i] = temp; } return arr} // Driver Codearr = [1, 2, 3, 4, 5, 6, 7];leftRotate(arr, 2, 7);printArray(arr, 7); </script> 3 4 5 6 7 1 2 Iterative Implementation: Here is iterative implementation of the same algorithm. Same utility function swap() is used here. C++ C Java Python3 C# Javascript // C++ code for above implementationvoid leftRotate(int arr[], int d, int n){ int i, j; if (d == 0 || d == n) return; /* If number of elements to be rotated is more than array size*/ if(d > n) d = d % n; i = d; j = n - d; while (i != j) { if (i < j) /*A is shorter*/ { swap(arr, d - i, d + j - i, i); j -= i; } else /*B is shorter*/ { swap(arr, d - i, d, j); i -= j; } // printArray(arr, 7); } /*Finally, block swap A and B*/ swap(arr, d - i, d, i);} // This code is contributed by Shivani // C code for above implementationvoid leftRotate(int arr[], int d, int n){ int i, j; if(d == 0 || d == n) return; /* If number of elements to be rotated is more than array size*/ if(d > n) d = d % n; i = d; j = n - d; while (i != j) { if(i < j) /*A is shorter*/ { swap(arr, d-i, d+j-i, i); j -= i; } else /*B is shorter*/ { swap(arr, d-i, d, j); i -= j; } // printArray(arr, 7); } /*Finally, block swap A and B*/ swap(arr, d-i, d, i);} //Java code for above implementationstatic void leftRotate(int arr[], int d, int n){int i, j;if(d == 0 || d == n) return;/* If number of elements to be rotated is more than array size*/ if(d > n) d = d % n;i = d;j = n - d;while (i != j){ if(i < j) /*A is shorter*/ { swap(arr, d-i, d+j-i, i); j -= i; } else /*B is shorter*/ { swap(arr, d-i, d, j); i -= j; } // printArray(arr, 7);}/*Finally, block swap A and B*/swap(arr, d-i, d, i);} # Python3 code for above implementation def leftRotate(arr, d, n): if(d == 0 or d == n): return; i = d j = n - d while (i != j): if(i < j): # A is shorter swap(arr, d - i, d + j - i, i) j -= i else: # B is shorter swap(arr, d - i, d, j) i -= j swap(arr, d - i, d, i) # This code is contributed# by Adarsh_Verma // C# code for above implementationstatic void leftRotate(int []arr, int d, int n){ int i, j; if(d == 0 || d == n) return; /* If number of elements to be rotated is more than array size*/ if(d > n) d = d % n; i = d; j = n - d; while (i != j) { if(i < j) /*A is shorter*/ { swap(arr, d-i, d+j-i, i); j -= i; } else /*B is shorter*/ { swap(arr, d-i, d, j); i -= j; } } /*Finally, block swap A and B*/ swap(arr, d-i, d, i);} // This code is contributed by Rajput-Ji <script>// JavaScript code for above implementationfunction leftRotate(arr, d, n){ if(d == 0 || d == n) return; let i = d; let j = n - d; while (i != j) { if(i < j) { // A is shorter arr = swap(arr, d - i, d + j - i, i); j -= i; } else{ // B is shorter arr = swap(arr, d - i, d, j); i -= j; } } arr = swap(arr, d - i, d, i); // This code is contributed by rohitsingh04052.}</script> Time Complexity: O(n) Auxiliary Space: O(1)Please see following posts for other methods of array rotation: https://www.geeksforgeeks.org/array-rotation/ https://www.geeksforgeeks.org/program-for-array-rotation-continued-reversal-algorithm/ References: http://www.cs.bell-labs.com/cm/cs/pearls/s02b.pdfPlease write comments if you find any bug in the above programs/algorithms or want to share any additional information about the block swap algorithm. AbhijeetPal prerna saini Adarsh_Verma Rajput-Ji rathbhupendra CodeSeeker Amal Kumar Choubey Rohit_ranjan rohitsingh07052 shivanisinghss2110 yashguptaindianera5 mahmady173 surinderdawra388 rishavnitro rotation Arrays Arrays 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 Largest Sum Contiguous Subarray Multidimensional Arrays in Java Linear Search Python | Using 2D arrays/lists the right way Find the Missing Number Subset Sum Problem | DP-25 Array of Strings in C++ (5 Different Ways to Create) Find Second largest element in an array
[ { "code": null, "e": 37760, "s": 37732, "text": "\n10 Mar, 2022" }, { "code": null, "e": 37841, "s": 37760, "text": "Write a function rotate(ar[], d, n) that rotates arr[] of size n by d elements. " }, { "code": null, "e": 37890, "s": 37841, "text": "Rotation of the above array by 2 will make array" }, { "code": null, "e": 37903, "s": 37890, "text": "Algorithm : " }, { "code": null, "e": 38459, "s": 37903, "text": "Initialize A = arr[0..d-1] and B = arr[d..n-1]\n1) Do following until size of A is equal to size of B\n\n a) If A is shorter, divide B into Bl and Br such that Br is of same \n length as A. Swap A and Br to change ABlBr into BrBlA. Now A\n is at its final place, so recur on pieces of B. \n\n b) If A is longer, divide A into Al and Ar such that Al is of same \n length as B Swap Al and B to change AlArB into BArAl. Now B\n is at its final place, so recur on pieces of A.\n\n2) Finally when A and B are of equal size, block swap them." }, { "code": null, "e": 38485, "s": 38459, "text": "Recursive Implementation:" }, { "code": null, "e": 38489, "s": 38485, "text": "C++" }, { "code": null, "e": 38491, "s": 38489, "text": "C" }, { "code": null, "e": 38496, "s": 38491, "text": "Java" }, { "code": null, "e": 38504, "s": 38496, "text": "Python3" }, { "code": null, "e": 38507, "s": 38504, "text": "C#" }, { "code": null, "e": 38518, "s": 38507, "text": "Javascript" }, { "code": "#include <bits/stdc++.h>using namespace std; /*Prototype for utility functions */void printArray(int arr[], int size);void swap(int arr[], int fi, int si, int d); void leftRotate(int arr[], int d, int n){ /* Return If number of elements to be rotated is zero or equal to array size */ if(d == 0 || d == n) return; /* If number of elements to be rotated is more than array size*/ if(d > n) d = d % n; /*If number of elements to be rotated is exactly half of array size */ if(n - d == d) { swap(arr, 0, n - d, d); return; } /* If A is shorter*/ if(d < n - d) { swap(arr, 0, n - d, d); leftRotate(arr, d, n - d); } else /* If B is shorter*/ { swap(arr, 0, d, n - d); leftRotate(arr + n - d, 2 * d - n, d); /*This is tricky*/ }} /*UTILITY FUNCTIONS*//* function to print an array */void printArray(int arr[], int size){ int i; for(i = 0; i < size; i++) cout << arr[i] << \" \"; cout << endl;} /*This function swaps d elements starting at index fiwith d elements starting at index si */void swap(int arr[], int fi, int si, int d){ int i, temp; for(i = 0; i < d; i++) { temp = arr[fi + i]; arr[fi + i] = arr[si + i]; arr[si + i] = temp; }} // Driver Codeint main(){ int arr[] = {1, 2, 3, 4, 5, 6, 7}; leftRotate(arr, 2, 7); printArray(arr, 7); return 0;} // This code is contributed by rathbhupendra", "e": 40006, "s": 38518, "text": null }, { "code": "#include<stdio.h> /*Prototype for utility functions */void printArray(int arr[], int size);void swap(int arr[], int fi, int si, int d); void leftRotate(int arr[], int d, int n){ /* Return If number of elements to be rotated is zero or equal to array size */ if(d == 0 || d == n) return; /*If number of elements to be rotated is exactly half of array size */ if(n-d == d) { swap(arr, 0, n-d, d); return; } /* If A is shorter*/ if(d < n-d) { swap(arr, 0, n-d, d); leftRotate(arr, d, n-d); } else /* If B is shorter*/ { swap(arr, 0, d, n-d); leftRotate(arr+n-d, 2*d-n, d); /*This is tricky*/ }} /*UTILITY FUNCTIONS*//* function to print an array */void printArray(int arr[], int size){ int i; for(i = 0; i < size; i++) printf(\"%d \", arr[i]); printf(\"\\n \");} /*This function swaps d elements starting at index fi with d elements starting at index si */void swap(int arr[], int fi, int si, int d){ int i, temp; for(i = 0; i<d; i++) { temp = arr[fi + i]; arr[fi + i] = arr[si + i]; arr[si + i] = temp; } } /* Driver program to test above functions */int main(){ int arr[] = {1, 2, 3, 4, 5, 6, 7}; leftRotate(arr, 2, 7); printArray(arr, 7); getchar(); return 0;} ", "e": 41298, "s": 40006, "text": null }, { "code": "import java.util.*; class GFG{ // Wrapper over the recursive function leftRotateRec() // It left rotates arr[] by d. public static void leftRotate(int arr[], int d, int n) { leftRotateRec(arr, 0, d, n); } public static void leftRotateRec(int arr[], int i, int d, int n) { /* Return If number of elements to be rotated is zero or equal to array size */ if(d == 0 || d == n) return; /*If number of elements to be rotated is exactly half of array size */ if(n - d == d) { swap(arr, i, n - d + i, d); return; } /* If A is shorter*/ if(d < n - d) { swap(arr, i, n - d + i, d); leftRotateRec(arr, i, d, n - d); } else /* If B is shorter*/ { swap(arr, i, d, n - d); leftRotateRec(arr, n - d + i, 2 * d - n, d); /*This is tricky*/ } } /*UTILITY FUNCTIONS*//* function to print an array */public static void printArray(int arr[], int size){ int i; for(i = 0; i < size; i++) System.out.print(arr[i] + \" \"); System.out.println();} /*This function swaps d elementsstarting at index fi with d elementsstarting at index si */public static void swap(int arr[], int fi, int si, int d){ int i, temp; for(i = 0; i < d; i++) { temp = arr[fi + i]; arr[fi + i] = arr[si + i]; arr[si + i] = temp; }} // Driver Codepublic static void main (String[] args){ int arr[] = {1, 2, 3, 4, 5, 6, 7}; leftRotate(arr, 2, 7); printArray(arr, 7); }} // This code is contributed by codeseeker", "e": 43060, "s": 41298, "text": null }, { "code": "# Wrapper over the recursive function leftRotateRec()# It left rotates arr by d.def leftRotate(arr, d, n): leftRotateRec(arr, 0, d, n); def leftRotateRec(arr, i, d, n): ''' * Return If number of elements to be rotated is zero or equal to array size ''' if (d == 0 or d == n): return; ''' * If number of elements to be rotated is exactly half of array size ''' if (n - d == d): swap(arr, i, n - d + i, d); return; ''' If A is shorter ''' if (d < n - d): swap(arr, i, n - d + i, d); leftRotateRec(arr, i, d, n - d); ''' If B is shorter ''' else: swap(arr, i, d, n - d); ''' This is tricky ''' leftRotateRec(arr, n - d + i, 2 * d - n, d); ''' UTILITY FUNCTIONS '''''' function to print an array '''def printArray(arr, size): for i in range(size): print(arr[i], end = \" \"); print(); ''' * This function swaps d elements starting at * index fi with d elements starting at index si '''def swap(arr, fi, si, d): for i in range(d): temp = arr[fi + i]; arr[fi + i] = arr[si + i]; arr[si + i] = temp; # Driver Codeif __name__ == '__main__': arr = [1, 2, 3, 4, 5, 6, 7]; leftRotate(arr, 2, 7); printArray(arr, 7); # This code is contributed by Rohit_ranjan", "e": 44374, "s": 43060, "text": null }, { "code": "using System; class GFG{ // Wrapper over the recursive function// leftRotateRec()// It left rotates []arr by d.public static void leftRotate(int []arr, int d, int n){ leftRotateRec(arr, 0, d, n);} public static void leftRotateRec(int []arr, int i, int d, int n){ // Return If number of elements // to be rotated is zero or equal // to array size if(d == 0 || d == n) return; // If number of elements to be rotated // is exactly half of array size if(n - d == d) { swap(arr, i, n - d + i, d); return; } // If A is shorter if(d < n - d) { swap(arr, i, n - d + i, d); leftRotateRec(arr, i, d, n - d); } // If B is shorter else { swap(arr, i, d, n - d); // This is tricky leftRotateRec(arr, n - d + i, 2 * d - n, d); }} // UTILITY FUNCTIONS// Function to print an arraypublic static void printArray(int []arr, int size){ int i; for(i = 0; i < size; i++) Console.Write(arr[i] + \" \"); Console.WriteLine();} // This function swaps d elements// starting at index fi with d elements// starting at index sipublic static void swap(int []arr, int fi, int si, int d){ int i, temp; for(i = 0; i < d; i++) { temp = arr[fi + i]; arr[fi + i] = arr[si + i]; arr[si + i] = temp; }} // Driver Codepublic static void Main(String[] args){ int []arr = { 1, 2, 3, 4, 5, 6, 7 }; leftRotate(arr, 2, 7); printArray(arr, 7); }} // This code is contributed by amal kumar choubey", "e": 46081, "s": 44374, "text": null }, { "code": "<script> let leftRotate = (arr, d, n) =>{ /* Return If number of elements to be rotated is zero or equal to array size */ if(d == 0 || d == n) return; /*If number of elements to be rotated is exactly half of array size */ if(n - d == d) { arr = swap(arr, 0, n - d, d); return; } /* If A is shorter*/ if(d < n - d) { arr = swap(arr, 0, n - d, d); leftRotate(arr, d, n - d); } else{ /* If B is shorter*/ arr = swap(arr, 0, d, n - d); /*This is tricky*/ leftRotate(arr + n - d, 2 * d - n, d); }} /*UTILITY FUNCTIONS*//* function to print an array */let printArray = (arr, size) =>{ ans = '' for(let i = 0; i < size; i++) ans += arr[i]+\" \"; document.write(ans)} /*This function swaps d elementsstarting at index fiwith d elements starting at index si */let swap = (arr, fi, si, d) =>{ for(let i = 0; i < d; i++) { let temp = arr[fi + i]; arr[fi + i] = arr[si + i]; arr[si + i] = temp; } return arr} // Driver Codearr = [1, 2, 3, 4, 5, 6, 7];leftRotate(arr, 2, 7);printArray(arr, 7); </script>", "e": 47255, "s": 46081, "text": null }, { "code": null, "e": 47270, "s": 47255, "text": "3 4 5 6 7 1 2 " }, { "code": null, "e": 47395, "s": 47270, "text": "Iterative Implementation: Here is iterative implementation of the same algorithm. Same utility function swap() is used here." }, { "code": null, "e": 47399, "s": 47395, "text": "C++" }, { "code": null, "e": 47401, "s": 47399, "text": "C" }, { "code": null, "e": 47406, "s": 47401, "text": "Java" }, { "code": null, "e": 47414, "s": 47406, "text": "Python3" }, { "code": null, "e": 47417, "s": 47414, "text": "C#" }, { "code": null, "e": 47428, "s": 47417, "text": "Javascript" }, { "code": "// C++ code for above implementationvoid leftRotate(int arr[], int d, int n){ int i, j; if (d == 0 || d == n) return; /* If number of elements to be rotated is more than array size*/ if(d > n) d = d % n; i = d; j = n - d; while (i != j) { if (i < j) /*A is shorter*/ { swap(arr, d - i, d + j - i, i); j -= i; } else /*B is shorter*/ { swap(arr, d - i, d, j); i -= j; } // printArray(arr, 7); } /*Finally, block swap A and B*/ swap(arr, d - i, d, i);} // This code is contributed by Shivani", "e": 48078, "s": 47428, "text": null }, { "code": "// C code for above implementationvoid leftRotate(int arr[], int d, int n){ int i, j; if(d == 0 || d == n) return; /* If number of elements to be rotated is more than array size*/ if(d > n) d = d % n; i = d; j = n - d; while (i != j) { if(i < j) /*A is shorter*/ { swap(arr, d-i, d+j-i, i); j -= i; } else /*B is shorter*/ { swap(arr, d-i, d, j); i -= j; } // printArray(arr, 7); } /*Finally, block swap A and B*/ swap(arr, d-i, d, i);}", "e": 48573, "s": 48078, "text": null }, { "code": "//Java code for above implementationstatic void leftRotate(int arr[], int d, int n){int i, j;if(d == 0 || d == n) return;/* If number of elements to be rotated is more than array size*/ if(d > n) d = d % n;i = d;j = n - d;while (i != j){ if(i < j) /*A is shorter*/ { swap(arr, d-i, d+j-i, i); j -= i; } else /*B is shorter*/ { swap(arr, d-i, d, j); i -= j; } // printArray(arr, 7);}/*Finally, block swap A and B*/swap(arr, d-i, d, i);}", "e": 49047, "s": 48573, "text": null }, { "code": "# Python3 code for above implementation def leftRotate(arr, d, n): if(d == 0 or d == n): return; i = d j = n - d while (i != j): if(i < j): # A is shorter swap(arr, d - i, d + j - i, i) j -= i else: # B is shorter swap(arr, d - i, d, j) i -= j swap(arr, d - i, d, i) # This code is contributed# by Adarsh_Verma", "e": 49461, "s": 49047, "text": null }, { "code": "// C# code for above implementationstatic void leftRotate(int []arr, int d, int n){ int i, j; if(d == 0 || d == n) return; /* If number of elements to be rotated is more than array size*/ if(d > n) d = d % n; i = d; j = n - d; while (i != j) { if(i < j) /*A is shorter*/ { swap(arr, d-i, d+j-i, i); j -= i; } else /*B is shorter*/ { swap(arr, d-i, d, j); i -= j; } } /*Finally, block swap A and B*/ swap(arr, d-i, d, i);} // This code is contributed by Rajput-Ji", "e": 50073, "s": 49461, "text": null }, { "code": "<script>// JavaScript code for above implementationfunction leftRotate(arr, d, n){ if(d == 0 || d == n) return; let i = d; let j = n - d; while (i != j) { if(i < j) { // A is shorter arr = swap(arr, d - i, d + j - i, i); j -= i; } else{ // B is shorter arr = swap(arr, d - i, d, j); i -= j; } } arr = swap(arr, d - i, d, i); // This code is contributed by rohitsingh04052.}</script>", "e": 50587, "s": 50073, "text": null }, { "code": null, "e": 50609, "s": 50587, "text": "Time Complexity: O(n)" }, { "code": null, "e": 50827, "s": 50609, "text": "Auxiliary Space: O(1)Please see following posts for other methods of array rotation: https://www.geeksforgeeks.org/array-rotation/ https://www.geeksforgeeks.org/program-for-array-rotation-continued-reversal-algorithm/" }, { "code": null, "e": 51039, "s": 50827, "text": "References: http://www.cs.bell-labs.com/cm/cs/pearls/s02b.pdfPlease write comments if you find any bug in the above programs/algorithms or want to share any additional information about the block swap algorithm." }, { "code": null, "e": 51051, "s": 51039, "text": "AbhijeetPal" }, { "code": null, "e": 51064, "s": 51051, "text": "prerna saini" }, { "code": null, "e": 51077, "s": 51064, "text": "Adarsh_Verma" }, { "code": null, "e": 51087, "s": 51077, "text": "Rajput-Ji" }, { "code": null, "e": 51101, "s": 51087, "text": "rathbhupendra" }, { "code": null, "e": 51112, "s": 51101, "text": "CodeSeeker" }, { "code": null, "e": 51131, "s": 51112, "text": "Amal Kumar Choubey" }, { "code": null, "e": 51144, "s": 51131, "text": "Rohit_ranjan" }, { "code": null, "e": 51160, "s": 51144, "text": "rohitsingh07052" }, { "code": null, "e": 51179, "s": 51160, "text": "shivanisinghss2110" }, { "code": null, "e": 51199, "s": 51179, "text": "yashguptaindianera5" }, { "code": null, "e": 51210, "s": 51199, "text": "mahmady173" }, { "code": null, "e": 51227, "s": 51210, "text": "surinderdawra388" }, { "code": null, "e": 51239, "s": 51227, "text": "rishavnitro" }, { "code": null, "e": 51248, "s": 51239, "text": "rotation" }, { "code": null, "e": 51255, "s": 51248, "text": "Arrays" }, { "code": null, "e": 51262, "s": 51255, "text": "Arrays" }, { "code": null, "e": 51360, "s": 51262, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 51428, "s": 51360, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 51472, "s": 51428, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 51504, "s": 51472, "text": "Largest Sum Contiguous Subarray" }, { "code": null, "e": 51536, "s": 51504, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 51550, "s": 51536, "text": "Linear Search" }, { "code": null, "e": 51595, "s": 51550, "text": "Python | Using 2D arrays/lists the right way" }, { "code": null, "e": 51619, "s": 51595, "text": "Find the Missing Number" }, { "code": null, "e": 51646, "s": 51619, "text": "Subset Sum Problem | DP-25" }, { "code": null, "e": 51699, "s": 51646, "text": "Array of Strings in C++ (5 Different Ways to Create)" } ]
ML | Mathematical explanation of RMSE and R-squared error - GeeksforGeeks
03 Sep, 2021 RMSE: Root Mean Square Error is the measure of how well a regression line fits the data points. RMSE can also be construed as Standard Deviation in the residuals. Consider the given data points: (1, 1), (2, 2), (2, 3), (3, 6). Lets break the above data points into 1-d lists. Input : x = [1, 2, 2, 3] y = [1, 2, 3, 6] Code : Regression Graph Python import matplotlib.pyplot as pltimport math # plotting the points plt.plot(x, y) # naming the x axisplt.xlabel('x - axis') # naming the y axisplt.ylabel('y - axis') # giving a title to my graphplt.title('Regression Graph') # function to show the plotplt.show() Code: Mean Calculation Python # in the next step we will find the equation of the best fit line# we will use Linear algebra's Point slope form to find regression line equation# point-slope form is represented by y = mx + c# where m is slope means (change in y) / (change in x)# c is constant, it represents at which point line will intercept y-axis# slope m can be formulated as below:''' nm =? (xi - Xmean) (yi - Ymean)/?(xi - Xmean)^2 i = 1'''# calculate Xmean and Ymeanct = len(x)sum_x = 0sum_y = 0 for i in x: sum_x = sum_x + ix_mean = sum_x / ctprint('Value of X mean', x_mean) for i in y: sum_y = sum_y + iy_mean = sum_y / ctprint('value of Y mean', y_mean) # we have the values of x mean and y_mean Output : Value of X mean 2.0 value of Y mean 3.0 Code : Line Equation Python # below is the process of finding line equation in mathematical terms# slope of our line is 2.5# calculate c to find out the equation m = 2.5c = y_mean - m * x_meanprint('Intercept', c) Output : Intercept -2.0 Code : Mean Squared Error Python # equation of our Regression line comes out to be as below:# y_pred = 2.5x-2.0# we call the line y_pred# paste regression line graphfrom sklearn.metrics import mean_squared_error# y_pred for our exusting data points is as below y =[1, 2, 3, 6]y_pred =[0.5, 3, 3, 5.5] Python # root mean square calculated by sklearn packagemse = math.sqrt(mean_squared_error(y, y_pred))print('Root mean square error', mse) Output : Root mean square error 0.6123724356957945 Code : RMSE Calculation Python # lets check how the Root mean square is calculated mathematically# lets introduce a term called residuals# residual are basically the distance of data point from the regression line# residuals are denoted by red marked line in below graph# root mean square and residuals are calculated as below# we have 4 data points'''r = 1, ri = yi-y_predy_pred is mx + cri = yi-(mx + c)e.g. x = 1, we have value of y as 1we want to evaluate what exactly our model has predicted for x = 1(1, 1)r1 = 1, x = 2'''# y_pred1 = 1-(2.5 * 1-2.0)= 0.5r1 = 1-(2.5 * 1-2.0) #(2, 2) r2 = 2, x = 2# y_pred2 = 2-(2.5 * 2-2.0)=-1r2 = 2-(2.5 * 2-2.0) #(2, 3) r3 = 3, x = 2# y_pred3 = 3-(2.5 * 2-2.0)= 0r3 = 3-(2.5 * 2-2.0) #(3, 6) r4 = 4, x = 3# y_pred4 = 6-(2.5 * 3-2.0)=.5r4 = 6-(2.5 * 3-2.0) # from above calculation we have values of residualsresiduals =[0.5, -1, 0, .5] # now calculate root mean square error# N = 4 data pointsN = 4rmse = math.sqrt((r1**2 + r2**2 + r3**2 + r4**2)/N)print('Root Mean square error using maths', rmse) # root mean square actually calculated using mathematics# both of RMSE calculated are same Output : Root Mean square error using maths 0.6123724356957945 R-squared Error or Coefficient of Determination R2 error answers the below question. How much y varies with variation in x.Basically the % variation of y on variation with x Code : R-Squared Error Python # SEline =(y1-(mx1 + b)**2 + y2-(mx2 + b)**2...+yn-(mxn + b)**2)# SE_line =(1-(2.5 * 1+(-2))**2 + (2-(2.5 * 2+(-2))**2) +(3-(2.5*(2)+(-2))**2) + (6-(2.5*(3)+(-2))**2)) val1 =(1-(2.5 * 1+(-2)))**2val2 =(2-(2.5 * 2+(-2)))**2val3 =(3-(2.5 * 2+(-2)))**2val4 =(6-(2.5 * 3+(-2)))**2SE_line = val1 + val2 + val3 + val4print('val', val1, val2, val3, val4) # next to calculate total variation in Y from mean value# variation in y is calculated as# y_var =(y1-ymean)**2+(y2-ymean)**2...+(yn-ymean)2 y =[1, 2, 3, 6] y_var =(1-3)**2+(2-3)**2+(3-3)**2+(6-3)**2SE_mean = y_var # by calculating y_var we are calculating the distance# between y data points and mean value of y# so answer to our question, % of the total variation# of wrt x is denoted as below:r_squared = 1-(SE_line / SE_mean) # [SE_line / SE_mean] -->tells us the what % of variation# in y is not described by regression line# 1-(SE_line / SE_mean) --> gives us the exact value of# how much % y varies with variation in xprint('Rsquared error', r_squared) Output : Rsquared error 0.8928571428571429 Code : R-Squared Error with sklearn Python from sklearn.metrics import r2_score # r2 error calculated by sklearn is similar# to ours mathematically calculated r2 error# calculate r2 error using sklearnr2_score(y, y_pred) Output : 0.8928571428571429 surindertarika1234 Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python | Decision tree implementation Search Algorithms in AI Decision Tree Introduction with example ML | Underfitting and Overfitting Support Vector Machine Algorithm Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe
[ { "code": null, "e": 24532, "s": 24504, "text": "\n03 Sep, 2021" }, { "code": null, "e": 24818, "s": 24532, "text": "RMSE: Root Mean Square Error is the measure of how well a regression line fits the data points. RMSE can also be construed as Standard Deviation in the residuals. Consider the given data points: (1, 1), (2, 2), (2, 3), (3, 6). Lets break the above data points into 1-d lists. Input : " }, { "code": null, "e": 24852, "s": 24818, "text": "x = [1, 2, 2, 3]\ny = [1, 2, 3, 6]" }, { "code": null, "e": 24878, "s": 24852, "text": "Code : Regression Graph " }, { "code": null, "e": 24885, "s": 24878, "text": "Python" }, { "code": "import matplotlib.pyplot as pltimport math # plotting the points plt.plot(x, y) # naming the x axisplt.xlabel('x - axis') # naming the y axisplt.ylabel('y - axis') # giving a title to my graphplt.title('Regression Graph') # function to show the plotplt.show()", "e": 25145, "s": 24885, "text": null }, { "code": null, "e": 25170, "s": 25145, "text": "Code: Mean Calculation " }, { "code": null, "e": 25177, "s": 25170, "text": "Python" }, { "code": "# in the next step we will find the equation of the best fit line# we will use Linear algebra's Point slope form to find regression line equation# point-slope form is represented by y = mx + c# where m is slope means (change in y) / (change in x)# c is constant, it represents at which point line will intercept y-axis# slope m can be formulated as below:''' nm =? (xi - Xmean) (yi - Ymean)/?(xi - Xmean)^2 i = 1'''# calculate Xmean and Ymeanct = len(x)sum_x = 0sum_y = 0 for i in x: sum_x = sum_x + ix_mean = sum_x / ctprint('Value of X mean', x_mean) for i in y: sum_y = sum_y + iy_mean = sum_y / ctprint('value of Y mean', y_mean) # we have the values of x mean and y_mean", "e": 25861, "s": 25177, "text": null }, { "code": null, "e": 25872, "s": 25861, "text": "Output : " }, { "code": null, "e": 25912, "s": 25872, "text": "Value of X mean 2.0\nvalue of Y mean 3.0" }, { "code": null, "e": 25935, "s": 25912, "text": "Code : Line Equation " }, { "code": null, "e": 25942, "s": 25935, "text": "Python" }, { "code": "# below is the process of finding line equation in mathematical terms# slope of our line is 2.5# calculate c to find out the equation m = 2.5c = y_mean - m * x_meanprint('Intercept', c)", "e": 26128, "s": 25942, "text": null }, { "code": null, "e": 26139, "s": 26128, "text": "Output : " }, { "code": null, "e": 26154, "s": 26139, "text": "Intercept -2.0" }, { "code": null, "e": 26182, "s": 26154, "text": "Code : Mean Squared Error " }, { "code": null, "e": 26189, "s": 26182, "text": "Python" }, { "code": "# equation of our Regression line comes out to be as below:# y_pred = 2.5x-2.0# we call the line y_pred# paste regression line graphfrom sklearn.metrics import mean_squared_error# y_pred for our exusting data points is as below y =[1, 2, 3, 6]y_pred =[0.5, 3, 3, 5.5]", "e": 26457, "s": 26189, "text": null }, { "code": null, "e": 26464, "s": 26457, "text": "Python" }, { "code": "# root mean square calculated by sklearn packagemse = math.sqrt(mean_squared_error(y, y_pred))print('Root mean square error', mse)", "e": 26595, "s": 26464, "text": null }, { "code": null, "e": 26606, "s": 26595, "text": "Output : " }, { "code": null, "e": 26648, "s": 26606, "text": "Root mean square error 0.6123724356957945" }, { "code": null, "e": 26674, "s": 26648, "text": "Code : RMSE Calculation " }, { "code": null, "e": 26681, "s": 26674, "text": "Python" }, { "code": "# lets check how the Root mean square is calculated mathematically# lets introduce a term called residuals# residual are basically the distance of data point from the regression line# residuals are denoted by red marked line in below graph# root mean square and residuals are calculated as below# we have 4 data points'''r = 1, ri = yi-y_predy_pred is mx + cri = yi-(mx + c)e.g. x = 1, we have value of y as 1we want to evaluate what exactly our model has predicted for x = 1(1, 1)r1 = 1, x = 2'''# y_pred1 = 1-(2.5 * 1-2.0)= 0.5r1 = 1-(2.5 * 1-2.0) #(2, 2) r2 = 2, x = 2# y_pred2 = 2-(2.5 * 2-2.0)=-1r2 = 2-(2.5 * 2-2.0) #(2, 3) r3 = 3, x = 2# y_pred3 = 3-(2.5 * 2-2.0)= 0r3 = 3-(2.5 * 2-2.0) #(3, 6) r4 = 4, x = 3# y_pred4 = 6-(2.5 * 3-2.0)=.5r4 = 6-(2.5 * 3-2.0) # from above calculation we have values of residualsresiduals =[0.5, -1, 0, .5] # now calculate root mean square error# N = 4 data pointsN = 4rmse = math.sqrt((r1**2 + r2**2 + r3**2 + r4**2)/N)print('Root Mean square error using maths', rmse) # root mean square actually calculated using mathematics# both of RMSE calculated are same", "e": 27781, "s": 26681, "text": null }, { "code": null, "e": 27792, "s": 27781, "text": "Output : " }, { "code": null, "e": 27846, "s": 27792, "text": "Root Mean square error using maths 0.6123724356957945" }, { "code": null, "e": 28022, "s": 27846, "text": "R-squared Error or Coefficient of Determination R2 error answers the below question. How much y varies with variation in x.Basically the % variation of y on variation with x " }, { "code": null, "e": 28047, "s": 28022, "text": "Code : R-Squared Error " }, { "code": null, "e": 28054, "s": 28047, "text": "Python" }, { "code": "# SEline =(y1-(mx1 + b)**2 + y2-(mx2 + b)**2...+yn-(mxn + b)**2)# SE_line =(1-(2.5 * 1+(-2))**2 + (2-(2.5 * 2+(-2))**2) +(3-(2.5*(2)+(-2))**2) + (6-(2.5*(3)+(-2))**2)) val1 =(1-(2.5 * 1+(-2)))**2val2 =(2-(2.5 * 2+(-2)))**2val3 =(3-(2.5 * 2+(-2)))**2val4 =(6-(2.5 * 3+(-2)))**2SE_line = val1 + val2 + val3 + val4print('val', val1, val2, val3, val4) # next to calculate total variation in Y from mean value# variation in y is calculated as# y_var =(y1-ymean)**2+(y2-ymean)**2...+(yn-ymean)2 y =[1, 2, 3, 6] y_var =(1-3)**2+(2-3)**2+(3-3)**2+(6-3)**2SE_mean = y_var # by calculating y_var we are calculating the distance# between y data points and mean value of y# so answer to our question, % of the total variation# of wrt x is denoted as below:r_squared = 1-(SE_line / SE_mean) # [SE_line / SE_mean] -->tells us the what % of variation# in y is not described by regression line# 1-(SE_line / SE_mean) --> gives us the exact value of# how much % y varies with variation in xprint('Rsquared error', r_squared)", "e": 29062, "s": 28054, "text": null }, { "code": null, "e": 29073, "s": 29062, "text": "Output : " }, { "code": null, "e": 29107, "s": 29073, "text": "Rsquared error 0.8928571428571429" }, { "code": null, "e": 29145, "s": 29107, "text": "Code : R-Squared Error with sklearn " }, { "code": null, "e": 29152, "s": 29145, "text": "Python" }, { "code": "from sklearn.metrics import r2_score # r2 error calculated by sklearn is similar# to ours mathematically calculated r2 error# calculate r2 error using sklearnr2_score(y, y_pred)", "e": 29330, "s": 29152, "text": null }, { "code": null, "e": 29341, "s": 29330, "text": "Output : " }, { "code": null, "e": 29360, "s": 29341, "text": "0.8928571428571429" }, { "code": null, "e": 29381, "s": 29362, "text": "surindertarika1234" }, { "code": null, "e": 29398, "s": 29381, "text": "Machine Learning" }, { "code": null, "e": 29405, "s": 29398, "text": "Python" }, { "code": null, "e": 29422, "s": 29405, "text": "Machine Learning" }, { "code": null, "e": 29520, "s": 29422, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29529, "s": 29520, "text": "Comments" }, { "code": null, "e": 29542, "s": 29529, "text": "Old Comments" }, { "code": null, "e": 29580, "s": 29542, "text": "Python | Decision tree implementation" }, { "code": null, "e": 29604, "s": 29580, "text": "Search Algorithms in AI" }, { "code": null, "e": 29644, "s": 29604, "text": "Decision Tree Introduction with example" }, { "code": null, "e": 29678, "s": 29644, "text": "ML | Underfitting and Overfitting" }, { "code": null, "e": 29711, "s": 29678, "text": "Support Vector Machine Algorithm" }, { "code": null, "e": 29739, "s": 29711, "text": "Read JSON file using Python" }, { "code": null, "e": 29789, "s": 29739, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 29811, "s": 29789, "text": "Python map() function" } ]
Find the memory size of a NumPy array - GeeksforGeeks
02 Sep, 2020 In this post, we will see how to find the memory size of a NumPy array. So for finding the memory size we are using following methods: Method 1: Using size and itemsize attributes of NumPy array. size: This attribute gives the number of elements present in the NumPy array. itemsize: This attribute gives the memory size of one element of NumPy array in bytes. Let’s see the examples: Example 1: Python3 # import libraryimport numpy as np # create a numpy 1d-arrayx = np.array([100,20,34]) print("Size of the array: ", x.size) print("Memory size of one array element in bytes: ", x.itemsize) # memory size of numpy array in bytesprint("Memory size of numpy array in bytes:", x.size * x.itemsize) Output: Size of the array: 3 Memory size of one array element in bytes: 4 Memory size of numpy array in bytes: 12 Example 2: Python3 # import libraryimport numpy as np # create a numpy 2d-arrayx = np.array([[100, 20, 34], [300, 400, 600]]) print("Size of the array: ", x.size) print("Memory size of one array element in bytes: ", x.itemsize) # memory size of numpy arrayprint("Memory size of numpy array in bytes:", x.size * x.itemsize) Output: Size of the array: 6 Length of one array element in bytes: 4 Memory size of numpy array in bytes: 24 Method 2: Using nbytes attribute of NumPy array. nbytes: This attribute gives the total bytes consumed by the elements of the NumPy array. Let’s see the examples: Example 1: Python3 # import libraryimport numpy as np # create numpy 1d-arrayx = np.array([100, 20, 34]) print("Memory size of a NumPy array:", x.nbytes) Output: Memory size of a NumPy array: 12 Example 2: Python3 # import libraryimport numpy as np # create numpy 2d-arrayx = np.array([[100, 20, 34], [300, 400, 600]]) print("Memory size of a NumPy array:", x.nbytes) Output: Memory size of a NumPy array: 24 Python-numpy 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 How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Pandas dataframe.groupby() Defaultdict in Python Python | Get unique values from a list Python Classes and Objects Python | os.path.join() method Create a directory in Python
[ { "code": null, "e": 23925, "s": 23897, "text": "\n02 Sep, 2020" }, { "code": null, "e": 24060, "s": 23925, "text": "In this post, we will see how to find the memory size of a NumPy array. So for finding the memory size we are using following methods:" }, { "code": null, "e": 24121, "s": 24060, "text": "Method 1: Using size and itemsize attributes of NumPy array." }, { "code": null, "e": 24199, "s": 24121, "text": "size: This attribute gives the number of elements present in the NumPy array." }, { "code": null, "e": 24286, "s": 24199, "text": "itemsize: This attribute gives the memory size of one element of NumPy array in bytes." }, { "code": null, "e": 24310, "s": 24286, "text": "Let’s see the examples:" }, { "code": null, "e": 24321, "s": 24310, "text": "Example 1:" }, { "code": null, "e": 24329, "s": 24321, "text": "Python3" }, { "code": "# import libraryimport numpy as np # create a numpy 1d-arrayx = np.array([100,20,34]) print(\"Size of the array: \", x.size) print(\"Memory size of one array element in bytes: \", x.itemsize) # memory size of numpy array in bytesprint(\"Memory size of numpy array in bytes:\", x.size * x.itemsize)", "e": 24640, "s": 24329, "text": null }, { "code": null, "e": 24648, "s": 24640, "text": "Output:" }, { "code": null, "e": 24757, "s": 24648, "text": "Size of the array: 3\nMemory size of one array element in bytes: 4\nMemory size of numpy array in bytes: 12\n" }, { "code": null, "e": 24768, "s": 24757, "text": "Example 2:" }, { "code": null, "e": 24776, "s": 24768, "text": "Python3" }, { "code": "# import libraryimport numpy as np # create a numpy 2d-arrayx = np.array([[100, 20, 34], [300, 400, 600]]) print(\"Size of the array: \", x.size) print(\"Memory size of one array element in bytes: \", x.itemsize) # memory size of numpy arrayprint(\"Memory size of numpy array in bytes:\", x.size * x.itemsize)", "e": 25112, "s": 24776, "text": null }, { "code": null, "e": 25120, "s": 25112, "text": "Output:" }, { "code": null, "e": 25224, "s": 25120, "text": "Size of the array: 6\nLength of one array element in bytes: 4\nMemory size of numpy array in bytes: 24\n" }, { "code": null, "e": 25273, "s": 25224, "text": "Method 2: Using nbytes attribute of NumPy array." }, { "code": null, "e": 25363, "s": 25273, "text": "nbytes: This attribute gives the total bytes consumed by the elements of the NumPy array." }, { "code": null, "e": 25387, "s": 25363, "text": "Let’s see the examples:" }, { "code": null, "e": 25398, "s": 25387, "text": "Example 1:" }, { "code": null, "e": 25406, "s": 25398, "text": "Python3" }, { "code": "# import libraryimport numpy as np # create numpy 1d-arrayx = np.array([100, 20, 34]) print(\"Memory size of a NumPy array:\", x.nbytes)", "e": 25548, "s": 25406, "text": null }, { "code": null, "e": 25556, "s": 25548, "text": "Output:" }, { "code": null, "e": 25590, "s": 25556, "text": "Memory size of a NumPy array: 12\n" }, { "code": null, "e": 25601, "s": 25590, "text": "Example 2:" }, { "code": null, "e": 25609, "s": 25601, "text": "Python3" }, { "code": "# import libraryimport numpy as np # create numpy 2d-arrayx = np.array([[100, 20, 34], [300, 400, 600]]) print(\"Memory size of a NumPy array:\", x.nbytes)", "e": 25783, "s": 25609, "text": null }, { "code": null, "e": 25791, "s": 25783, "text": "Output:" }, { "code": null, "e": 25825, "s": 25791, "text": "Memory size of a NumPy array: 24\n" }, { "code": null, "e": 25838, "s": 25825, "text": "Python-numpy" }, { "code": null, "e": 25845, "s": 25838, "text": "Python" }, { "code": null, "e": 25943, "s": 25845, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25952, "s": 25943, "text": "Comments" }, { "code": null, "e": 25965, "s": 25952, "text": "Old Comments" }, { "code": null, "e": 25997, "s": 25965, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26053, "s": 25997, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26095, "s": 26053, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26137, "s": 26095, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26173, "s": 26137, "text": "Python | Pandas dataframe.groupby()" }, { "code": null, "e": 26195, "s": 26173, "text": "Defaultdict in Python" }, { "code": null, "e": 26234, "s": 26195, "text": "Python | Get unique values from a list" }, { "code": null, "e": 26261, "s": 26234, "text": "Python Classes and Objects" }, { "code": null, "e": 26292, "s": 26261, "text": "Python | os.path.join() method" } ]
Scala - Default Parameter Values for a Function
Scala lets you specify default values for function parameters. The argument for such a parameter can optionally be omitted from a function call, in which case the corresponding argument will be filled in with the default. If you specify one of the parameters, then first argument will be passed using that parameter and second will be taken from default value. Try the following example, it is an example of specifying default parameters for a function − object Demo { def main(args: Array[String]) { println( "Returned Value : " + addInt() ); } def addInt( a:Int = 5, b:Int = 7 ) : Int = { var sum:Int = 0 sum = a + b return sum } } Save the above program in Demo.scala. The following commands are used to compile and execute this program. \>scalac Demo.scala \>scala Demo Returned Value : 12 82 Lectures 7 hours Arnab Chakraborty 23 Lectures 1.5 hours Mukund Kumar Mishra 52 Lectures 1.5 hours Bigdata Engineer 76 Lectures 5.5 hours Bigdata Engineer 69 Lectures 7.5 hours Bigdata Engineer 46 Lectures 4.5 hours Stone River ELearning Print Add Notes Bookmark this page
[ { "code": null, "e": 2359, "s": 1998, "text": "Scala lets you specify default values for function parameters. The argument for such a parameter can optionally be omitted from a function call, in which case the corresponding argument will be filled in with the default. If you specify one of the parameters, then first argument will be passed using that parameter and second will be taken from default value." }, { "code": null, "e": 2453, "s": 2359, "text": "Try the following example, it is an example of specifying default parameters for a function −" }, { "code": null, "e": 2673, "s": 2453, "text": "object Demo {\n def main(args: Array[String]) {\n println( \"Returned Value : \" + addInt() );\n }\n \n def addInt( a:Int = 5, b:Int = 7 ) : Int = {\n var sum:Int = 0\n sum = a + b\n\n return sum\n }\n}" }, { "code": null, "e": 2780, "s": 2673, "text": "Save the above program in Demo.scala. The following commands are used to compile and execute this program." }, { "code": null, "e": 2814, "s": 2780, "text": "\\>scalac Demo.scala\n\\>scala Demo\n" }, { "code": null, "e": 2835, "s": 2814, "text": "Returned Value : 12\n" }, { "code": null, "e": 2868, "s": 2835, "text": "\n 82 Lectures \n 7 hours \n" }, { "code": null, "e": 2887, "s": 2868, "text": " Arnab Chakraborty" }, { "code": null, "e": 2922, "s": 2887, "text": "\n 23 Lectures \n 1.5 hours \n" }, { "code": null, "e": 2943, "s": 2922, "text": " Mukund Kumar Mishra" }, { "code": null, "e": 2978, "s": 2943, "text": "\n 52 Lectures \n 1.5 hours \n" }, { "code": null, "e": 2996, "s": 2978, "text": " Bigdata Engineer" }, { "code": null, "e": 3031, "s": 2996, "text": "\n 76 Lectures \n 5.5 hours \n" }, { "code": null, "e": 3049, "s": 3031, "text": " Bigdata Engineer" }, { "code": null, "e": 3084, "s": 3049, "text": "\n 69 Lectures \n 7.5 hours \n" }, { "code": null, "e": 3102, "s": 3084, "text": " Bigdata Engineer" }, { "code": null, "e": 3137, "s": 3102, "text": "\n 46 Lectures \n 4.5 hours \n" }, { "code": null, "e": 3160, "s": 3137, "text": " Stone River ELearning" }, { "code": null, "e": 3167, "s": 3160, "text": " Print" }, { "code": null, "e": 3178, "s": 3167, "text": " Add Notes" } ]
DC.js - Introduction to Crossfilter
Crossfilter is a multi-dimensional dataset. It supports extremely fast interaction with datasets containing a million or more records. Crossfilter is defined under the crossfilter namespace. It uses semantic versioning. Consider a crossfilter object loaded with a collection of fruits that is defined below − var fruits = crossfilter ([ { name: “Apple”, type: “fruit”, count: 20 }, { name: “Orange”, type: "fruit”, count: 10 }, { name: “Grapes”, type: “fruit”, count: 50 }, { name: “Mango”, type: “fruit”, count: 40 } ]); If we need to perform the total records in a group, we can use the following function − var count = fruits.groupAll().reduceCount().value(); If we want to filter by a specific type − var filtering = fruits.dimension(function(d) { return d.type; }); filtering.filter(“Grapes”) Similarly, we can perform grouping with Crossfilter. To do this, we can use the following function − var grouping = filtering.group().reduceCount(); var first = grouping.top(2); Hence, Crossfilter is built to be extremely fast. If you want to recalculate groups as filters are applied, it calculates incrementally. Crossfilter dimensions are very expensive. Let us go through the notable Crossfilter APIs in detail. crossfilter([records]) − It is used to construct a new crossfilter. If the record is specified, then it simultaneously adds the specified records. Records can be any array of JavaScript objects or primitives. crossfilter([records]) − It is used to construct a new crossfilter. If the record is specified, then it simultaneously adds the specified records. Records can be any array of JavaScript objects or primitives. crossfilter.add(records) − Adds the specified records to the crossfilter. crossfilter.add(records) − Adds the specified records to the crossfilter. crossfilter.remove() − Removes all records that match the current filters from the crossfilter. crossfilter.remove() − Removes all records that match the current filters from the crossfilter. crossfilter.size() − Returns the number of records in the crossfilter. crossfilter.size() − Returns the number of records in the crossfilter. crossfilter.groupAll() − It is a function for grouping all records and reducing to a single value. crossfilter.groupAll() − It is a function for grouping all records and reducing to a single value. crossfilter.dimension(value) − It is used to construct a new dimension using the specified value accessor function. crossfilter.dimension(value) − It is used to construct a new dimension using the specified value accessor function. dimension.filter(value) − It is used to filter records for dimension's match value, and returns the dimension. dimension.filter(value) − It is used to filter records for dimension's match value, and returns the dimension. dimension.filterRange(range) − Filters records for dimension's value that are greater than or equal to range[0], and less than range[1]. dimension.filterRange(range) − Filters records for dimension's value that are greater than or equal to range[0], and less than range[1]. dimension.filterAll() − Clears any filters on this dimension. dimension.filterAll() − Clears any filters on this dimension. dimension.top(k) − It is used to return a new array containing the top k records, according to the natural order of this dimension. dimension.top(k) − It is used to return a new array containing the top k records, according to the natural order of this dimension. dimension.bottom(k) − It is used to return a new array containing the bottom k records, according to the natural order of this dimension. dimension.bottom(k) − It is used to return a new array containing the bottom k records, according to the natural order of this dimension. dimension.dispose() − It is used to remove the dimension from the crossfilter. dimension.dispose() − It is used to remove the dimension from the crossfilter. In the next chapter, we will understand in brief about D3.js. Print Add Notes Bookmark this page
[ { "code": null, "e": 2194, "s": 2059, "text": "Crossfilter is a multi-dimensional dataset. It supports extremely fast interaction with datasets containing a million or more records." }, { "code": null, "e": 2368, "s": 2194, "text": "Crossfilter is defined under the crossfilter namespace. It uses semantic versioning. Consider a crossfilter object loaded with a collection of fruits that is defined below −" }, { "code": null, "e": 2594, "s": 2368, "text": "var fruits = crossfilter ([\n { name: “Apple”, type: “fruit”, count: 20 },\n { name: “Orange”, type: \"fruit”, count: 10 },\n { name: “Grapes”, type: “fruit”, count: 50 },\n { name: “Mango”, type: “fruit”, count: 40 }\n]);" }, { "code": null, "e": 2682, "s": 2594, "text": "If we need to perform the total records in a group, we can use the following function −" }, { "code": null, "e": 2735, "s": 2682, "text": "var count = fruits.groupAll().reduceCount().value();" }, { "code": null, "e": 2777, "s": 2735, "text": "If we want to filter by a specific type −" }, { "code": null, "e": 2870, "s": 2777, "text": "var filtering = fruits.dimension(function(d) { return d.type; });\nfiltering.filter(“Grapes”)" }, { "code": null, "e": 2971, "s": 2870, "text": "Similarly, we can perform grouping with Crossfilter. To do this, we can use the following function −" }, { "code": null, "e": 3048, "s": 2971, "text": "var grouping = filtering.group().reduceCount();\nvar first = grouping.top(2);" }, { "code": null, "e": 3228, "s": 3048, "text": "Hence, Crossfilter is built to be extremely fast. If you want to recalculate groups as filters are applied, it calculates incrementally. Crossfilter dimensions are very expensive." }, { "code": null, "e": 3286, "s": 3228, "text": "Let us go through the notable Crossfilter APIs in detail." }, { "code": null, "e": 3495, "s": 3286, "text": "crossfilter([records]) − It is used to construct a new crossfilter. If the record is specified, then it simultaneously adds the specified records. Records can be any array of JavaScript objects or primitives." }, { "code": null, "e": 3704, "s": 3495, "text": "crossfilter([records]) − It is used to construct a new crossfilter. If the record is specified, then it simultaneously adds the specified records. Records can be any array of JavaScript objects or primitives." }, { "code": null, "e": 3778, "s": 3704, "text": "crossfilter.add(records) − Adds the specified records to the crossfilter." }, { "code": null, "e": 3852, "s": 3778, "text": "crossfilter.add(records) − Adds the specified records to the crossfilter." }, { "code": null, "e": 3948, "s": 3852, "text": "crossfilter.remove() − Removes all records that match the current filters from the crossfilter." }, { "code": null, "e": 4044, "s": 3948, "text": "crossfilter.remove() − Removes all records that match the current filters from the crossfilter." }, { "code": null, "e": 4115, "s": 4044, "text": "crossfilter.size() − Returns the number of records in the crossfilter." }, { "code": null, "e": 4186, "s": 4115, "text": "crossfilter.size() − Returns the number of records in the crossfilter." }, { "code": null, "e": 4285, "s": 4186, "text": "crossfilter.groupAll() − It is a function for grouping all records and reducing to a single value." }, { "code": null, "e": 4384, "s": 4285, "text": "crossfilter.groupAll() − It is a function for grouping all records and reducing to a single value." }, { "code": null, "e": 4500, "s": 4384, "text": "crossfilter.dimension(value) − It is used to construct a new dimension using the specified value accessor function." }, { "code": null, "e": 4616, "s": 4500, "text": "crossfilter.dimension(value) − It is used to construct a new dimension using the specified value accessor function." }, { "code": null, "e": 4727, "s": 4616, "text": "dimension.filter(value) − It is used to filter records for dimension's match value, and returns the dimension." }, { "code": null, "e": 4838, "s": 4727, "text": "dimension.filter(value) − It is used to filter records for dimension's match value, and returns the dimension." }, { "code": null, "e": 4975, "s": 4838, "text": "dimension.filterRange(range) − Filters records for dimension's value that are greater than or equal to range[0], and less than range[1]." }, { "code": null, "e": 5112, "s": 4975, "text": "dimension.filterRange(range) − Filters records for dimension's value that are greater than or equal to range[0], and less than range[1]." }, { "code": null, "e": 5174, "s": 5112, "text": "dimension.filterAll() − Clears any filters on this dimension." }, { "code": null, "e": 5236, "s": 5174, "text": "dimension.filterAll() − Clears any filters on this dimension." }, { "code": null, "e": 5368, "s": 5236, "text": "dimension.top(k) − It is used to return a new array containing the top k records, according to the natural order of this dimension." }, { "code": null, "e": 5500, "s": 5368, "text": "dimension.top(k) − It is used to return a new array containing the top k records, according to the natural order of this dimension." }, { "code": null, "e": 5638, "s": 5500, "text": "dimension.bottom(k) − It is used to return a new array containing the bottom k records, according to the natural order of this dimension." }, { "code": null, "e": 5776, "s": 5638, "text": "dimension.bottom(k) − It is used to return a new array containing the bottom k records, according to the natural order of this dimension." }, { "code": null, "e": 5855, "s": 5776, "text": "dimension.dispose() − It is used to remove the dimension from the crossfilter." }, { "code": null, "e": 5934, "s": 5855, "text": "dimension.dispose() − It is used to remove the dimension from the crossfilter." }, { "code": null, "e": 5996, "s": 5934, "text": "In the next chapter, we will understand in brief about D3.js." }, { "code": null, "e": 6003, "s": 5996, "text": " Print" }, { "code": null, "e": 6014, "s": 6003, "text": " Add Notes" } ]
A different way to visualize classification results | by Nils Flaschel | Towards Data Science
I love good data visualizations. Back in the days when I did my PhD in particle physics, I was stunned by the histograms my colleagues built and how much information was accumulated in one single plot. It is really challenging to improve existing visualization methods or to transport methods from other research fields. You have to think about the dimensions in your plot and the ways to add more of them. A good example is the path from a boxplot to a violinplot to a swarmplot. It is a continuous process of adding dimensions and thus information. The possibilities of adding information or dimensions to a plot are almost endless. Categories can be added with different marker shapes, color maps like in a heat map can serve as another dimension and the size of a marker can give insight to further parameters. When it comes to machine learning, there are many ways to plot the performance of a classifier. There is an overwhelming amount of metrics to compare different estimators like accuracy, precision, recall or the helpful MMC. All of the common classification metrics are calculated from true positive, true negative, false positive and false negative incidents. The most popular plots are definitely ROC curve, PRC, CAP curve and the confusion matrix. I won’t get into detail of the three curves, but there are many different ways to handle the confusion matrix, like adding a heat map. For many cases, this is probably sufficient and easy to pick up all relevant information, but for a multi class problem, it can get much harder to do so. While reading some papers, I stumbled across: Jakob Raymaekers, Peter J. Rousseeuw, Mia Hubert. Visualizing classification results. arXiv:2007.14495 [stat.ML] and from there to Friendly, Michael. “Mosaic Displays for Multi-Way Contingency Tables.” Journal of the American Statistical Association, vol. 89, no. 425, 1994, pp. 190–200. JSTOR, www.jstor.org/stable/2291215. Accessed 13 Aug. 2020. The authors propose a mosaic diagram to plot discrete values. We can transport this idea to the field of machine learning with the predicted classes as the discrete values. In a multi class environment, such a plot would look like the following: It has several advantages over a classical confusion matrix. One can easily see the predicted classes on the y-axis and the number proportion of each class on the x-axis. The big difference from a simple bar plot is the width of the bars, which are giving an idea of the class imbalance. You can find the code for such a plot fed with a confusion matrix here: Note: This is not my idea, it is inspired by: Jakob Raymaekers, Peter J. Rousseeuw, Mia Hubert. Visualizing classification results. arXiv:2007.14495 [stat.ML] and Friendly, Michael. "Mosaic Displays for Multi-Way Contingency Tables." Journal of the American Statistical Association, vol. 89, no. 425, 1994, pp. 190–200. JSTOR, www.jstor.org/stable/2291215. Accessed 13 Aug. 2020. In short: This is an approach of visualizing the results of a multiclass estimator by taking the class distribution into account. The predicted classes are plotted along the y-axis and the class size on the x-axis. That way, one can immediatly see the class distribution in the data set. That makes it easier to judge the performance of the estimator. import numpy as np import pandas as pd import matplotlib.pyplot as plt %matplotlib inline from statsmodels.graphics.mosaicplot import mosaic from matplotlib.patches import Patch import itertools from collections import deque def nclass_classification_mosaic_plot(n_classes, results): """ build a mosaic plot from the results of a classification parameters: n_classes: number of classes results: results of the prediction in form of an array of arrays In case of 3 classes the prdiction could look like [[10, 2, 4], [1, 12, 3], [2, 2, 9] ] where there is one array for each class and each array holds the predictions for each class [class 1, class 2, class 3]. This is just a prototype including colors for 6 classes. """ class_lists = [range(n_classes)]*2 mosaic_tuples = tuple(itertools.product(*class_lists)) res_list = results[0] for i, l in enumerate(results): if i == 0: pass else: tmp = deque(l) tmp.rotate(-i) res_list.extend(tmp) data = {t:res_list[i] for i,t in enumerate(mosaic_tuples)} fig, ax = plt.subplots(figsize=(11, 10)) plt.rcParams.update({'font.size': 16}) font_color = '#2c3e50' pallet = [ '#6a89cc', '#4a69bd', '#1e3799', '#0c2461', '#82ccdd', '#60a3bc', ] colors = deque(pallet[:n_classes]) all_colors = [] for i in range(n_classes): if i > 0: colors.rotate(-1) all_colors.extend(colors) props = {(str(a), str(b)):{'color':all_colors[i]} for i,(a, b) in enumerate(mosaic_tuples)} labelizer = lambda k: '' p = mosaic(data, labelizer=labelizer, properties=props, ax=ax) title_font_dict = { 'fontsize': 20, 'color' : font_color, } axis_label_font_dict = { 'fontsize': 16, 'color' : font_color, } ax.tick_params(axis = "x", which = "both", bottom = False, top = False) ax.axes.yaxis.set_ticks([]) ax.tick_params(axis='x', which='major', labelsize=14) ax.set_title('Classification Report', fontdict=title_font_dict, pad=25) ax.set_xlabel('Observed Class', fontdict=axis_label_font_dict, labelpad=10) ax.set_ylabel('Predicted Class', fontdict=axis_label_font_dict, labelpad=35) legend_elements = [Patch(facecolor=all_colors[i], label='Class {}'.format(i)) for i in range(n_classes)] ax.legend(handles=legend_elements, bbox_to_anchor=(1,1.018), fontsize=16) plt.tight_layout() plt.show() n_classes = 4 # number of classes results = [ [50, 4, 1, 2], # predictions for class 1 [1, 40, 4, 3], # predictions for class 2 [3, 2, 30, 1], # predictions for class 3 [1, 3, 1, 60], # predictions for class 4 ] nclass_classification_mosaic_plot(n_classes, results) Have fun plotting your next classification results!
[ { "code": null, "e": 374, "s": 172, "text": "I love good data visualizations. Back in the days when I did my PhD in particle physics, I was stunned by the histograms my colleagues built and how much information was accumulated in one single plot." }, { "code": null, "e": 723, "s": 374, "text": "It is really challenging to improve existing visualization methods or to transport methods from other research fields. You have to think about the dimensions in your plot and the ways to add more of them. A good example is the path from a boxplot to a violinplot to a swarmplot. It is a continuous process of adding dimensions and thus information." }, { "code": null, "e": 987, "s": 723, "text": "The possibilities of adding information or dimensions to a plot are almost endless. Categories can be added with different marker shapes, color maps like in a heat map can serve as another dimension and the size of a marker can give insight to further parameters." }, { "code": null, "e": 1211, "s": 987, "text": "When it comes to machine learning, there are many ways to plot the performance of a classifier. There is an overwhelming amount of metrics to compare different estimators like accuracy, precision, recall or the helpful MMC." }, { "code": null, "e": 1437, "s": 1211, "text": "All of the common classification metrics are calculated from true positive, true negative, false positive and false negative incidents. The most popular plots are definitely ROC curve, PRC, CAP curve and the confusion matrix." }, { "code": null, "e": 1572, "s": 1437, "text": "I won’t get into detail of the three curves, but there are many different ways to handle the confusion matrix, like adding a heat map." }, { "code": null, "e": 1726, "s": 1572, "text": "For many cases, this is probably sufficient and easy to pick up all relevant information, but for a multi class problem, it can get much harder to do so." }, { "code": null, "e": 1772, "s": 1726, "text": "While reading some papers, I stumbled across:" }, { "code": null, "e": 1885, "s": 1772, "text": "Jakob Raymaekers, Peter J. Rousseeuw, Mia Hubert. Visualizing classification results. arXiv:2007.14495 [stat.ML]" }, { "code": null, "e": 1903, "s": 1885, "text": "and from there to" }, { "code": null, "e": 2120, "s": 1903, "text": "Friendly, Michael. “Mosaic Displays for Multi-Way Contingency Tables.” Journal of the American Statistical Association, vol. 89, no. 425, 1994, pp. 190–200. JSTOR, www.jstor.org/stable/2291215. Accessed 13 Aug. 2020." }, { "code": null, "e": 2293, "s": 2120, "text": "The authors propose a mosaic diagram to plot discrete values. We can transport this idea to the field of machine learning with the predicted classes as the discrete values." }, { "code": null, "e": 2366, "s": 2293, "text": "In a multi class environment, such a plot would look like the following:" }, { "code": null, "e": 2654, "s": 2366, "text": "It has several advantages over a classical confusion matrix. One can easily see the predicted classes on the y-axis and the number proportion of each class on the x-axis. The big difference from a simple bar plot is the width of the bars, which are giving an idea of the class imbalance." }, { "code": null, "e": 2726, "s": 2654, "text": "You can find the code for such a plot fed with a confusion matrix here:" }, { "code": null, "e": 2772, "s": 2726, "text": "Note: This is not my idea, it is inspired by:" }, { "code": null, "e": 2885, "s": 2772, "text": "Jakob Raymaekers, Peter J. Rousseeuw, Mia Hubert. Visualizing classification results. arXiv:2007.14495 [stat.ML]" }, { "code": null, "e": 2889, "s": 2885, "text": "and" }, { "code": null, "e": 3106, "s": 2889, "text": "Friendly, Michael. \"Mosaic Displays for Multi-Way Contingency Tables.\" Journal of the American Statistical Association, vol. 89, no. 425, 1994, pp. 190–200. JSTOR, www.jstor.org/stable/2291215. Accessed 13 Aug. 2020." }, { "code": null, "e": 3458, "s": 3106, "text": "In short:\nThis is an approach of visualizing the results of a multiclass estimator by taking the class distribution into account. The predicted classes are plotted along the y-axis and the class size on the x-axis. That way, one can immediatly see the class distribution in the data set. That makes it easier to judge the performance of the estimator." }, { "code": null, "e": 3684, "s": 3458, "text": "import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n%matplotlib inline\nfrom statsmodels.graphics.mosaicplot import mosaic\nfrom matplotlib.patches import Patch\nimport itertools\nfrom collections import deque\n" }, { "code": null, "e": 6047, "s": 3684, "text": "def nclass_classification_mosaic_plot(n_classes, results):\n \"\"\"\n build a mosaic plot from the results of a classification\n \n parameters:\n n_classes: number of classes\n results: results of the prediction in form of an array of arrays\n \n In case of 3 classes the prdiction could look like\n [[10, 2, 4],\n [1, 12, 3],\n [2, 2, 9]\n ]\n where there is one array for each class and each array holds the\n predictions for each class [class 1, class 2, class 3].\n \n This is just a prototype including colors for 6 classes.\n \"\"\"\n class_lists = [range(n_classes)]*2\n mosaic_tuples = tuple(itertools.product(*class_lists))\n \n res_list = results[0]\n for i, l in enumerate(results):\n if i == 0:\n pass\n else:\n tmp = deque(l)\n tmp.rotate(-i)\n res_list.extend(tmp)\n data = {t:res_list[i] for i,t in enumerate(mosaic_tuples)}\n\n fig, ax = plt.subplots(figsize=(11, 10))\n plt.rcParams.update({'font.size': 16})\n\n font_color = '#2c3e50'\n pallet = [\n '#6a89cc', \n '#4a69bd', \n '#1e3799', \n '#0c2461',\n '#82ccdd',\n '#60a3bc',\n ]\n colors = deque(pallet[:n_classes])\n all_colors = []\n for i in range(n_classes):\n if i > 0:\n colors.rotate(-1)\n all_colors.extend(colors)\n\n props = {(str(a), str(b)):{'color':all_colors[i]} for i,(a, b) in enumerate(mosaic_tuples)}\n\n labelizer = lambda k: ''\n\n p = mosaic(data, labelizer=labelizer, properties=props, ax=ax)\n\n title_font_dict = {\n 'fontsize': 20,\n 'color' : font_color,\n }\n axis_label_font_dict = {\n 'fontsize': 16,\n 'color' : font_color,\n }\n\n ax.tick_params(axis = \"x\", which = \"both\", bottom = False, top = False)\n ax.axes.yaxis.set_ticks([])\n ax.tick_params(axis='x', which='major', labelsize=14)\n\n ax.set_title('Classification Report', fontdict=title_font_dict, pad=25)\n ax.set_xlabel('Observed Class', fontdict=axis_label_font_dict, labelpad=10)\n ax.set_ylabel('Predicted Class', fontdict=axis_label_font_dict, labelpad=35)\n\n legend_elements = [Patch(facecolor=all_colors[i], label='Class {}'.format(i)) for i in range(n_classes)]\n ax.legend(handles=legend_elements, bbox_to_anchor=(1,1.018), fontsize=16)\n\n plt.tight_layout()\n plt.show()\n" }, { "code": null, "e": 6276, "s": 6047, "text": "n_classes = 4 # number of classes\nresults = [\n [50, 4, 1, 2], # predictions for class 1\n [1, 40, 4, 3], # predictions for class 2\n [3, 2, 30, 1], # predictions for class 3\n [1, 3, 1, 60], # predictions for class 4\n]\n" }, { "code": null, "e": 6331, "s": 6276, "text": "nclass_classification_mosaic_plot(n_classes, results)\n" } ]
How to remove rows in an R data frame column that has duplicate values greater than or equal to a certain number of times?
To remove rows from the data frame that duplicate values greater than a certain number of times, we can create a subset for rows having duplicate values less than the certain number of times. For this purpose, we first need to extract the rows and then subset the data frame with the particular column as shown in the below examples. Consider the below data frame − Live Demo > x1<-rpois(20,1) > x2<-rpois(20,1) > df1<-data.frame(x1,x2) > df1 x1 x2 1 0 0 2 0 0 3 1 0 4 0 1 5 0 0 6 1 1 7 0 1 8 1 1 9 1 2 10 0 0 11 1 1 12 0 0 13 1 1 14 2 2 15 1 1 16 1 0 17 1 1 18 0 3 19 2 0 20 0 0 Removing rows based on x1 that has number of duplicate values greater than or equal to 3 − df1[df1$x1 %in% names(which(table(df1$x1)<3)),] x1 x2 14 2 2 19 2 0 Live Demo > y1<-rpois(20,2) > y2<-rpois(20,2) > y3<-rpois(20,2) > df2<-data.frame(y1,y2,y3) > df2 y1 y2 y3 1 2 2 1 2 1 2 0 3 1 2 3 4 3 1 4 5 2 1 1 6 2 1 2 7 1 0 1 8 0 3 5 9 6 1 3 10 2 2 2 11 0 3 0 12 2 2 3 13 3 2 0 14 2 2 4 15 1 0 1 16 1 1 2 17 3 1 3 18 2 4 1 19 0 1 2 20 0 0 0 Removing rows based on y2 that has number of duplicate values greater than or equal to 2 − > df2[df2$y2 %in% names(which(table(df2$y2)<2)),] y1 y2 y3 18 2 4 1 Live Demo > z1<-rpois(20,2) > z2<-rpois(20,2) > z3<-rpois(20,2) > z4<-rpois(20,2) > df3<-data.frame(z1,z2,z3,z4) > df3 z1 z2 z3 z4 1 5 1 3 3 2 1 1 3 3 3 1 1 2 5 4 1 1 2 6 5 3 5 0 1 6 1 3 1 1 7 0 2 0 0 8 2 0 1 2 9 4 1 3 1 10 3 2 1 1 11 1 0 1 1 12 2 3 0 4 13 0 1 2 1 14 2 3 3 2 15 4 2 0 4 16 1 4 2 2 17 0 2 2 3 18 2 1 2 1 19 4 3 4 1 20 3 3 5 2 Removing rows based on z1 that has number of duplicate values greater than or equal to 2 − > df3[df3$z1 %in% names(which(table(df3$z1)<2)),] z1 z2 z3 z4 1 5 1 3 3
[ { "code": null, "e": 1396, "s": 1062, "text": "To remove rows from the data frame that duplicate values greater than a certain number of times, we can create a subset for rows having duplicate values less than the certain number of times. For this purpose, we first need to extract the rows and then subset the data frame with the particular column as shown in the below examples." }, { "code": null, "e": 1428, "s": 1396, "text": "Consider the below data frame −" }, { "code": null, "e": 1438, "s": 1428, "text": "Live Demo" }, { "code": null, "e": 1505, "s": 1438, "text": "> x1<-rpois(20,1)\n> x2<-rpois(20,1)\n> df1<-data.frame(x1,x2)\n> df1" }, { "code": null, "e": 1674, "s": 1505, "text": " x1 x2\n1 0 0\n2 0 0\n3 1 0\n4 0 1\n5 0 0\n6 1 1\n7 0 1\n8 1 1\n9 1 2\n10 0 0\n11 1 1\n12 0 0\n13 1 1\n14 2 2\n15 1 1\n16 1 0\n17 1 1\n18 0 3\n19 2 0\n20 0 0" }, { "code": null, "e": 1765, "s": 1674, "text": "Removing rows based on x1 that has number of duplicate values greater than or equal to 3 −" }, { "code": null, "e": 1813, "s": 1765, "text": "df1[df1$x1 %in% names(which(table(df1$x1)<3)),]" }, { "code": null, "e": 1838, "s": 1813, "text": " x1 x2\n14 2 2\n19 2 0" }, { "code": null, "e": 1848, "s": 1838, "text": "Live Demo" }, { "code": null, "e": 1936, "s": 1848, "text": "> y1<-rpois(20,2)\n> y2<-rpois(20,2)\n> y3<-rpois(20,2)\n> df2<-data.frame(y1,y2,y3)\n> df2" }, { "code": null, "e": 2168, "s": 1936, "text": " y1 y2 y3\n1 2 2 1\n2 1 2 0\n3 1 2 3\n4 3 1 4\n5 2 1 1\n6 2 1 2\n7 1 0 1\n8 0 3 5\n9 6 1 3\n10 2 2 2\n11 0 3 0\n12 2 2 3\n13 3 2 0\n14 2 2 4\n15 1 0 1\n16 1 1 2\n17 3 1 3\n18 2 4 1\n19 0 1 2\n20 0 0 0" }, { "code": null, "e": 2259, "s": 2168, "text": "Removing rows based on y2 that has number of duplicate values greater than or equal to 2 −" }, { "code": null, "e": 2309, "s": 2259, "text": "> df2[df2$y2 %in% names(which(table(df2$y2)<2)),]" }, { "code": null, "e": 2332, "s": 2309, "text": " y1 y2 y3\n18 2 4 1" }, { "code": null, "e": 2342, "s": 2332, "text": "Live Demo" }, { "code": null, "e": 2451, "s": 2342, "text": "> z1<-rpois(20,2)\n> z2<-rpois(20,2)\n> z3<-rpois(20,2)\n> z4<-rpois(20,2)\n> df3<-data.frame(z1,z2,z3,z4)\n> df3" }, { "code": null, "e": 2746, "s": 2451, "text": " z1 z2 z3 z4\n1 5 1 3 3\n2 1 1 3 3\n3 1 1 2 5\n4 1 1 2 6\n5 3 5 0 1\n6 1 3 1 1\n7 0 2 0 0\n8 2 0 1 2\n9 4 1 3 1\n10 3 2 1 1\n11 1 0 1 1\n12 2 3 0 4\n13 0 1 2 1\n14 2 3 3 2\n15 4 2 0 4\n16 1 4 2 2\n17 0 2 2 3\n18 2 1 2 1\n19 4 3 4 1\n20 3 3 5 2" }, { "code": null, "e": 2837, "s": 2746, "text": "Removing rows based on z1 that has number of duplicate values greater than or equal to 2 −" }, { "code": null, "e": 2887, "s": 2837, "text": "> df3[df3$z1 %in% names(which(table(df3$z1)<2)),]" }, { "code": null, "e": 2914, "s": 2887, "text": " z1 z2 z3 z4\n1 5 1 3 3" } ]
Java Examples - Use of enum & switch statement
How to use enum & switch statement ? This example displays how to check which enum member is selected using Switch statements. enum Car { lamborghini,tata,audi,fiat,honda } public class Main { public static void main(String args[]){ Car c; c = Car.tata; switch(c) { case lamborghini: System.out.println("You choose lamborghini!"); break; case tata: System.out.println("You choose tata!"); break; case audi: System.out.println("You choose audi!"); break; case fiat: System.out.println("You choose fiat!"); break; case honda: System.out.println("You choose honda!"); break; default: System.out.println("I don't know your car."); break; } } } The above code sample will produce the following result. You choose tata! The following is an another example of enum & switch statement public class MainClass { enum Choice { Choice1, Choice2, Choice3 } public static void main(String[] args) { Choice ch = Choice.Choice1; switch(ch) { case Choice1: System.out.println("Choice1 selected"); break; case Choice2: System.out.println("Choice2 selected"); break; case Choice3: System.out.println("Choice3 selected"); break; } } } The above code sample will produce the following result. Choice1 selected Print Add Notes Bookmark this page
[ { "code": null, "e": 2105, "s": 2068, "text": "How to use enum & switch statement ?" }, { "code": null, "e": 2195, "s": 2105, "text": "This example displays how to check which enum member is selected using Switch statements." }, { "code": null, "e": 2939, "s": 2195, "text": "enum Car {\n lamborghini,tata,audi,fiat,honda\n}\npublic class Main {\n public static void main(String args[]){\n Car c;\n c = Car.tata;\n switch(c) {\n case lamborghini:\n System.out.println(\"You choose lamborghini!\");\n break;\n case tata:\n System.out.println(\"You choose tata!\");\n break;\n case audi:\n System.out.println(\"You choose audi!\");\n break;\n case fiat:\n System.out.println(\"You choose fiat!\");\n break;\n case honda:\n System.out.println(\"You choose honda!\");\n break;\n default:\n System.out.println(\"I don't know your car.\");\n break;\n }\n }\n}" }, { "code": null, "e": 2996, "s": 2939, "text": "The above code sample will produce the following result." }, { "code": null, "e": 3014, "s": 2996, "text": "You choose tata!\n" }, { "code": null, "e": 3077, "s": 3014, "text": "The following is an another example of enum & switch statement" }, { "code": null, "e": 3543, "s": 3077, "text": "public class MainClass {\n enum Choice { Choice1, Choice2, Choice3 }\n public static void main(String[] args) {\n Choice ch = Choice.Choice1;\n\n switch(ch) {\n case Choice1:\n System.out.println(\"Choice1 selected\");\n break;\n case Choice2:\n System.out.println(\"Choice2 selected\");\n break;\n case Choice3:\n System.out.println(\"Choice3 selected\");\n break;\n }\n }\n}" }, { "code": null, "e": 3600, "s": 3543, "text": "The above code sample will produce the following result." }, { "code": null, "e": 3618, "s": 3600, "text": "Choice1 selected\n" }, { "code": null, "e": 3625, "s": 3618, "text": " Print" }, { "code": null, "e": 3636, "s": 3625, "text": " Add Notes" } ]
Important Topics for GATE 2020 Computer Science
16 Sep, 2021 GATE CS 2022 TS These topics are categorized based on the previous GATE CS Papers: Propositional logic and predicate logic Matrix determinant and eigen values Conditional probability Graph connectivity Relations Mathematical logic Linear algebra Propositional logic Linear algebra Graph theory Probability Predicate logic Groups functions Lattice theory Counting Algorithm Analysis Heap trees Sorting Graph Algorithms Sorting algorithms Searching and sorting algorithms Divide and conquer Greedy algorithms Divide and conquer Dynamic programming algorithms Recursive programs Trees and graphs Trees Stacks and Queues Trees Recursive functions, and pointers CPU Scheduling Algorithms Paging Semaphores Page replacement algorithms Page replacement algorithms Paging CPU Scheduling Page replacement Semaphore Paging and Segmentation Disk scheduling algorithms Deadlock Relational Algebra SQL Serializability Relational Tuple SQL queries Normalization Relational algebra Transactions SQL ER-diagrams IP Addressing TCP and UDP Application protocols Congestion control IP Addressing TCP Ethernet IP addressing Routing Algorithms Encryption and Decryption algorithms Pipelining Cache organization Addressing modes Cache organization Addressing modes and Machine cycles Cache organization Pipelining I/O Data transfer DFA and Regular expression Closure properties and Undecidability Regular languages Undecidability Regular expressions Closure properties Undecidability CFL and DCFL Formal grammars and CNF LL(1) and LR parsers Parsing Lexical Analysis and syntax Analysis Intermediate code generation Syntax directed translations(SDTs) Run time environments Combinational circuits: Multiplexer, decoder and demultiplexer Minimization Counters Combinational circuits Minimization Combinational circuits Sequential circuits Number system, fixed and floating point numbers Registers Numerical computation Data interpretation Sentence completion Word analogies GATE CS 2019 topic wise notesGATE CS Previous Year Solved PapersLast minutes notes for GATE CS GATE CS 2019 topic wise notes GATE CS Previous Year Solved Papers Last minutes notes for GATE CS If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. nnr223442 Articles GATE GATE CS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n16 Sep, 2021" }, { "code": null, "e": 70, "s": 54, "text": "GATE CS 2022 TS" }, { "code": null, "e": 137, "s": 70, "text": "These topics are categorized based on the previous GATE CS Papers:" }, { "code": null, "e": 177, "s": 137, "text": "Propositional logic and predicate logic" }, { "code": null, "e": 213, "s": 177, "text": "Matrix determinant and eigen values" }, { "code": null, "e": 237, "s": 213, "text": "Conditional probability" }, { "code": null, "e": 256, "s": 237, "text": "Graph connectivity" }, { "code": null, "e": 266, "s": 256, "text": "Relations" }, { "code": null, "e": 285, "s": 266, "text": "Mathematical logic" }, { "code": null, "e": 300, "s": 285, "text": "Linear algebra" }, { "code": null, "e": 320, "s": 300, "text": "Propositional logic" }, { "code": null, "e": 335, "s": 320, "text": "Linear algebra" }, { "code": null, "e": 348, "s": 335, "text": "Graph theory" }, { "code": null, "e": 360, "s": 348, "text": "Probability" }, { "code": null, "e": 376, "s": 360, "text": "Predicate logic" }, { "code": null, "e": 383, "s": 376, "text": "Groups" }, { "code": null, "e": 393, "s": 383, "text": "functions" }, { "code": null, "e": 408, "s": 393, "text": "Lattice theory" }, { "code": null, "e": 417, "s": 408, "text": "Counting" }, { "code": null, "e": 436, "s": 417, "text": "Algorithm Analysis" }, { "code": null, "e": 447, "s": 436, "text": "Heap trees" }, { "code": null, "e": 455, "s": 447, "text": "Sorting" }, { "code": null, "e": 472, "s": 455, "text": "Graph Algorithms" }, { "code": null, "e": 491, "s": 472, "text": "Sorting algorithms" }, { "code": null, "e": 524, "s": 491, "text": "Searching and sorting algorithms" }, { "code": null, "e": 543, "s": 524, "text": "Divide and conquer" }, { "code": null, "e": 561, "s": 543, "text": "Greedy algorithms" }, { "code": null, "e": 580, "s": 561, "text": "Divide and conquer" }, { "code": null, "e": 611, "s": 580, "text": "Dynamic programming algorithms" }, { "code": null, "e": 630, "s": 611, "text": "Recursive programs" }, { "code": null, "e": 647, "s": 630, "text": "Trees and graphs" }, { "code": null, "e": 653, "s": 647, "text": "Trees" }, { "code": null, "e": 671, "s": 653, "text": "Stacks and Queues" }, { "code": null, "e": 677, "s": 671, "text": "Trees" }, { "code": null, "e": 711, "s": 677, "text": "Recursive functions, and pointers" }, { "code": null, "e": 737, "s": 711, "text": "CPU Scheduling Algorithms" }, { "code": null, "e": 744, "s": 737, "text": "Paging" }, { "code": null, "e": 755, "s": 744, "text": "Semaphores" }, { "code": null, "e": 783, "s": 755, "text": "Page replacement algorithms" }, { "code": null, "e": 811, "s": 783, "text": "Page replacement algorithms" }, { "code": null, "e": 818, "s": 811, "text": "Paging" }, { "code": null, "e": 833, "s": 818, "text": "CPU Scheduling" }, { "code": null, "e": 850, "s": 833, "text": "Page replacement" }, { "code": null, "e": 860, "s": 850, "text": "Semaphore" }, { "code": null, "e": 884, "s": 860, "text": "Paging and Segmentation" }, { "code": null, "e": 911, "s": 884, "text": "Disk scheduling algorithms" }, { "code": null, "e": 920, "s": 911, "text": "Deadlock" }, { "code": null, "e": 939, "s": 920, "text": "Relational Algebra" }, { "code": null, "e": 943, "s": 939, "text": "SQL" }, { "code": null, "e": 959, "s": 943, "text": "Serializability" }, { "code": null, "e": 970, "s": 959, "text": "Relational" }, { "code": null, "e": 976, "s": 970, "text": "Tuple" }, { "code": null, "e": 988, "s": 976, "text": "SQL queries" }, { "code": null, "e": 1002, "s": 988, "text": "Normalization" }, { "code": null, "e": 1021, "s": 1002, "text": "Relational algebra" }, { "code": null, "e": 1034, "s": 1021, "text": "Transactions" }, { "code": null, "e": 1038, "s": 1034, "text": "SQL" }, { "code": null, "e": 1050, "s": 1038, "text": "ER-diagrams" }, { "code": null, "e": 1064, "s": 1050, "text": "IP Addressing" }, { "code": null, "e": 1076, "s": 1064, "text": "TCP and UDP" }, { "code": null, "e": 1098, "s": 1076, "text": "Application protocols" }, { "code": null, "e": 1117, "s": 1098, "text": "Congestion control" }, { "code": null, "e": 1131, "s": 1117, "text": "IP Addressing" }, { "code": null, "e": 1135, "s": 1131, "text": "TCP" }, { "code": null, "e": 1144, "s": 1135, "text": "Ethernet" }, { "code": null, "e": 1158, "s": 1144, "text": "IP addressing" }, { "code": null, "e": 1177, "s": 1158, "text": "Routing Algorithms" }, { "code": null, "e": 1214, "s": 1177, "text": "Encryption and Decryption algorithms" }, { "code": null, "e": 1225, "s": 1214, "text": "Pipelining" }, { "code": null, "e": 1244, "s": 1225, "text": "Cache organization" }, { "code": null, "e": 1261, "s": 1244, "text": "Addressing modes" }, { "code": null, "e": 1280, "s": 1261, "text": "Cache organization" }, { "code": null, "e": 1316, "s": 1280, "text": "Addressing modes and Machine cycles" }, { "code": null, "e": 1335, "s": 1316, "text": "Cache organization" }, { "code": null, "e": 1346, "s": 1335, "text": "Pipelining" }, { "code": null, "e": 1364, "s": 1346, "text": "I/O Data transfer" }, { "code": null, "e": 1391, "s": 1364, "text": "DFA and Regular expression" }, { "code": null, "e": 1429, "s": 1391, "text": "Closure properties and Undecidability" }, { "code": null, "e": 1447, "s": 1429, "text": "Regular languages" }, { "code": null, "e": 1462, "s": 1447, "text": "Undecidability" }, { "code": null, "e": 1482, "s": 1462, "text": "Regular expressions" }, { "code": null, "e": 1501, "s": 1482, "text": "Closure properties" }, { "code": null, "e": 1516, "s": 1501, "text": "Undecidability" }, { "code": null, "e": 1529, "s": 1516, "text": "CFL and DCFL" }, { "code": null, "e": 1553, "s": 1529, "text": "Formal grammars and CNF" }, { "code": null, "e": 1574, "s": 1553, "text": "LL(1) and LR parsers" }, { "code": null, "e": 1582, "s": 1574, "text": "Parsing" }, { "code": null, "e": 1619, "s": 1582, "text": "Lexical Analysis and syntax Analysis" }, { "code": null, "e": 1648, "s": 1619, "text": "Intermediate code generation" }, { "code": null, "e": 1683, "s": 1648, "text": "Syntax directed translations(SDTs)" }, { "code": null, "e": 1705, "s": 1683, "text": "Run time environments" }, { "code": null, "e": 1768, "s": 1705, "text": "Combinational circuits: Multiplexer, decoder and demultiplexer" }, { "code": null, "e": 1781, "s": 1768, "text": "Minimization" }, { "code": null, "e": 1790, "s": 1781, "text": "Counters" }, { "code": null, "e": 1813, "s": 1790, "text": "Combinational circuits" }, { "code": null, "e": 1826, "s": 1813, "text": "Minimization" }, { "code": null, "e": 1849, "s": 1826, "text": "Combinational circuits" }, { "code": null, "e": 1869, "s": 1849, "text": "Sequential circuits" }, { "code": null, "e": 1917, "s": 1869, "text": "Number system, fixed and floating point numbers" }, { "code": null, "e": 1927, "s": 1917, "text": "Registers" }, { "code": null, "e": 1949, "s": 1927, "text": "Numerical computation" }, { "code": null, "e": 1969, "s": 1949, "text": "Data interpretation" }, { "code": null, "e": 1989, "s": 1969, "text": "Sentence completion" }, { "code": null, "e": 2004, "s": 1989, "text": "Word analogies" }, { "code": null, "e": 2099, "s": 2004, "text": "GATE CS 2019 topic wise notesGATE CS Previous Year Solved PapersLast minutes notes for GATE CS" }, { "code": null, "e": 2129, "s": 2099, "text": "GATE CS 2019 topic wise notes" }, { "code": null, "e": 2165, "s": 2129, "text": "GATE CS Previous Year Solved Papers" }, { "code": null, "e": 2196, "s": 2165, "text": "Last minutes notes for GATE CS" }, { "code": null, "e": 2447, "s": 2196, "text": "If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 2572, "s": 2447, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 2582, "s": 2572, "text": "nnr223442" }, { "code": null, "e": 2591, "s": 2582, "text": "Articles" }, { "code": null, "e": 2596, "s": 2591, "text": "GATE" }, { "code": null, "e": 2604, "s": 2596, "text": "GATE CS" } ]
Output of C++ programs | Set 34 (File Handling)
07 Feb, 2022 What task does the following program perform? What task does the following program perform? CPP #include<iostream>#include<fstream>using namespace std; int main(){ ofstream ofile; ofile.open ("text.txt"); ofile << "geeksforgeeks" << endl; cout << "Data written to file" << endl; ofile.close(); return 0;} Answer: Answer: The program prints "geeksforgeeks" in the file text.txt Description: When an object is created for ofstream class, it allows us to write into a file just like cout. When opening a file with ofstream object if file is present then the content is erased else it is created. What task does the following program perform? Description: When an object is created for ofstream class, it allows us to write into a file just like cout. When opening a file with ofstream object if file is present then the content is erased else it is created. What task does the following program perform? CPP #include<iostream>#include<fstream>using namespace std; int main(){ char data[100]; ifstream ifile; //create a text file before executing. ifile.open ("text.txt"); while ( !ifile.eof() ) { ifile.getline (data, 100); cout << data << endl; } ifile.close(); return 0;} Answer: Answer: The program takes input from text.txt file and then prints on the terminal. Description: When an object is created for ifstream class, it allows us to input from a file just like cin. getline takes the entire line at once. What is the Output of following program? Description: When an object is created for ifstream class, it allows us to input from a file just like cin. getline takes the entire line at once. What is the Output of following program? CPP #include<iostream>#include<fstream>#include<string>#include<cctype> using namespace std; int main(){ ifstream ifile; ifile.open ("text.txt"); cout << "Reading data from a file :-" << endl ; int c = ifile.peek(); if ( c == EOF ) return 1; if ( isdigit(c) ) { int n; ifile >> n; cout << "Data in the file: " << n << '\n'; } else { string str; ifile >> str; cout << "Data in the file: " << str << '\n'; } ifile.close(); return 0;} Output: Output: Reading data from a file:- Data in the file: /*content of the file */ Description: peek() obtains the next character in the input stream without removing it from that stream. The function accesses the input sequence by first constructing a object. Then, it reads one character from its associated stream buffer object(ifile) by calling its member function sgetc, and finally destroys the object before returning. What will be the changes made to the content of the file after running the code? Description: peek() obtains the next character in the input stream without removing it from that stream. The function accesses the input sequence by first constructing a object. Then, it reads one character from its associated stream buffer object(ifile) by calling its member function sgetc, and finally destroys the object before returning. What will be the changes made to the content of the file after running the code? CPP #include <iostream>#include <fstream> using namespace std; int main (){ //create a text file named file before running. ofstream ofile; ofile.open ("file.txt"); ofile<< "geeksforgeeks", 13; ofile.seekp (8); ofile<< " geeks", 6; ofile.close(); return 0;} Output: Output: content of file before: geeksforgeeks contents of the file after execution: geeksfor geeks Description: seekp() is used to move the put pointer to a desired location with respect to a reference point. Using this function the stream pointer is changed to the absolute position (counting from the beginning of the file). In this program the following will write in the file. Description: seekp() is used to move the put pointer to a desired location with respect to a reference point. Using this function the stream pointer is changed to the absolute position (counting from the beginning of the file). In this program the following will write in the file. ofile<< "geeksforgeeks", 13; then ofile.seekp(8) will place the pointer at 8th position from the beginning and then the following will be printed. then ofile.seekp(8) will place the pointer at 8th position from the beginning and then the following will be printed. ofile<< " geeks", 6; What is the Output of following program? What is the Output of following program? CPP #include <iostream> #include <fstream>#include <cctype> using namespace std; int main (){ ifstream ifile; ifile.open ("text.txt"); //content of file: geeksfor geeks char last; ifile.ignore (256, ' '); last = ifile.get(); cout << "Your initial is " << last << '\n'; ifile.close(); return 0;} Output: Output: Your initial is g Description: ignore(256, ‘ ‘) Extracts characters from the input sequence and discards them, until either 256 characters have been extracted, or one compares equal to ‘ ‘.This program prints the first character of the second word in the file. Description: ignore(256, ‘ ‘) Extracts characters from the input sequence and discards them, until either 256 characters have been extracted, or one compares equal to ‘ ‘.This program prints the first character of the second word in the file. This article is contributed by I.HARISH KUMAR. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. sumitgumber28 varshagumber28 CPP-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 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 Output of Java Program | Set 7 Output of C Programs | Set 3
[ { "code": null, "e": 54, "s": 26, "text": "\n07 Feb, 2022" }, { "code": null, "e": 102, "s": 54, "text": "What task does the following program perform? " }, { "code": null, "e": 150, "s": 102, "text": "What task does the following program perform? " }, { "code": null, "e": 154, "s": 150, "text": "CPP" }, { "code": "#include<iostream>#include<fstream>using namespace std; int main(){ ofstream ofile; ofile.open (\"text.txt\"); ofile << \"geeksforgeeks\" << endl; cout << \"Data written to file\" << endl; ofile.close(); return 0;}", "e": 375, "s": 154, "text": null }, { "code": null, "e": 385, "s": 375, "text": "Answer: " }, { "code": null, "e": 395, "s": 385, "text": "Answer: " }, { "code": null, "e": 452, "s": 395, "text": " The program prints \"geeksforgeeks\" in the file text.txt" }, { "code": null, "e": 717, "s": 452, "text": "Description: When an object is created for ofstream class, it allows us to write into a file just like cout. When opening a file with ofstream object if file is present then the content is erased else it is created. What task does the following program perform? " }, { "code": null, "e": 935, "s": 717, "text": "Description: When an object is created for ofstream class, it allows us to write into a file just like cout. When opening a file with ofstream object if file is present then the content is erased else it is created. " }, { "code": null, "e": 983, "s": 935, "text": "What task does the following program perform? " }, { "code": null, "e": 987, "s": 983, "text": "CPP" }, { "code": "#include<iostream>#include<fstream>using namespace std; int main(){ char data[100]; ifstream ifile; //create a text file before executing. ifile.open (\"text.txt\"); while ( !ifile.eof() ) { ifile.getline (data, 100); cout << data << endl; } ifile.close(); return 0;}", "e": 1299, "s": 987, "text": null }, { "code": null, "e": 1309, "s": 1299, "text": "Answer: " }, { "code": null, "e": 1319, "s": 1309, "text": "Answer: " }, { "code": null, "e": 1395, "s": 1319, "text": "The program takes input from text.txt file and then prints on the terminal." }, { "code": null, "e": 1585, "s": 1395, "text": "Description: When an object is created for ifstream class, it allows us to input from a file just like cin. getline takes the entire line at once. What is the Output of following program? " }, { "code": null, "e": 1733, "s": 1585, "text": "Description: When an object is created for ifstream class, it allows us to input from a file just like cin. getline takes the entire line at once. " }, { "code": null, "e": 1776, "s": 1733, "text": "What is the Output of following program? " }, { "code": null, "e": 1780, "s": 1776, "text": "CPP" }, { "code": "#include<iostream>#include<fstream>#include<string>#include<cctype> using namespace std; int main(){ ifstream ifile; ifile.open (\"text.txt\"); cout << \"Reading data from a file :-\" << endl ; int c = ifile.peek(); if ( c == EOF ) return 1; if ( isdigit(c) ) { int n; ifile >> n; cout << \"Data in the file: \" << n << '\\n'; } else { string str; ifile >> str; cout << \"Data in the file: \" << str << '\\n'; } ifile.close(); return 0;}", "e": 2294, "s": 1780, "text": null }, { "code": null, "e": 2304, "s": 2294, "text": "Output: " }, { "code": null, "e": 2314, "s": 2304, "text": "Output: " }, { "code": null, "e": 2384, "s": 2314, "text": "Reading data from a file:-\nData in the file:\n/*content of the file */" }, { "code": null, "e": 2810, "s": 2384, "text": "Description: peek() obtains the next character in the input stream without removing it from that stream. The function accesses the input sequence by first constructing a object. Then, it reads one character from its associated stream buffer object(ifile) by calling its member function sgetc, and finally destroys the object before returning. What will be the changes made to the content of the file after running the code? " }, { "code": null, "e": 3154, "s": 2810, "text": "Description: peek() obtains the next character in the input stream without removing it from that stream. The function accesses the input sequence by first constructing a object. Then, it reads one character from its associated stream buffer object(ifile) by calling its member function sgetc, and finally destroys the object before returning. " }, { "code": null, "e": 3237, "s": 3154, "text": "What will be the changes made to the content of the file after running the code? " }, { "code": null, "e": 3241, "s": 3237, "text": "CPP" }, { "code": "#include <iostream>#include <fstream> using namespace std; int main (){ //create a text file named file before running. ofstream ofile; ofile.open (\"file.txt\"); ofile<< \"geeksforgeeks\", 13; ofile.seekp (8); ofile<< \" geeks\", 6; ofile.close(); return 0;}", "e": 3537, "s": 3241, "text": null }, { "code": null, "e": 3547, "s": 3537, "text": "Output: " }, { "code": null, "e": 3557, "s": 3547, "text": "Output: " }, { "code": null, "e": 3649, "s": 3557, "text": "content of file before:\ngeeksforgeeks\n\ncontents of the file after execution:\ngeeksfor geeks" }, { "code": null, "e": 3933, "s": 3649, "text": "Description: seekp() is used to move the put pointer to a desired location with respect to a reference point. Using this function the stream pointer is changed to the absolute position (counting from the beginning of the file). In this program the following will write in the file. " }, { "code": null, "e": 4217, "s": 3933, "text": "Description: seekp() is used to move the put pointer to a desired location with respect to a reference point. Using this function the stream pointer is changed to the absolute position (counting from the beginning of the file). In this program the following will write in the file. " }, { "code": null, "e": 4246, "s": 4217, "text": "ofile<< \"geeksforgeeks\", 13;" }, { "code": null, "e": 4366, "s": 4246, "text": "then ofile.seekp(8) will place the pointer at 8th position from the beginning and then the following will be printed. " }, { "code": null, "e": 4486, "s": 4366, "text": "then ofile.seekp(8) will place the pointer at 8th position from the beginning and then the following will be printed. " }, { "code": null, "e": 4507, "s": 4486, "text": "ofile<< \" geeks\", 6;" }, { "code": null, "e": 4550, "s": 4507, "text": "What is the Output of following program? " }, { "code": null, "e": 4593, "s": 4550, "text": "What is the Output of following program? " }, { "code": null, "e": 4597, "s": 4593, "text": "CPP" }, { "code": "#include <iostream> #include <fstream>#include <cctype> using namespace std; int main (){ ifstream ifile; ifile.open (\"text.txt\"); //content of file: geeksfor geeks char last; ifile.ignore (256, ' '); last = ifile.get(); cout << \"Your initial is \" << last << '\\n'; ifile.close(); return 0;}", "e": 4932, "s": 4597, "text": null }, { "code": null, "e": 4942, "s": 4932, "text": "Output: " }, { "code": null, "e": 4952, "s": 4942, "text": "Output: " }, { "code": null, "e": 4970, "s": 4952, "text": "Your initial is g" }, { "code": null, "e": 5215, "s": 4970, "text": "Description: ignore(256, ‘ ‘) Extracts characters from the input sequence and discards them, until either 256 characters have been extracted, or one compares equal to ‘ ‘.This program prints the first character of the second word in the file. " }, { "code": null, "e": 5460, "s": 5215, "text": "Description: ignore(256, ‘ ‘) Extracts characters from the input sequence and discards them, until either 256 characters have been extracted, or one compares equal to ‘ ‘.This program prints the first character of the second word in the file. " }, { "code": null, "e": 5887, "s": 5460, "text": "This article is contributed by I.HARISH KUMAR. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 5901, "s": 5887, "text": "sumitgumber28" }, { "code": null, "e": 5916, "s": 5901, "text": "varshagumber28" }, { "code": null, "e": 5927, "s": 5916, "text": "CPP-Output" }, { "code": null, "e": 5942, "s": 5927, "text": "Program Output" }, { "code": null, "e": 6040, "s": 5942, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6055, "s": 6040, "text": "Runtime Errors" }, { "code": null, "e": 6084, "s": 6055, "text": "Output of C Programs | Set 2" }, { "code": null, "e": 6125, "s": 6084, "text": "Different ways to copy a string in C/C++" }, { "code": null, "e": 6158, "s": 6125, "text": "Output of Python Program | Set 1" }, { "code": null, "e": 6189, "s": 6158, "text": "Output of Java Program | Set 2" }, { "code": null, "e": 6220, "s": 6189, "text": "Output of Java Program | Set 3" }, { "code": null, "e": 6263, "s": 6220, "text": "Output of C++ programs | Set 47 (Pointers)" }, { "code": null, "e": 6296, "s": 6263, "text": "Output of Java Programs | Set 12" }, { "code": null, "e": 6327, "s": 6296, "text": "Output of Java Program | Set 7" } ]
How to capitalize first character of string in Python
29 Jun, 2022 The problem of case changes in a string is quite common and has been discussed many times. Sometimes, we might have a problem like this in which we need to convert the initial character of the string to the upper case. Let’s discuss certain ways in which this can be performed. Method #1: Using string slicing + upper() This task can easily be performed using the upper method which uppercases the characters provided to it and slicing can be used to add the remaining string after the lowercase first character. Python3 # Python3 code to demonstrate working of# Initial character upper case# Using upper() + string slicing # initializing stringtest_str = "geeksforgeeks & quot # printing original stringprint(& quot The original string is : & quot + str(test_str)) # Using upper() + string slicing# Initial character upper caseres = test_str[0].upper() + test_str[1:] # printing resultprint(& quot The string after uppercasing initial character : & quot + str(res)) The original string is : geeksforgeeks The string after uppercasing initial character : Geeksforgeeks Method #2 : Using capitalize() We can use the inbuilt method to perform this task. This method is recommended to solve this problem and performs the task of converting to upper case internally. Python3 # Python3 code to demonstrate working of# Initial character upper case# Using capitalize() + string slicing # initializing stringtest_str = "geeksforgeeks & quot # printing original stringprint(& quot The original string is : & quot + str(test_str)) # Using capitalize() + string slicing# Initial character upper caseres = test_str.capitalize() # printing resultprint(& quot The string after uppercasing initial character : & quot + str(res)) The original string is : geeksforgeeks The string after uppercasing initial character : Geeksforgeeks Method #3: Using str.title() method We can use string title function to perform this task. Title function convert the first letter of word to upper case and remaining to lower case. Python3 # Python3 code to demonstrate working of# Initial character upper case# Using title function of string # initializing stringtest_str = "geeksforgeeks" # printing original stringprint("The original string is : " + str(test_str)) # Using str.title()# Initial character upper caseres = test_str.title() # printing resultprint("The string after uppercasing initial character : " + str(res)) The original string is : geeksforgeeks The string after uppercasing initial character : Geeksforgeeks satyam00so 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 | os.path.join() method Introduction To PYTHON Python OOPs Concepts 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": "\n29 Jun, 2022" }, { "code": null, "e": 306, "s": 28, "text": "The problem of case changes in a string is quite common and has been discussed many times. Sometimes, we might have a problem like this in which we need to convert the initial character of the string to the upper case. Let’s discuss certain ways in which this can be performed." }, { "code": null, "e": 542, "s": 306, "text": "Method #1: Using string slicing + upper() This task can easily be performed using the upper method which uppercases the characters provided to it and slicing can be used to add the remaining string after the lowercase first character. " }, { "code": null, "e": 550, "s": 542, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of# Initial character upper case# Using upper() + string slicing # initializing stringtest_str = \"geeksforgeeks & quot # printing original stringprint(& quot The original string is : & quot + str(test_str)) # Using upper() + string slicing# Initial character upper caseres = test_str[0].upper() + test_str[1:] # printing resultprint(& quot The string after uppercasing initial character : & quot + str(res))", "e": 1020, "s": 550, "text": null }, { "code": null, "e": 1122, "s": 1020, "text": "The original string is : geeksforgeeks\nThe string after uppercasing initial character : Geeksforgeeks" }, { "code": null, "e": 1317, "s": 1122, "text": "Method #2 : Using capitalize() We can use the inbuilt method to perform this task. This method is recommended to solve this problem and performs the task of converting to upper case internally. " }, { "code": null, "e": 1325, "s": 1317, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of# Initial character upper case# Using capitalize() + string slicing # initializing stringtest_str = \"geeksforgeeks & quot # printing original stringprint(& quot The original string is : & quot + str(test_str)) # Using capitalize() + string slicing# Initial character upper caseres = test_str.capitalize() # printing resultprint(& quot The string after uppercasing initial character : & quot + str(res))", "e": 1792, "s": 1325, "text": null }, { "code": null, "e": 1894, "s": 1792, "text": "The original string is : geeksforgeeks\nThe string after uppercasing initial character : Geeksforgeeks" }, { "code": null, "e": 2077, "s": 1894, "text": "Method #3: Using str.title() method We can use string title function to perform this task. Title function convert the first letter of word to upper case and remaining to lower case. " }, { "code": null, "e": 2085, "s": 2077, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of# Initial character upper case# Using title function of string # initializing stringtest_str = \"geeksforgeeks\" # printing original stringprint(\"The original string is : \" + str(test_str)) # Using str.title()# Initial character upper caseres = test_str.title() # printing resultprint(\"The string after uppercasing initial character : \" + str(res))", "e": 2472, "s": 2085, "text": null }, { "code": null, "e": 2575, "s": 2472, "text": "The original string is : geeksforgeeks\nThe string after uppercasing initial character : Geeksforgeeks\n" }, { "code": null, "e": 2586, "s": 2575, "text": "satyam00so" }, { "code": null, "e": 2609, "s": 2586, "text": "Python string-programs" }, { "code": null, "e": 2616, "s": 2609, "text": "Python" }, { "code": null, "e": 2632, "s": 2616, "text": "Python Programs" }, { "code": null, "e": 2730, "s": 2632, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2762, "s": 2730, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2789, "s": 2762, "text": "Python Classes and Objects" }, { "code": null, "e": 2820, "s": 2789, "text": "Python | os.path.join() method" }, { "code": null, "e": 2843, "s": 2820, "text": "Introduction To PYTHON" }, { "code": null, "e": 2864, "s": 2843, "text": "Python OOPs Concepts" }, { "code": null, "e": 2886, "s": 2864, "text": "Defaultdict in Python" }, { "code": null, "e": 2925, "s": 2886, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 2963, "s": 2925, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 3012, "s": 2963, "text": "Python | Convert string dictionary to dictionary" } ]
Building an undirected graph and finding shortest path using Dictionaries in Python
15 Dec, 2021 Prerequisites: BFS for a Graph Dictionaries in Python In this article, we will be looking at how to build an undirected graph and then find the shortest path between two nodes/vertex of that graph easily using dictionaries in Python Language. Approach: The idea is to store the adjacency list into the dictionaries, which helps to store the graph in any format not only in the form of the integers. Here we have used characters as a reference on those places any custom objects can also be used. Below is the implementation of the above approach: Python3 # Python3 implementation to build a# graph using Dictionaries from collections import defaultdict # Function to build the graphdef build_graph(): edges = [ ["A", "B"], ["A", "E"], ["A", "C"], ["B", "D"], ["B", "E"], ["C", "F"], ["C", "G"], ["D", "E"] ] graph = defaultdict(list) # Loop to iterate over every # edge of the graph for edge in edges: a, b = edge[0], edge[1] # Creating the graph # as adjacency list graph[a].append(b) graph[b].append(a) return graph if __name__ == "__main__": graph = build_graph() print(graph) { 'G': ['C'], 'F': ['C'], 'E': ['A', 'B', 'D'], 'A': ['B', 'E', 'C'], 'B': ['A', 'D', 'E'], 'D': ['B', 'E'], 'C': ['A', 'F', 'G'] } Approach: The idea is to use queue and visit every adjacent node of the starting nodes that traverses the graph in Breadth-First Search manner to find the shortest path between two nodes of the graph. Below is the implementation of the above approach: Python3 # Python implementation to find the# shortest path in the graph using# dictionaries # Function to find the shortest# path between two nodes of a graphdef BFS_SP(graph, start, goal): explored = [] # Queue for traversing the # graph in the BFS queue = [[start]] # If the desired node is # reached if start == goal: print("Same Node") return # Loop to traverse the graph # with the help of the queue while queue: path = queue.pop(0) node = path[-1] # Condition to check if the # current node is not visited if node not in explored: neighbours = graph[node] # Loop to iterate over the # neighbours of the node for neighbour in neighbours: new_path = list(path) new_path.append(neighbour) queue.append(new_path) # Condition to check if the # neighbour node is the goal if neighbour == goal: print("Shortest path = ", *new_path) return explored.append(node) # Condition when the nodes # are not connected print("So sorry, but a connecting"\ "path doesn't exist :(") return # Driver Codeif __name__ == "__main__": # Graph using dictionaries graph = {'A': ['B', 'E', 'C'], 'B': ['A', 'D', 'E'], 'C': ['A', 'F', 'G'], 'D': ['B', 'E'], 'E': ['A', 'B', 'D'], 'F': ['C'], 'G': ['C']} # Function Call BFS_SP(graph, 'A', 'D') Shortest path = A B D simranarora5sos sweetyty Algorithms-Graph Shortest Paths Quiz Python dictionary-programs python-dict Algorithms Data Structures Graph Python Data Structures python-dict Graph Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n15 Dec, 2021" }, { "code": null, "e": 68, "s": 52, "text": "Prerequisites: " }, { "code": null, "e": 84, "s": 68, "text": "BFS for a Graph" }, { "code": null, "e": 107, "s": 84, "text": "Dictionaries in Python" }, { "code": null, "e": 297, "s": 107, "text": "In this article, we will be looking at how to build an undirected graph and then find the shortest path between two nodes/vertex of that graph easily using dictionaries in Python Language. " }, { "code": null, "e": 550, "s": 297, "text": "Approach: The idea is to store the adjacency list into the dictionaries, which helps to store the graph in any format not only in the form of the integers. Here we have used characters as a reference on those places any custom objects can also be used." }, { "code": null, "e": 603, "s": 550, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 611, "s": 603, "text": "Python3" }, { "code": "# Python3 implementation to build a# graph using Dictionaries from collections import defaultdict # Function to build the graphdef build_graph(): edges = [ [\"A\", \"B\"], [\"A\", \"E\"], [\"A\", \"C\"], [\"B\", \"D\"], [\"B\", \"E\"], [\"C\", \"F\"], [\"C\", \"G\"], [\"D\", \"E\"] ] graph = defaultdict(list) # Loop to iterate over every # edge of the graph for edge in edges: a, b = edge[0], edge[1] # Creating the graph # as adjacency list graph[a].append(b) graph[b].append(a) return graph if __name__ == \"__main__\": graph = build_graph() print(graph)", "e": 1245, "s": 611, "text": null }, { "code": null, "e": 1404, "s": 1245, "text": "{\n 'G': ['C'], \n 'F': ['C'], \n 'E': ['A', 'B', 'D'], \n 'A': ['B', 'E', 'C'], \n 'B': ['A', 'D', 'E'], \n 'D': ['B', 'E'], \n 'C': ['A', 'F', 'G']\n}" }, { "code": null, "e": 1607, "s": 1406, "text": "Approach: The idea is to use queue and visit every adjacent node of the starting nodes that traverses the graph in Breadth-First Search manner to find the shortest path between two nodes of the graph." }, { "code": null, "e": 1658, "s": 1607, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 1666, "s": 1658, "text": "Python3" }, { "code": "# Python implementation to find the# shortest path in the graph using# dictionaries # Function to find the shortest# path between two nodes of a graphdef BFS_SP(graph, start, goal): explored = [] # Queue for traversing the # graph in the BFS queue = [[start]] # If the desired node is # reached if start == goal: print(\"Same Node\") return # Loop to traverse the graph # with the help of the queue while queue: path = queue.pop(0) node = path[-1] # Condition to check if the # current node is not visited if node not in explored: neighbours = graph[node] # Loop to iterate over the # neighbours of the node for neighbour in neighbours: new_path = list(path) new_path.append(neighbour) queue.append(new_path) # Condition to check if the # neighbour node is the goal if neighbour == goal: print(\"Shortest path = \", *new_path) return explored.append(node) # Condition when the nodes # are not connected print(\"So sorry, but a connecting\"\\ \"path doesn't exist :(\") return # Driver Codeif __name__ == \"__main__\": # Graph using dictionaries graph = {'A': ['B', 'E', 'C'], 'B': ['A', 'D', 'E'], 'C': ['A', 'F', 'G'], 'D': ['B', 'E'], 'E': ['A', 'B', 'D'], 'F': ['C'], 'G': ['C']} # Function Call BFS_SP(graph, 'A', 'D')", "e": 3310, "s": 1666, "text": null }, { "code": null, "e": 3333, "s": 3310, "text": "Shortest path = A B D" }, { "code": null, "e": 3351, "s": 3335, "text": "simranarora5sos" }, { "code": null, "e": 3360, "s": 3351, "text": "sweetyty" }, { "code": null, "e": 3397, "s": 3360, "text": "Algorithms-Graph Shortest Paths Quiz" }, { "code": null, "e": 3424, "s": 3397, "text": "Python dictionary-programs" }, { "code": null, "e": 3436, "s": 3424, "text": "python-dict" }, { "code": null, "e": 3447, "s": 3436, "text": "Algorithms" }, { "code": null, "e": 3463, "s": 3447, "text": "Data Structures" }, { "code": null, "e": 3469, "s": 3463, "text": "Graph" }, { "code": null, "e": 3476, "s": 3469, "text": "Python" }, { "code": null, "e": 3492, "s": 3476, "text": "Data Structures" }, { "code": null, "e": 3504, "s": 3492, "text": "python-dict" }, { "code": null, "e": 3510, "s": 3504, "text": "Graph" }, { "code": null, "e": 3521, "s": 3510, "text": "Algorithms" } ]
Delete last occurrence of an item from linked list
14 Jun, 2022 Using pointers, loop through the whole list and keep track of the node prior to the node containing the last occurrence key using a special pointer. After this just store the next of next of the special pointer, into to next of special pointer to remove the required node from the linked list. C++ C Java Python3 Javascript #include <iostream>#include <bits/stdc++.h>using namespace std; // A linked list Nodestruct Node{ int data; struct Node* next;}; // Function to delete the last occurrencevoid deleteLast(struct Node** head, int x){ struct Node** tmp1 = NULL; while (*head) { if ((*head)->data == x) { tmp1 = head; } head = &(*head)->next; } if (tmp1) { struct Node* tmp = *tmp1; *tmp1 = tmp->next; free(tmp); }} // Utility function to create a new node with// given keystruct Node* newNode(int x){ Node* node = new Node ; node->data = x; node->next = NULL; return node;} // This function prints contents of linked// list starting from the given Nodevoid display(struct Node* head){ struct Node* temp = head; if (head == NULL) { cout << "NULL\n"; return; } while (temp != NULL) { cout << temp->data <<" --> "; temp = temp->next; } cout << "NULL\n";} // Driver codeint main(){ struct Node* head = newNode(1); head->next = newNode(2); head->next->next = newNode(3); head->next->next->next = newNode(4); head->next->next->next->next = newNode(5); head->next->next->next->next->next = newNode(4); head->next->next->next->next->next->next = newNode(4); cout << "Created Linked list: "; display(head); // Pass the address of the head pointer deleteLast(&head, 4); cout << "List after deletion of 4: "; display(head); return 0;} // This code is contributed by khushboogoyal499 #include <stdio.h>#include <stdlib.h> // A linked list Nodestruct Node { int data; struct Node* next;}; // Function to delete the last occurrencevoid deleteLast(struct Node** head, int x){ struct Node** tmp1 = NULL; while(*head) { if((*head)->data == x) { tmp1 = head; } head = &(*head)->next; } if(tmp1) { struct Node* tmp = *tmp1; *tmp1 = tmp->next; free(tmp); }} /* Utility function to create a new node withgiven key */struct Node* newNode(int x){ struct Node* node = malloc(sizeof(struct Node*)); node->data = x; node->next = NULL; return node;} // This function prints contents of linked list// starting from the given Nodevoid display(struct Node* head){ struct Node* temp = head; if (head == NULL) { printf("NULL\n"); return; } while (temp != NULL) { printf("%d --> ", temp->data); temp = temp->next; } printf("NULL\n");} /* Driver program to test above functions*/int main(){ struct Node* head = newNode(1); head->next = newNode(2); head->next->next = newNode(3); head->next->next->next = newNode(4); head->next->next->next->next = newNode(5); head->next->next->next->next->next = newNode(4); head->next->next->next->next->next->next = newNode(4); printf("Created Linked list: "); display(head); deleteLast(&head, 4); // Pass the address of the head pointer printf("List after deletion of 4: "); display(head); return 0;} import java.io.*; // A linked list Nodeclass Node{ int data; Node next; Node(int data) { this.data = data; this.next = null; }} class GFG{ // Function to delete the last occurrencestatic Node deleteLast(Node head,int x){ Node temp = head; Node ptr = null; while (temp != null) { // If found key, update if (temp.data == x) ptr = temp; temp = temp.next; } // If the last occurrence is the last node if (ptr != null && ptr.next == null) { temp = head; while (temp.next != ptr) { temp = temp.next; } temp.next = null; } // If it is not the last node if (ptr != null && ptr.next != null) { ptr.data = ptr.next.data; temp = ptr.next; ptr.next = ptr.next.next; } return head;} // This function prints contents of linked list// starting from the given Nodestatic void display(Node head){ Node temp = head; if (head == null) { System.out.print("NULL\n"); return; } while (temp != null) { System.out.print( temp.data+" --> "); temp = temp.next; } System.out.print("NULL\n");} // Driver codepublic static void main(String[] args){ Node head = new Node(1); head.next = new Node(2); head.next.next = new Node(3); head.next.next.next = new Node(4); head.next.next.next.next = new Node(5); head.next.next.next.next.next = new Node(4); head.next.next.next.next.next.next = new Node(4); System.out.print("Created Linked list: "); display(head); // Pass the address of the head pointer head = deleteLast(head, 4); System.out.print("List after deletion of 4: "); display(head);}} // This code is contributed by patel2127 # A linked list Nodeclass Node: def __init__(self, new_data): self.data = new_data self.next = None # Function to delete the last occurrencedef deleteLast(head, x): temp = head ptr = None while (temp != None): # If found key, update if (temp.data == x): ptr = temp temp = temp.next # If the last occurrence is the last node if (ptr != None and ptr.next == None): temp = head while (temp.next != ptr): temp = temp.next temp.next = None # If it is not the last node if (ptr != None and ptr.next != None): ptr.data = ptr.next.data temp = ptr.next ptr.next = ptr.next.next return head # Utility function to create a new node# with given keydef newNode(x): node = Node(0) node.data = x node.next = None return node # This function prints contents of linked# list starting from the given Nodedef display(head): temp = head if (head == None): print("NULL\n") return while (temp != None): print( temp.data," --> ", end = "") temp = temp.next print("NULL") # Driver codehead = newNode(1)head.next = newNode(2)head.next.next = newNode(3)head.next.next.next = newNode(4)head.next.next.next.next = newNode(5)head.next.next.next.next.next = newNode(4)head.next.next.next.next.next.next = newNode(4) print("Created Linked list: ", end = '')display(head) # Pass the address of the head pointerhead = deleteLast(head, 4)print("List after deletion of 4: ", end = '') display(head) # This code is contributed by rutvik_56 <script>// A linked list Nodeclass Node{ // Utility function to create a new node // with given key constructor(data) { this.data = data; this.next = null; }} // Function to delete the last occurrencefunction deleteLast(head, x){ let temp = head; let prt = null; while (temp != null) { //If found key, update if (temp.data == x) ptr = temp; temp = temp.next; } // If the last occurrence is the last node if (ptr != null && ptr.next == null) { temp = head; while (temp.next != ptr) { temp = temp.next; } temp.next = null; } // If it is not the last node if (ptr != null && ptr.next != null) { ptr.data = ptr.next.data; temp = ptr.next; ptr.next = ptr.next.next; } return head; } // This function prints contents of linked// list starting from the given Nodefunction display(head){ let temp = head if (head == null) { document.write("NULL<br>"); return; } while (temp != null) { document.write( temp.data," --> ", end = ""); temp = temp.next; } document.write("NULL<br>")} // Driver codelet head = new Node(1)head.next = new Node(2)head.next.next = new Node(3)head.next.next.next = new Node(4)head.next.next.next.next = new Node(5)head.next.next.next.next.next = new Node(4)head.next.next.next.next.next.next = new Node(4); document.write("Created Linked list: ");display(head) // Pass the address of the head pointerhead = deleteLast(head, 4)document.write("List after deletion of 4: ")display(head) // This code is contributed by avanitrachhadiya2155</script> Created Linked list: 1 --> 2 --> 3 --> 4 --> 5 --> 4 --> 4 --> NULL List after deletion of 4: 1 --> 2 --> 3 --> 4 --> 5 --> 4 --> NULL Time Complexity: O(n) Auxiliary Space: O(1) Given a linked list and a key to be deleted. Delete last occurrence of key from linked. The list may have duplicates. Examples: Input: 1->2->3->5->2->10, key = 2 Output: 1->2->3->5->10 The idea is to traverse the linked list from beginning to end. While traversing, keep track of last occurrence key. After traversing the complete list, delete the last occurrence by copying data of next node and deleting the next node. C++ Java Python3 C# Javascript // A C++ program to demonstrate deletion of last// Node in singly linked list#include <bits/stdc++.h> // A linked list Nodestruct Node { int key; struct Node* next;}; void deleteLast(Node* head, int key){ // Initialize previous of Node to be deleted Node* x = NULL; // Start from head and find the Node to be // deleted Node* temp = head; while (temp) { // If we found the key, update xv if (temp->key == key) x = temp; temp = temp->next; } // key occurs at-least once if (x != NULL) { // Copy key of next Node to x x->key = x->next->key; // Store and unlink next temp = x->next; x->next = x->next->next; // Free memory for next delete temp; }} /* Utility function to create a new node with given key */Node* newNode(int key){ Node* temp = new Node; temp->key = key; temp->next = NULL; return temp;} // This function prints contents of linked list// starting from the given Nodevoid printList(struct Node* node){ while (node != NULL) { printf(" %d ", node->key); node = node->next; }} /* Driver program to test above functions*/int main(){ /* Start with the empty list */ struct Node* head = newNode(1); head->next = newNode(2); head->next->next = newNode(3); head->next->next->next = newNode(5); head->next->next->next->next = newNode(2); head->next->next->next->next->next = newNode(10); puts("Created Linked List: "); printList(head); deleteLast(head, 2); puts("\nLinked List after Deletion of 2: "); printList(head); return 0;} // A Java program to demonstrate deletion of last// Node in singly linked listclass GFG{ // A linked list Nodestatic class Node{ int key; Node next;}; static Node deleteLast(Node head, int key){ // Initialize previous of Node to be deleted Node x = null; // Start from head and find the Node to be // deleted Node temp = head; while (temp != null) { // If we found the key, update xv if (temp.key == key) x = temp; temp = temp.next; } // key occurs at-least once if (x != null) { // Copy key of next Node to x x.key = x.next.key; // Store and unlink next temp = x.next; x.next = x.next.next; // Free memory for next } return head;} /// Utility function to create a new node with//given key /static Node newNode(int key){ Node temp = new Node(); temp.key = key; temp.next = null; return temp;} // This function prints contents of linked list// starting from the given Nodestatic void printList( Node node){ while (node != null) { System.out.printf(" %d ", node.key); node = node.next; }} // Driver code/public static void main(String args[]){ // /Start with the empty list / Node head = newNode(1); head.next = newNode(2); head.next.next = newNode(3); head.next.next.next = newNode(5); head.next.next.next.next = newNode(2); head.next.next.next.next.next = newNode(10); System.out.printf("Created Linked List: "); printList(head); deleteLast(head, 2); System.out.printf("\nLinked List after Deletion of 2: "); printList(head);}} // This code is contributed by Arnab Kundu # Python3 program to demonstrate deletion of# last Node in singly linked list # A linked list Nodeclass Node: # Constructor to initialize the node object def __init__(self, data): self.data = data self.next = None def deleteLast(head, key) : # Initialize previous of Node to be deleted x = None # Start from head and find the Node to be # deleted temp = head while (temp != None) : # If we found the key, update xv if (temp.key == key) : x = temp temp = temp.next # key occurs at-least once if (x != None) : # Copy key of next Node to x x.key = x.next.key # Store and unlink next temp = x.next x.next = x.next.next # Free memory for next return head # Utility function to create# a new node with given keydef newNode(key) : temp = Node(0) temp.key = key temp.next = None return temp # This function prints contents of linked list# starting from the given Nodedef printList( node) : while (node != None) : print ( node.key, end = " ") node = node.next # Driver Codeif __name__=='__main__': # Start with the empty list head = newNode(1) head.next = newNode(2) head.next.next = newNode(3) head.next.next.next = newNode(5) head.next.next.next.next = newNode(2) head.next.next.next.next.next = newNode(10) print("Created Linked List: ") printList(head) deleteLast(head, 2) print("\nLinked List after Deletion of 2: ") printList(head) # This code is contributed by Arnab Kundu // C# program to demonstrate deletion of last// Node in singly linked listusing System; class GFG{ // A linked list Nodepublic class Node{ public int key; public Node next;}; static Node deleteLast(Node head, int key){ // Initialize previous of Node to be deleted Node x = null; // Start from head and find the Node to be // deleted Node temp = head; while (temp != null) { // If we found the key, update xv if (temp.key == key) x = temp; temp = temp.next; } // key occurs at-least once if (x != null) { // Copy key of next Node to x x.key = x.next.key; // Store and unlink next temp = x.next; x.next = x.next.next; // Free memory for next } return head;} /// Utility function to create a new node with//given key /static Node newNode(int key){ Node temp = new Node(); temp.key = key; temp.next = null; return temp;} // This function prints contents of linked list// starting from the given Nodestatic void printList( Node node){ while (node != null) { Console.Write(" {0} ", node.key); node = node.next; }} // Driver codepublic static void Main(String []args){ // Start with the empty list Node head = newNode(1); head.next = newNode(2); head.next.next = newNode(3); head.next.next.next = newNode(5); head.next.next.next.next = newNode(2); head.next.next.next.next.next = newNode(10); Console.Write("Created Linked List: "); printList(head); deleteLast(head, 2); Console.Write("\nLinked List after Deletion of 2: "); printList(head);}} // This code has been contributed by 29AjayKumar <script> // A Javascript program to demonstrate// deletion of last Node in singly// linked listclass Node{ constructor(key) { this.key = key; this.next = null; }} function deleteLast(head, key){ // Initialize previous of Node to be deleted let x = null; // Start from head and find the Node to be // deleted let temp = head; while (temp != null) { // If we found the key, update xv if (temp.key == key) x = temp; temp = temp.next; } // key occurs at-least once if (x != null) { // Copy key of next Node to x x.key = x.next.key; // Store and unlink next temp = x.next; x.next = x.next.next; // Free memory for next } return head;} // This function prints contents of linked// list starting from the given Nodefunction printList(node){ while (node != null) { document.write(node.key + " "); node = node.next; }} // Driver codelet head = new Node(1);head.next = new Node(2);head.next.next = new Node(3);head.next.next.next = new Node(5);head.next.next.next.next = new Node(2);head.next.next.next.next.next = new Node(10); document.write("Created Linked List: <br>");printList(head);deleteLast(head, 2); document.write("<br>Linked List after " + "Deletion of 2: <br>");printList(head); // This code is contributed by rag2127 </script> Created Linked List: 1 2 3 5 2 10 Linked List after Deletion of 2: 1 2 3 5 10 Time Complexity: O(n) Auxiliary Space: O(1) The above solution doesn’t work when the node to be deleted is the last node.Following solution handles all cases. C++ C Java Python3 C# Javascript // A C++ program to demonstrate deletion of last// Node in singly linked list#include <bits/stdc++.h>using namespace std; // A linked list Nodestruct Node { int data; struct Node* next;}; // Function to delete the last occurrencevoid deleteLast(struct Node* head, int x){ struct Node *temp = head, *ptr = NULL; while (temp) { // If found key, update if (temp->data == x) ptr = temp; temp = temp->next; } // If the last occurrence is the last node if (ptr != NULL && ptr->next == NULL) { temp = head; while (temp->next != ptr) temp = temp->next; temp->next = NULL; } // If it is not the last node if (ptr != NULL && ptr->next != NULL) { ptr->data = ptr->next->data; temp = ptr->next; ptr->next = ptr->next->next; free(temp); }} /* Utility function to create a new node withgiven key */struct Node* newNode(int x){ Node* node = new Node ; node->data = x; node->next = NULL; return node;} // This function prints contents of linked list// starting from the given Nodevoid display(struct Node* head){ struct Node* temp = head; if (head == NULL) { cout <<"NULL\n"; return; } while (temp != NULL) { cout <<" --> "<< temp->data; temp = temp->next; } cout <<"NULL\n";} /* Driver program to test above functions*/int main(){ struct Node* head = newNode(1); head->next = newNode(2); head->next->next = newNode(3); head->next->next->next = newNode(4); head->next->next->next->next = newNode(5); head->next->next->next->next->next = newNode(4); head->next->next->next->next->next->next = newNode(4); cout <<"Created Linked list: "; display(head); deleteLast(head, 4); cout <<"Linked List after deletion of 4: "; display(head); return 0;} // This code is contributed by shivanisinghss2110 // A C program to demonstrate deletion of last// Node in singly linked list#include <stdio.h>#include <stdlib.h> // A linked list Nodestruct Node { int data; struct Node* next;}; // Function to delete the last occurrencevoid deleteLast(struct Node* head, int x){ struct Node *temp = head, *ptr = NULL; while (temp) { // If found key, update if (temp->data == x) ptr = temp; temp = temp->next; } // If the last occurrence is the last node if (ptr != NULL && ptr->next == NULL) { temp = head; while (temp->next != ptr) temp = temp->next; temp->next = NULL; } // If it is not the last node if (ptr != NULL && ptr->next != NULL) { ptr->data = ptr->next->data; temp = ptr->next; ptr->next = ptr->next->next; free(temp); }} /* Utility function to create a new node withgiven key */struct Node* newNode(int x){ struct Node* node = malloc(sizeof(struct Node*)); node->data = x; node->next = NULL; return node;} // This function prints contents of linked list// starting from the given Nodevoid display(struct Node* head){ struct Node* temp = head; if (head == NULL) { printf("NULL\n"); return; } while (temp != NULL) { printf("%d --> ", temp->data); temp = temp->next; } printf("NULL\n");} /* Driver program to test above functions*/int main(){ struct Node* head = newNode(1); head->next = newNode(2); head->next->next = newNode(3); head->next->next->next = newNode(4); head->next->next->next->next = newNode(5); head->next->next->next->next->next = newNode(4); head->next->next->next->next->next->next = newNode(4); printf("Created Linked list: "); display(head); deleteLast(head, 4); printf("List after deletion of 4: "); display(head); return 0;} // Java program to demonstrate deletion of last// Node in singly linked listclass GFG{ // A linked list Nodestatic class Node{ int data; Node next;}; // Function to delete the last occurrencestatic void deleteLast(Node head, int x){ Node temp = head, ptr = null; while (temp!=null) { // If found key, update if (temp.data == x) ptr = temp; temp = temp.next; } // If the last occurrence is the last node if (ptr != null && ptr.next == null) { temp = head; while (temp.next != ptr) temp = temp.next; temp.next = null; } // If it is not the last node if (ptr != null && ptr.next != null) { ptr.data = ptr.next.data; temp = ptr.next; ptr.next = ptr.next.next; System.gc(); }} /* Utility function to create a new node withgiven key */static Node newNode(int x){ Node node = new Node(); node.data = x; node.next = null; return node;} // This function prints contents of linked list// starting from the given Nodestatic void display(Node head){ Node temp = head; if (head == null) { System.out.print("null\n"); return; } while (temp != null) { System.out.printf("%d --> ", temp.data); temp = temp.next; } System.out.print("null\n");} /* Driver code*/public static void main(String[] args){ Node head = newNode(1); head.next = newNode(2); head.next.next = newNode(3); head.next.next.next = newNode(4); head.next.next.next.next = newNode(5); head.next.next.next.next.next = newNode(4); head.next.next.next.next.next.next = newNode(4); System.out.print("Created Linked list: "); display(head); deleteLast(head, 4); System.out.print("List after deletion of 4: "); display(head);}} /* This code is contributed by PrinciRaj1992 */ # A Python3 program to demonstrate deletion of last# Node in singly linked list # A linked list Nodeclass Node: def __init__(self, new_data): self.data = new_data self.next = None # Function to delete the last occurrencedef deleteLast(head, x): temp = head ptr = None while (temp!=None): # If found key, update if (temp.data == x) : ptr = temp temp = temp.next # If the last occurrence is the last node if (ptr != None and ptr.next == None): temp = head while (temp.next != ptr) : temp = temp.next temp.next = None # If it is not the last node if (ptr != None and ptr.next != None): ptr.data = ptr.next.data temp = ptr.next ptr.next = ptr.next.next return head # Utility function to create a new node with# given keydef newNode(x): node = Node(0) node.data = x node.next = None return node # This function prints contents of linked list# starting from the given Nodedef display( head): temp = head if (head == None): print("None\n") return while (temp != None): print( temp.data," -> ",end="") temp = temp.next print("None") # Driver code head = newNode(1)head.next = newNode(2)head.next.next = newNode(3)head.next.next.next = newNode(4)head.next.next.next.next = newNode(5)head.next.next.next.next.next = newNode(4)head.next.next.next.next.next.next = newNode(4)print("Created Linked list: ")display(head)head = deleteLast(head, 4)print("List after deletion of 4: ")display(head) # This code is contributed by Arnab Kundu // C# program to demonstrate deletion of last// Node in singly linked listusing System; class GFG{ // A linked list Nodepublic class Node{ public int data; public Node next;}; // Function to delete the last occurrencestatic void deleteLast(Node head, int x){ Node temp = head, ptr = null; while (temp != null) { // If found key, update if (temp.data == x) ptr = temp; temp = temp.next; } // If the last occurrence is the last node if (ptr != null && ptr.next == null) { temp = head; while (temp.next != ptr) temp = temp.next; temp.next = null; } // If it is not the last node if (ptr != null && ptr.next != null) { ptr.data = ptr.next.data; temp = ptr.next; ptr.next = ptr.next.next; }} /* Utility function to create a new node withgiven key */static Node newNode(int x){ Node node = new Node(); node.data = x; node.next = null; return node;} // This function prints contents of linked list// starting from the given Nodestatic void display(Node head){ Node temp = head; if (head == null) { Console.Write("null\n"); return; } while (temp != null) { Console.Write("{0} --> ", temp.data); temp = temp.next; } Console.Write("null\n");} /* Driver code*/public static void Main(String[] args){ Node head = newNode(1); head.next = newNode(2); head.next.next = newNode(3); head.next.next.next = newNode(4); head.next.next.next.next = newNode(5); head.next.next.next.next.next = newNode(4); head.next.next.next.next.next.next = newNode(4); Console.Write("Created Linked list: "); display(head); deleteLast(head, 4); Console.Write("List after deletion of 4: "); display(head);}} // This code contributed by Rajput-Ji <script> // JavaScript program to demonstrate// deletion of last// Node in singly linked list // A linked list Nodeclass Node { constructor() { this.data = 0; this.next = null; }} // Function to delete the last occurrence function deleteLast(head , x) { var temp = head, ptr = null; while (temp != null) { // If found key, update if (temp.data == x) ptr = temp; temp = temp.next; } // If the last occurrence is the last node if (ptr != null && ptr.next == null) { temp = head; while (temp.next != ptr) temp = temp.next; temp.next = null; } // If it is not the last node if (ptr != null && ptr.next != null) { ptr.data = ptr.next.data; temp = ptr.next; ptr.next = ptr.next.next; } } /* Utility function to create a new node with given key */ function newNode(x) { var node = new Node(); node.data = x; node.next = null; return node; } // This function prints contents of linked list // starting from the given Node function display(head) { var temp = head; if (head == null) { document.write("null<br/>"); return; } while (temp != null) { document.write( temp.data + " --> "); temp = temp.next; } document.write("null<br/>"); } /* Driver code */ var head = newNode(1); head.next = newNode(2); head.next.next = newNode(3); head.next.next.next = newNode(4); head.next.next.next.next = newNode(5); head.next.next.next.next.next = newNode(4); head.next.next.next.next.next.next = newNode(4); document.write("Created Linked list: "); display(head); deleteLast(head, 4); document.write("List after deletion of 4: "); display(head); // This code contributed by gauravrajput1 </script> Created Linked list: --> 1 --> 2 --> 3 --> 4 --> 5 --> 4 --> 4NULL Linked List after deletion of 4: --> 1 --> 2 --> 3 --> 4 --> 5 --> 4NULL Time Complexity: O(n) Auxiliary Space: O(1)Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above princiraj1992 Rajput-Ji andrew1234 kalaikarthick 29AjayKumar nidhi_biet rutvik_56 khushboogoyal499 GauravRajput1 shivanisinghss2110 rag2127 avanitrachhadiya2155 patel2127 rhythmsingla1 sumitgumber28 hiteshreddy2181 technophpfij Linked List Linked List Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stack Data Structure (Introduction and Program) LinkedList in Java Introduction to Data Structures What is Data Structure: Types, Classifications and Applications Implementing a Linked List in Java using Class Detect and Remove Loop in a Linked List Add two numbers represented by linked lists | Set 1 Queue - Linked List Implementation Function to check if a singly linked list is palindrome Implement a stack using singly linked list
[ { "code": null, "e": 52, "s": 24, "text": "\n14 Jun, 2022" }, { "code": null, "e": 346, "s": 52, "text": "Using pointers, loop through the whole list and keep track of the node prior to the node containing the last occurrence key using a special pointer. After this just store the next of next of the special pointer, into to next of special pointer to remove the required node from the linked list." }, { "code": null, "e": 350, "s": 346, "text": "C++" }, { "code": null, "e": 352, "s": 350, "text": "C" }, { "code": null, "e": 357, "s": 352, "text": "Java" }, { "code": null, "e": 365, "s": 357, "text": "Python3" }, { "code": null, "e": 376, "s": 365, "text": "Javascript" }, { "code": "#include <iostream>#include <bits/stdc++.h>using namespace std; // A linked list Nodestruct Node{ int data; struct Node* next;}; // Function to delete the last occurrencevoid deleteLast(struct Node** head, int x){ struct Node** tmp1 = NULL; while (*head) { if ((*head)->data == x) { tmp1 = head; } head = &(*head)->next; } if (tmp1) { struct Node* tmp = *tmp1; *tmp1 = tmp->next; free(tmp); }} // Utility function to create a new node with// given keystruct Node* newNode(int x){ Node* node = new Node ; node->data = x; node->next = NULL; return node;} // This function prints contents of linked// list starting from the given Nodevoid display(struct Node* head){ struct Node* temp = head; if (head == NULL) { cout << \"NULL\\n\"; return; } while (temp != NULL) { cout << temp->data <<\" --> \"; temp = temp->next; } cout << \"NULL\\n\";} // Driver codeint main(){ struct Node* head = newNode(1); head->next = newNode(2); head->next->next = newNode(3); head->next->next->next = newNode(4); head->next->next->next->next = newNode(5); head->next->next->next->next->next = newNode(4); head->next->next->next->next->next->next = newNode(4); cout << \"Created Linked list: \"; display(head); // Pass the address of the head pointer deleteLast(&head, 4); cout << \"List after deletion of 4: \"; display(head); return 0;} // This code is contributed by khushboogoyal499", "e": 1962, "s": 376, "text": null }, { "code": "#include <stdio.h>#include <stdlib.h> // A linked list Nodestruct Node { int data; struct Node* next;}; // Function to delete the last occurrencevoid deleteLast(struct Node** head, int x){ struct Node** tmp1 = NULL; while(*head) { if((*head)->data == x) { tmp1 = head; } head = &(*head)->next; } if(tmp1) { struct Node* tmp = *tmp1; *tmp1 = tmp->next; free(tmp); }} /* Utility function to create a new node withgiven key */struct Node* newNode(int x){ struct Node* node = malloc(sizeof(struct Node*)); node->data = x; node->next = NULL; return node;} // This function prints contents of linked list// starting from the given Nodevoid display(struct Node* head){ struct Node* temp = head; if (head == NULL) { printf(\"NULL\\n\"); return; } while (temp != NULL) { printf(\"%d --> \", temp->data); temp = temp->next; } printf(\"NULL\\n\");} /* Driver program to test above functions*/int main(){ struct Node* head = newNode(1); head->next = newNode(2); head->next->next = newNode(3); head->next->next->next = newNode(4); head->next->next->next->next = newNode(5); head->next->next->next->next->next = newNode(4); head->next->next->next->next->next->next = newNode(4); printf(\"Created Linked list: \"); display(head); deleteLast(&head, 4); // Pass the address of the head pointer printf(\"List after deletion of 4: \"); display(head); return 0;}", "e": 3546, "s": 1962, "text": null }, { "code": "import java.io.*; // A linked list Nodeclass Node{ int data; Node next; Node(int data) { this.data = data; this.next = null; }} class GFG{ // Function to delete the last occurrencestatic Node deleteLast(Node head,int x){ Node temp = head; Node ptr = null; while (temp != null) { // If found key, update if (temp.data == x) ptr = temp; temp = temp.next; } // If the last occurrence is the last node if (ptr != null && ptr.next == null) { temp = head; while (temp.next != ptr) { temp = temp.next; } temp.next = null; } // If it is not the last node if (ptr != null && ptr.next != null) { ptr.data = ptr.next.data; temp = ptr.next; ptr.next = ptr.next.next; } return head;} // This function prints contents of linked list// starting from the given Nodestatic void display(Node head){ Node temp = head; if (head == null) { System.out.print(\"NULL\\n\"); return; } while (temp != null) { System.out.print( temp.data+\" --> \"); temp = temp.next; } System.out.print(\"NULL\\n\");} // Driver codepublic static void main(String[] args){ Node head = new Node(1); head.next = new Node(2); head.next.next = new Node(3); head.next.next.next = new Node(4); head.next.next.next.next = new Node(5); head.next.next.next.next.next = new Node(4); head.next.next.next.next.next.next = new Node(4); System.out.print(\"Created Linked list: \"); display(head); // Pass the address of the head pointer head = deleteLast(head, 4); System.out.print(\"List after deletion of 4: \"); display(head);}} // This code is contributed by patel2127", "e": 5370, "s": 3546, "text": null }, { "code": "# A linked list Nodeclass Node: def __init__(self, new_data): self.data = new_data self.next = None # Function to delete the last occurrencedef deleteLast(head, x): temp = head ptr = None while (temp != None): # If found key, update if (temp.data == x): ptr = temp temp = temp.next # If the last occurrence is the last node if (ptr != None and ptr.next == None): temp = head while (temp.next != ptr): temp = temp.next temp.next = None # If it is not the last node if (ptr != None and ptr.next != None): ptr.data = ptr.next.data temp = ptr.next ptr.next = ptr.next.next return head # Utility function to create a new node# with given keydef newNode(x): node = Node(0) node.data = x node.next = None return node # This function prints contents of linked# list starting from the given Nodedef display(head): temp = head if (head == None): print(\"NULL\\n\") return while (temp != None): print( temp.data,\" --> \", end = \"\") temp = temp.next print(\"NULL\") # Driver codehead = newNode(1)head.next = newNode(2)head.next.next = newNode(3)head.next.next.next = newNode(4)head.next.next.next.next = newNode(5)head.next.next.next.next.next = newNode(4)head.next.next.next.next.next.next = newNode(4) print(\"Created Linked list: \", end = '')display(head) # Pass the address of the head pointerhead = deleteLast(head, 4)print(\"List after deletion of 4: \", end = '') display(head) # This code is contributed by rutvik_56", "e": 7046, "s": 5370, "text": null }, { "code": "<script>// A linked list Nodeclass Node{ // Utility function to create a new node // with given key constructor(data) { this.data = data; this.next = null; }} // Function to delete the last occurrencefunction deleteLast(head, x){ let temp = head; let prt = null; while (temp != null) { //If found key, update if (temp.data == x) ptr = temp; temp = temp.next; } // If the last occurrence is the last node if (ptr != null && ptr.next == null) { temp = head; while (temp.next != ptr) { temp = temp.next; } temp.next = null; } // If it is not the last node if (ptr != null && ptr.next != null) { ptr.data = ptr.next.data; temp = ptr.next; ptr.next = ptr.next.next; } return head; } // This function prints contents of linked// list starting from the given Nodefunction display(head){ let temp = head if (head == null) { document.write(\"NULL<br>\"); return; } while (temp != null) { document.write( temp.data,\" --> \", end = \"\"); temp = temp.next; } document.write(\"NULL<br>\")} // Driver codelet head = new Node(1)head.next = new Node(2)head.next.next = new Node(3)head.next.next.next = new Node(4)head.next.next.next.next = new Node(5)head.next.next.next.next.next = new Node(4)head.next.next.next.next.next.next = new Node(4); document.write(\"Created Linked list: \");display(head) // Pass the address of the head pointerhead = deleteLast(head, 4)document.write(\"List after deletion of 4: \")display(head) // This code is contributed by avanitrachhadiya2155</script>", "e": 8778, "s": 7046, "text": null }, { "code": null, "e": 8913, "s": 8778, "text": "Created Linked list: 1 --> 2 --> 3 --> 4 --> 5 --> 4 --> 4 --> NULL\nList after deletion of 4: 1 --> 2 --> 3 --> 4 --> 5 --> 4 --> NULL" }, { "code": null, "e": 8935, "s": 8913, "text": "Time Complexity: O(n)" }, { "code": null, "e": 8957, "s": 8935, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 9075, "s": 8957, "text": "Given a linked list and a key to be deleted. Delete last occurrence of key from linked. The list may have duplicates." }, { "code": null, "e": 9087, "s": 9075, "text": "Examples: " }, { "code": null, "e": 9147, "s": 9087, "text": "Input: 1->2->3->5->2->10, key = 2\nOutput: 1->2->3->5->10" }, { "code": null, "e": 9385, "s": 9147, "text": "The idea is to traverse the linked list from beginning to end. While traversing, keep track of last occurrence key. After traversing the complete list, delete the last occurrence by copying data of next node and deleting the next node. " }, { "code": null, "e": 9389, "s": 9385, "text": "C++" }, { "code": null, "e": 9394, "s": 9389, "text": "Java" }, { "code": null, "e": 9402, "s": 9394, "text": "Python3" }, { "code": null, "e": 9405, "s": 9402, "text": "C#" }, { "code": null, "e": 9416, "s": 9405, "text": "Javascript" }, { "code": "// A C++ program to demonstrate deletion of last// Node in singly linked list#include <bits/stdc++.h> // A linked list Nodestruct Node { int key; struct Node* next;}; void deleteLast(Node* head, int key){ // Initialize previous of Node to be deleted Node* x = NULL; // Start from head and find the Node to be // deleted Node* temp = head; while (temp) { // If we found the key, update xv if (temp->key == key) x = temp; temp = temp->next; } // key occurs at-least once if (x != NULL) { // Copy key of next Node to x x->key = x->next->key; // Store and unlink next temp = x->next; x->next = x->next->next; // Free memory for next delete temp; }} /* Utility function to create a new node with given key */Node* newNode(int key){ Node* temp = new Node; temp->key = key; temp->next = NULL; return temp;} // This function prints contents of linked list// starting from the given Nodevoid printList(struct Node* node){ while (node != NULL) { printf(\" %d \", node->key); node = node->next; }} /* Driver program to test above functions*/int main(){ /* Start with the empty list */ struct Node* head = newNode(1); head->next = newNode(2); head->next->next = newNode(3); head->next->next->next = newNode(5); head->next->next->next->next = newNode(2); head->next->next->next->next->next = newNode(10); puts(\"Created Linked List: \"); printList(head); deleteLast(head, 2); puts(\"\\nLinked List after Deletion of 2: \"); printList(head); return 0;}", "e": 11045, "s": 9416, "text": null }, { "code": "// A Java program to demonstrate deletion of last// Node in singly linked listclass GFG{ // A linked list Nodestatic class Node{ int key; Node next;}; static Node deleteLast(Node head, int key){ // Initialize previous of Node to be deleted Node x = null; // Start from head and find the Node to be // deleted Node temp = head; while (temp != null) { // If we found the key, update xv if (temp.key == key) x = temp; temp = temp.next; } // key occurs at-least once if (x != null) { // Copy key of next Node to x x.key = x.next.key; // Store and unlink next temp = x.next; x.next = x.next.next; // Free memory for next } return head;} /// Utility function to create a new node with//given key /static Node newNode(int key){ Node temp = new Node(); temp.key = key; temp.next = null; return temp;} // This function prints contents of linked list// starting from the given Nodestatic void printList( Node node){ while (node != null) { System.out.printf(\" %d \", node.key); node = node.next; }} // Driver code/public static void main(String args[]){ // /Start with the empty list / Node head = newNode(1); head.next = newNode(2); head.next.next = newNode(3); head.next.next.next = newNode(5); head.next.next.next.next = newNode(2); head.next.next.next.next.next = newNode(10); System.out.printf(\"Created Linked List: \"); printList(head); deleteLast(head, 2); System.out.printf(\"\\nLinked List after Deletion of 2: \"); printList(head);}} // This code is contributed by Arnab Kundu", "e": 12718, "s": 11045, "text": null }, { "code": "# Python3 program to demonstrate deletion of# last Node in singly linked list # A linked list Nodeclass Node: # Constructor to initialize the node object def __init__(self, data): self.data = data self.next = None def deleteLast(head, key) : # Initialize previous of Node to be deleted x = None # Start from head and find the Node to be # deleted temp = head while (temp != None) : # If we found the key, update xv if (temp.key == key) : x = temp temp = temp.next # key occurs at-least once if (x != None) : # Copy key of next Node to x x.key = x.next.key # Store and unlink next temp = x.next x.next = x.next.next # Free memory for next return head # Utility function to create# a new node with given keydef newNode(key) : temp = Node(0) temp.key = key temp.next = None return temp # This function prints contents of linked list# starting from the given Nodedef printList( node) : while (node != None) : print ( node.key, end = \" \") node = node.next # Driver Codeif __name__=='__main__': # Start with the empty list head = newNode(1) head.next = newNode(2) head.next.next = newNode(3) head.next.next.next = newNode(5) head.next.next.next.next = newNode(2) head.next.next.next.next.next = newNode(10) print(\"Created Linked List: \") printList(head) deleteLast(head, 2) print(\"\\nLinked List after Deletion of 2: \") printList(head) # This code is contributed by Arnab Kundu", "e": 14319, "s": 12718, "text": null }, { "code": "// C# program to demonstrate deletion of last// Node in singly linked listusing System; class GFG{ // A linked list Nodepublic class Node{ public int key; public Node next;}; static Node deleteLast(Node head, int key){ // Initialize previous of Node to be deleted Node x = null; // Start from head and find the Node to be // deleted Node temp = head; while (temp != null) { // If we found the key, update xv if (temp.key == key) x = temp; temp = temp.next; } // key occurs at-least once if (x != null) { // Copy key of next Node to x x.key = x.next.key; // Store and unlink next temp = x.next; x.next = x.next.next; // Free memory for next } return head;} /// Utility function to create a new node with//given key /static Node newNode(int key){ Node temp = new Node(); temp.key = key; temp.next = null; return temp;} // This function prints contents of linked list// starting from the given Nodestatic void printList( Node node){ while (node != null) { Console.Write(\" {0} \", node.key); node = node.next; }} // Driver codepublic static void Main(String []args){ // Start with the empty list Node head = newNode(1); head.next = newNode(2); head.next.next = newNode(3); head.next.next.next = newNode(5); head.next.next.next.next = newNode(2); head.next.next.next.next.next = newNode(10); Console.Write(\"Created Linked List: \"); printList(head); deleteLast(head, 2); Console.Write(\"\\nLinked List after Deletion of 2: \"); printList(head);}} // This code has been contributed by 29AjayKumar", "e": 16007, "s": 14319, "text": null }, { "code": "<script> // A Javascript program to demonstrate// deletion of last Node in singly// linked listclass Node{ constructor(key) { this.key = key; this.next = null; }} function deleteLast(head, key){ // Initialize previous of Node to be deleted let x = null; // Start from head and find the Node to be // deleted let temp = head; while (temp != null) { // If we found the key, update xv if (temp.key == key) x = temp; temp = temp.next; } // key occurs at-least once if (x != null) { // Copy key of next Node to x x.key = x.next.key; // Store and unlink next temp = x.next; x.next = x.next.next; // Free memory for next } return head;} // This function prints contents of linked// list starting from the given Nodefunction printList(node){ while (node != null) { document.write(node.key + \" \"); node = node.next; }} // Driver codelet head = new Node(1);head.next = new Node(2);head.next.next = new Node(3);head.next.next.next = new Node(5);head.next.next.next.next = new Node(2);head.next.next.next.next.next = new Node(10); document.write(\"Created Linked List: <br>\");printList(head);deleteLast(head, 2); document.write(\"<br>Linked List after \" + \"Deletion of 2: <br>\");printList(head); // This code is contributed by rag2127 </script>", "e": 17449, "s": 16007, "text": null }, { "code": null, "e": 17542, "s": 17449, "text": "Created Linked List: \n 1 2 3 5 2 10 \nLinked List after Deletion of 2: \n 1 2 3 5 10 " }, { "code": null, "e": 17564, "s": 17542, "text": "Time Complexity: O(n)" }, { "code": null, "e": 17586, "s": 17564, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 17702, "s": 17586, "text": "The above solution doesn’t work when the node to be deleted is the last node.Following solution handles all cases. " }, { "code": null, "e": 17706, "s": 17702, "text": "C++" }, { "code": null, "e": 17708, "s": 17706, "text": "C" }, { "code": null, "e": 17713, "s": 17708, "text": "Java" }, { "code": null, "e": 17721, "s": 17713, "text": "Python3" }, { "code": null, "e": 17724, "s": 17721, "text": "C#" }, { "code": null, "e": 17735, "s": 17724, "text": "Javascript" }, { "code": "// A C++ program to demonstrate deletion of last// Node in singly linked list#include <bits/stdc++.h>using namespace std; // A linked list Nodestruct Node { int data; struct Node* next;}; // Function to delete the last occurrencevoid deleteLast(struct Node* head, int x){ struct Node *temp = head, *ptr = NULL; while (temp) { // If found key, update if (temp->data == x) ptr = temp; temp = temp->next; } // If the last occurrence is the last node if (ptr != NULL && ptr->next == NULL) { temp = head; while (temp->next != ptr) temp = temp->next; temp->next = NULL; } // If it is not the last node if (ptr != NULL && ptr->next != NULL) { ptr->data = ptr->next->data; temp = ptr->next; ptr->next = ptr->next->next; free(temp); }} /* Utility function to create a new node withgiven key */struct Node* newNode(int x){ Node* node = new Node ; node->data = x; node->next = NULL; return node;} // This function prints contents of linked list// starting from the given Nodevoid display(struct Node* head){ struct Node* temp = head; if (head == NULL) { cout <<\"NULL\\n\"; return; } while (temp != NULL) { cout <<\" --> \"<< temp->data; temp = temp->next; } cout <<\"NULL\\n\";} /* Driver program to test above functions*/int main(){ struct Node* head = newNode(1); head->next = newNode(2); head->next->next = newNode(3); head->next->next->next = newNode(4); head->next->next->next->next = newNode(5); head->next->next->next->next->next = newNode(4); head->next->next->next->next->next->next = newNode(4); cout <<\"Created Linked list: \"; display(head); deleteLast(head, 4); cout <<\"Linked List after deletion of 4: \"; display(head); return 0;} // This code is contributed by shivanisinghss2110", "e": 19651, "s": 17735, "text": null }, { "code": "// A C program to demonstrate deletion of last// Node in singly linked list#include <stdio.h>#include <stdlib.h> // A linked list Nodestruct Node { int data; struct Node* next;}; // Function to delete the last occurrencevoid deleteLast(struct Node* head, int x){ struct Node *temp = head, *ptr = NULL; while (temp) { // If found key, update if (temp->data == x) ptr = temp; temp = temp->next; } // If the last occurrence is the last node if (ptr != NULL && ptr->next == NULL) { temp = head; while (temp->next != ptr) temp = temp->next; temp->next = NULL; } // If it is not the last node if (ptr != NULL && ptr->next != NULL) { ptr->data = ptr->next->data; temp = ptr->next; ptr->next = ptr->next->next; free(temp); }} /* Utility function to create a new node withgiven key */struct Node* newNode(int x){ struct Node* node = malloc(sizeof(struct Node*)); node->data = x; node->next = NULL; return node;} // This function prints contents of linked list// starting from the given Nodevoid display(struct Node* head){ struct Node* temp = head; if (head == NULL) { printf(\"NULL\\n\"); return; } while (temp != NULL) { printf(\"%d --> \", temp->data); temp = temp->next; } printf(\"NULL\\n\");} /* Driver program to test above functions*/int main(){ struct Node* head = newNode(1); head->next = newNode(2); head->next->next = newNode(3); head->next->next->next = newNode(4); head->next->next->next->next = newNode(5); head->next->next->next->next->next = newNode(4); head->next->next->next->next->next->next = newNode(4); printf(\"Created Linked list: \"); display(head); deleteLast(head, 4); printf(\"List after deletion of 4: \"); display(head); return 0;}", "e": 21531, "s": 19651, "text": null }, { "code": "// Java program to demonstrate deletion of last// Node in singly linked listclass GFG{ // A linked list Nodestatic class Node{ int data; Node next;}; // Function to delete the last occurrencestatic void deleteLast(Node head, int x){ Node temp = head, ptr = null; while (temp!=null) { // If found key, update if (temp.data == x) ptr = temp; temp = temp.next; } // If the last occurrence is the last node if (ptr != null && ptr.next == null) { temp = head; while (temp.next != ptr) temp = temp.next; temp.next = null; } // If it is not the last node if (ptr != null && ptr.next != null) { ptr.data = ptr.next.data; temp = ptr.next; ptr.next = ptr.next.next; System.gc(); }} /* Utility function to create a new node withgiven key */static Node newNode(int x){ Node node = new Node(); node.data = x; node.next = null; return node;} // This function prints contents of linked list// starting from the given Nodestatic void display(Node head){ Node temp = head; if (head == null) { System.out.print(\"null\\n\"); return; } while (temp != null) { System.out.printf(\"%d --> \", temp.data); temp = temp.next; } System.out.print(\"null\\n\");} /* Driver code*/public static void main(String[] args){ Node head = newNode(1); head.next = newNode(2); head.next.next = newNode(3); head.next.next.next = newNode(4); head.next.next.next.next = newNode(5); head.next.next.next.next.next = newNode(4); head.next.next.next.next.next.next = newNode(4); System.out.print(\"Created Linked list: \"); display(head); deleteLast(head, 4); System.out.print(\"List after deletion of 4: \"); display(head);}} /* This code is contributed by PrinciRaj1992 */", "e": 23390, "s": 21531, "text": null }, { "code": "# A Python3 program to demonstrate deletion of last# Node in singly linked list # A linked list Nodeclass Node: def __init__(self, new_data): self.data = new_data self.next = None # Function to delete the last occurrencedef deleteLast(head, x): temp = head ptr = None while (temp!=None): # If found key, update if (temp.data == x) : ptr = temp temp = temp.next # If the last occurrence is the last node if (ptr != None and ptr.next == None): temp = head while (temp.next != ptr) : temp = temp.next temp.next = None # If it is not the last node if (ptr != None and ptr.next != None): ptr.data = ptr.next.data temp = ptr.next ptr.next = ptr.next.next return head # Utility function to create a new node with# given keydef newNode(x): node = Node(0) node.data = x node.next = None return node # This function prints contents of linked list# starting from the given Nodedef display( head): temp = head if (head == None): print(\"None\\n\") return while (temp != None): print( temp.data,\" -> \",end=\"\") temp = temp.next print(\"None\") # Driver code head = newNode(1)head.next = newNode(2)head.next.next = newNode(3)head.next.next.next = newNode(4)head.next.next.next.next = newNode(5)head.next.next.next.next.next = newNode(4)head.next.next.next.next.next.next = newNode(4)print(\"Created Linked list: \")display(head)head = deleteLast(head, 4)print(\"List after deletion of 4: \")display(head) # This code is contributed by Arnab Kundu", "e": 25035, "s": 23390, "text": null }, { "code": "// C# program to demonstrate deletion of last// Node in singly linked listusing System; class GFG{ // A linked list Nodepublic class Node{ public int data; public Node next;}; // Function to delete the last occurrencestatic void deleteLast(Node head, int x){ Node temp = head, ptr = null; while (temp != null) { // If found key, update if (temp.data == x) ptr = temp; temp = temp.next; } // If the last occurrence is the last node if (ptr != null && ptr.next == null) { temp = head; while (temp.next != ptr) temp = temp.next; temp.next = null; } // If it is not the last node if (ptr != null && ptr.next != null) { ptr.data = ptr.next.data; temp = ptr.next; ptr.next = ptr.next.next; }} /* Utility function to create a new node withgiven key */static Node newNode(int x){ Node node = new Node(); node.data = x; node.next = null; return node;} // This function prints contents of linked list// starting from the given Nodestatic void display(Node head){ Node temp = head; if (head == null) { Console.Write(\"null\\n\"); return; } while (temp != null) { Console.Write(\"{0} --> \", temp.data); temp = temp.next; } Console.Write(\"null\\n\");} /* Driver code*/public static void Main(String[] args){ Node head = newNode(1); head.next = newNode(2); head.next.next = newNode(3); head.next.next.next = newNode(4); head.next.next.next.next = newNode(5); head.next.next.next.next.next = newNode(4); head.next.next.next.next.next.next = newNode(4); Console.Write(\"Created Linked list: \"); display(head); deleteLast(head, 4); Console.Write(\"List after deletion of 4: \"); display(head);}} // This code contributed by Rajput-Ji", "e": 26877, "s": 25035, "text": null }, { "code": "<script> // JavaScript program to demonstrate// deletion of last// Node in singly linked list // A linked list Nodeclass Node { constructor() { this.data = 0; this.next = null; }} // Function to delete the last occurrence function deleteLast(head , x) { var temp = head, ptr = null; while (temp != null) { // If found key, update if (temp.data == x) ptr = temp; temp = temp.next; } // If the last occurrence is the last node if (ptr != null && ptr.next == null) { temp = head; while (temp.next != ptr) temp = temp.next; temp.next = null; } // If it is not the last node if (ptr != null && ptr.next != null) { ptr.data = ptr.next.data; temp = ptr.next; ptr.next = ptr.next.next; } } /* Utility function to create a new node with given key */ function newNode(x) { var node = new Node(); node.data = x; node.next = null; return node; } // This function prints contents of linked list // starting from the given Node function display(head) { var temp = head; if (head == null) { document.write(\"null<br/>\"); return; } while (temp != null) { document.write( temp.data + \" --> \"); temp = temp.next; } document.write(\"null<br/>\"); } /* Driver code */ var head = newNode(1); head.next = newNode(2); head.next.next = newNode(3); head.next.next.next = newNode(4); head.next.next.next.next = newNode(5); head.next.next.next.next.next = newNode(4); head.next.next.next.next.next.next = newNode(4); document.write(\"Created Linked list: \"); display(head); deleteLast(head, 4); document.write(\"List after deletion of 4: \"); display(head); // This code contributed by gauravrajput1 </script>", "e": 28932, "s": 26877, "text": null }, { "code": null, "e": 29074, "s": 28932, "text": "Created Linked list: --> 1 --> 2 --> 3 --> 4 --> 5 --> 4 --> 4NULL\nLinked List after deletion of 4: --> 1 --> 2 --> 3 --> 4 --> 5 --> 4NULL" }, { "code": null, "e": 29096, "s": 29074, "text": "Time Complexity: O(n)" }, { "code": null, "e": 29242, "s": 29096, "text": "Auxiliary Space: O(1)Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 29256, "s": 29242, "text": "princiraj1992" }, { "code": null, "e": 29266, "s": 29256, "text": "Rajput-Ji" }, { "code": null, "e": 29277, "s": 29266, "text": "andrew1234" }, { "code": null, "e": 29291, "s": 29277, "text": "kalaikarthick" }, { "code": null, "e": 29303, "s": 29291, "text": "29AjayKumar" }, { "code": null, "e": 29314, "s": 29303, "text": "nidhi_biet" }, { "code": null, "e": 29324, "s": 29314, "text": "rutvik_56" }, { "code": null, "e": 29341, "s": 29324, "text": "khushboogoyal499" }, { "code": null, "e": 29355, "s": 29341, "text": "GauravRajput1" }, { "code": null, "e": 29374, "s": 29355, "text": "shivanisinghss2110" }, { "code": null, "e": 29382, "s": 29374, "text": "rag2127" }, { "code": null, "e": 29403, "s": 29382, "text": "avanitrachhadiya2155" }, { "code": null, "e": 29413, "s": 29403, "text": "patel2127" }, { "code": null, "e": 29427, "s": 29413, "text": "rhythmsingla1" }, { "code": null, "e": 29441, "s": 29427, "text": "sumitgumber28" }, { "code": null, "e": 29457, "s": 29441, "text": "hiteshreddy2181" }, { "code": null, "e": 29470, "s": 29457, "text": "technophpfij" }, { "code": null, "e": 29482, "s": 29470, "text": "Linked List" }, { "code": null, "e": 29494, "s": 29482, "text": "Linked List" }, { "code": null, "e": 29592, "s": 29494, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29640, "s": 29592, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 29659, "s": 29640, "text": "LinkedList in Java" }, { "code": null, "e": 29691, "s": 29659, "text": "Introduction to Data Structures" }, { "code": null, "e": 29755, "s": 29691, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 29802, "s": 29755, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 29842, "s": 29802, "text": "Detect and Remove Loop in a Linked List" }, { "code": null, "e": 29894, "s": 29842, "text": "Add two numbers represented by linked lists | Set 1" }, { "code": null, "e": 29929, "s": 29894, "text": "Queue - Linked List Implementation" }, { "code": null, "e": 29985, "s": 29929, "text": "Function to check if a singly linked list is palindrome" } ]
Minimum and maximum possible length of the third side of a triangle
07 Jun, 2022 Given two sides of a triangle s1 and s2, the task is to find the minimum and maximum possible length of the third side of the given triangle. Print -1 if it is not possible to make a triangle with the given side lengths. Note that the length of all the sides must be integers.Examples: Input: s1 = 3, s2 = 6 Output: Max = 8 Min = 4Input: s1 = 5, s2 = 8 Output: Max = 12 Min = 4 Approach: Let s1, s2 and s3 be the sides of the given triangle where s1 and s2 are given. As we know that in a triangle, the sum of two sides must always be greater than the third side. So, the following equations must be satisfied: s1 + s2 > s3s1 + s3 > s2s2 + s3 > s1 s1 + s2 > s3 s1 + s3 > s2 s2 + s3 > s1 Solving for s3, we get s3 < s1 + s2, s3 > s2 – s1 and s3 > s1 – s2. It is clear now that the length of the third side must lie in the range (max(s1, s2) – min(s1, s2), s1 + s2) So, the minimum possible value will be max(s1, s2) – min(s1, s2) + 1 and the maximum possible value will be s1 + s2 – 1.Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the approach#include <iostream>using namespace std; // Function to find the minimum and the// maximum possible length of the third// side of the given trianglevoid find_length(int s1, int s2){ // Not a valid triangle if (s1 <= 0 || s2 <= 0) { cout << -1; return; } int max_length = s1 + s2 - 1; int min_length = max(s1, s2) - min(s1, s2) + 1; // Not a valid triangle if (min_length > max_length) { cout << -1; return; } cout << "Max = " << max_length << endl; cout << "Min = " << min_length;} // Driver codeint main(){ int s1 = 8, s2 = 5; find_length(s1, s2); return 0;} // Java implementation of the approachimport java.io.*; class GFG{ // Function to find the minimum and the// maximum possible length of the third// side of the given trianglestatic void find_length(int s1, int s2){ // Not a valid triangle if (s1 <= 0 || s2 <= 0) { System.out.print(-1); return; } int max_length = s1 + s2 - 1; int min_length = Math.max(s1, s2) - Math.min(s1, s2) + 1; // Not a valid triangle if (min_length > max_length) { System.out.print(-1); return; } System.out.println("Max = " + max_length); System.out.print("Min = " + min_length);} // Driver codepublic static void main (String[] args){ int s1 = 8, s2 = 5; find_length(s1, s2);}} // This code is contributed by anuj_67.. # Python3 implementation of the approach # Function to find the minimum and the# maximum possible length of the third# side of the given triangledef find_length(s1, s2) : # Not a valid triangle if (s1 <= 0 or s2 <= 0) : print(-1, end = ""); return; max_length = s1 + s2 - 1; min_length = max(s1, s2) - min(s1, s2) + 1; # Not a valid triangle if (min_length > max_length) : print(-1, end = ""); return; print("Max =", max_length); print("Min =", min_length); # Driver codeif __name__ == "__main__" : s1 = 8; s2 = 5; find_length(s1, s2); # This code is contributed by AnkitRai01 // C# implementation of the approachusing System; class GFG{ // Function to find the minimum and the// maximum possible length of the third// side of the given trianglestatic void find_length(int s1, int s2){ // Not a valid triangle if (s1 <= 0 || s2 <= 0) { Console.Write(-1); return; } int max_length = s1 + s2 - 1; int min_length = Math.Max(s1, s2) - Math.Min(s1, s2) + 1; // Not a valid triangle if (min_length > max_length) { Console.WriteLine(-1); return; } Console.WriteLine("Max = " + max_length); Console.WriteLine("Min = " + min_length);} // Driver codepublic static void Main (){ int s1 = 8, s2 = 5; find_length(s1, s2);}} // This code is contributed by anuj_67.. <script>// javascript implementation of the approach // Function to find the minimum and the // maximum possible length of the third // side of the given triangle function find_length(s1 , s2) { // Not a valid triangle if (s1 <= 0 || s2 <= 0) { document.write(-1); return; } var max_length = s1 + s2 - 1; var min_length = Math.max(s1, s2) - Math.min(s1, s2) + 1; // Not a valid triangle if (min_length > max_length) { document.write(-1); return; } document.write("Max = " + max_length+"<br/>"); document.write("Min = " + min_length); } // Driver code var s1 = 8, s2 = 5; find_length(s1, s2); // This code is contributed by todaysgaurav</script> Max = 12 Min = 4 Time Complexity: O(1) Auxiliary Space: O(1) ankthon vt_m todaysgaurav subham348 Constructive Algorithms Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n07 Jun, 2022" }, { "code": null, "e": 341, "s": 53, "text": "Given two sides of a triangle s1 and s2, the task is to find the minimum and maximum possible length of the third side of the given triangle. Print -1 if it is not possible to make a triangle with the given side lengths. Note that the length of all the sides must be integers.Examples: " }, { "code": null, "e": 435, "s": 341, "text": "Input: s1 = 3, s2 = 6 Output: Max = 8 Min = 4Input: s1 = 5, s2 = 8 Output: Max = 12 Min = 4 " }, { "code": null, "e": 672, "s": 437, "text": "Approach: Let s1, s2 and s3 be the sides of the given triangle where s1 and s2 are given. As we know that in a triangle, the sum of two sides must always be greater than the third side. So, the following equations must be satisfied: " }, { "code": null, "e": 709, "s": 672, "text": "s1 + s2 > s3s1 + s3 > s2s2 + s3 > s1" }, { "code": null, "e": 722, "s": 709, "text": "s1 + s2 > s3" }, { "code": null, "e": 735, "s": 722, "text": "s1 + s3 > s2" }, { "code": null, "e": 748, "s": 735, "text": "s2 + s3 > s1" }, { "code": null, "e": 1098, "s": 748, "text": "Solving for s3, we get s3 < s1 + s2, s3 > s2 – s1 and s3 > s1 – s2. It is clear now that the length of the third side must lie in the range (max(s1, s2) – min(s1, s2), s1 + s2) So, the minimum possible value will be max(s1, s2) – min(s1, s2) + 1 and the maximum possible value will be s1 + s2 – 1.Below is the implementation of the above approach: " }, { "code": null, "e": 1102, "s": 1098, "text": "C++" }, { "code": null, "e": 1107, "s": 1102, "text": "Java" }, { "code": null, "e": 1115, "s": 1107, "text": "Python3" }, { "code": null, "e": 1118, "s": 1115, "text": "C#" }, { "code": null, "e": 1129, "s": 1118, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <iostream>using namespace std; // Function to find the minimum and the// maximum possible length of the third// side of the given trianglevoid find_length(int s1, int s2){ // Not a valid triangle if (s1 <= 0 || s2 <= 0) { cout << -1; return; } int max_length = s1 + s2 - 1; int min_length = max(s1, s2) - min(s1, s2) + 1; // Not a valid triangle if (min_length > max_length) { cout << -1; return; } cout << \"Max = \" << max_length << endl; cout << \"Min = \" << min_length;} // Driver codeint main(){ int s1 = 8, s2 = 5; find_length(s1, s2); return 0;}", "e": 1796, "s": 1129, "text": null }, { "code": "// Java implementation of the approachimport java.io.*; class GFG{ // Function to find the minimum and the// maximum possible length of the third// side of the given trianglestatic void find_length(int s1, int s2){ // Not a valid triangle if (s1 <= 0 || s2 <= 0) { System.out.print(-1); return; } int max_length = s1 + s2 - 1; int min_length = Math.max(s1, s2) - Math.min(s1, s2) + 1; // Not a valid triangle if (min_length > max_length) { System.out.print(-1); return; } System.out.println(\"Max = \" + max_length); System.out.print(\"Min = \" + min_length);} // Driver codepublic static void main (String[] args){ int s1 = 8, s2 = 5; find_length(s1, s2);}} // This code is contributed by anuj_67..", "e": 2565, "s": 1796, "text": null }, { "code": "# Python3 implementation of the approach # Function to find the minimum and the# maximum possible length of the third# side of the given triangledef find_length(s1, s2) : # Not a valid triangle if (s1 <= 0 or s2 <= 0) : print(-1, end = \"\"); return; max_length = s1 + s2 - 1; min_length = max(s1, s2) - min(s1, s2) + 1; # Not a valid triangle if (min_length > max_length) : print(-1, end = \"\"); return; print(\"Max =\", max_length); print(\"Min =\", min_length); # Driver codeif __name__ == \"__main__\" : s1 = 8; s2 = 5; find_length(s1, s2); # This code is contributed by AnkitRai01", "e": 3226, "s": 2565, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{ // Function to find the minimum and the// maximum possible length of the third// side of the given trianglestatic void find_length(int s1, int s2){ // Not a valid triangle if (s1 <= 0 || s2 <= 0) { Console.Write(-1); return; } int max_length = s1 + s2 - 1; int min_length = Math.Max(s1, s2) - Math.Min(s1, s2) + 1; // Not a valid triangle if (min_length > max_length) { Console.WriteLine(-1); return; } Console.WriteLine(\"Max = \" + max_length); Console.WriteLine(\"Min = \" + min_length);} // Driver codepublic static void Main (){ int s1 = 8, s2 = 5; find_length(s1, s2);}} // This code is contributed by anuj_67..", "e": 3974, "s": 3226, "text": null }, { "code": "<script>// javascript implementation of the approach // Function to find the minimum and the // maximum possible length of the third // side of the given triangle function find_length(s1 , s2) { // Not a valid triangle if (s1 <= 0 || s2 <= 0) { document.write(-1); return; } var max_length = s1 + s2 - 1; var min_length = Math.max(s1, s2) - Math.min(s1, s2) + 1; // Not a valid triangle if (min_length > max_length) { document.write(-1); return; } document.write(\"Max = \" + max_length+\"<br/>\"); document.write(\"Min = \" + min_length); } // Driver code var s1 = 8, s2 = 5; find_length(s1, s2); // This code is contributed by todaysgaurav</script>", "e": 4779, "s": 3974, "text": null }, { "code": null, "e": 4796, "s": 4779, "text": "Max = 12\nMin = 4" }, { "code": null, "e": 4820, "s": 4798, "text": "Time Complexity: O(1)" }, { "code": null, "e": 4842, "s": 4820, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 4850, "s": 4842, "text": "ankthon" }, { "code": null, "e": 4855, "s": 4850, "text": "vt_m" }, { "code": null, "e": 4868, "s": 4855, "text": "todaysgaurav" }, { "code": null, "e": 4878, "s": 4868, "text": "subham348" }, { "code": null, "e": 4902, "s": 4878, "text": "Constructive Algorithms" }, { "code": null, "e": 4915, "s": 4902, "text": "Mathematical" }, { "code": null, "e": 4928, "s": 4915, "text": "Mathematical" } ]
What is the difference between <section> and <div> tags in HTML ?
22 Dec, 2021 Both the tags (<div> and <section>) are used in the webpage, <section> tag means that the content inside relates to a single theme, and <div> tag is used as a block part of the webpage and don’t convey any particular meaning. HTML <div> Tag: It is called a division tag. The <div> tag is a block-level element that only represents its child elements and doesn’t have a special meaning. It takes the Whole Width available on the screen. It is generally used with the title and class attributes. The <div> tag is one of the most used tags in website creation. Use <div> element for style purposes or for wrapping paragraphs within a section that are all to be given similar properties. Requires closing </div> tag too. Note: It is recommended to use the <div> element as a last option and use other various tags such as <main>, <article> or <nav> as this practice is more convenient for the readers. Syntax: <div> <h1>Title</h1> <p>Information goes here....</p> </div> Example: This example shows <div> tag. HTML <!DOCTYPE html><html> <head> <title>Div example</title> </head> <body> <h1 style="color:green">GeeksForGeeks</h1> <div style="background-color:#189"> <h2>This is heading inside Div tag</h2> <p>This is paragraph inside Div tag.</p> </div> <p style="color:red">This is outside div tag</p> </body></html> Output: Html <section> Tag: The <section> tag is not a generic container in a web-page. The content inside <section> tag will be grouped i.e. it’ll connect to a single subject and appear as an entry in an outline of the page. A common rule is that the <section> element is valid only if tha element’s contents would be listed explicitly in the document’s outline. Section tag is used to distribute the content with a similar theme. The main advantage of the section tag is, it describes its meaning in a web page. It is mostly used when headers, footers, or any other section of documents are needed in a web page. Requires closing </section> tag too. Syntax: <section> <h1>Title</h1> <p>Information goes here....</p> </section> Example: This example shows <section> tag HTML <!DOCTYPE html><html> <head> <title>Title of the document</title> </head> <body> <h1 style="color:green">GeeksForGeeks</h1> <section> <h2>GeeksForGeeks </h2> <ul> <li>Machine learing</li> <li>DSA</li> <li>Competitive programming</li> <li>Web-Development</li> <li>Java</li> </ul> </section> <section> <h3>Books</h3> <p>Learn Machine learing</p> <p>Learn DSA</p> <p>Learn Competitive programming</p> <p>Learn Web-Development</p> <p>Learn Java</p> </section> </body></html> Output: Differences between <div> and <section> tag: use <section> during requirements of headers or footers or any other section of documents. sagar0719kumar adnanirshad158 HTML-Questions HTML-Tags 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 ? REST API (Introduction) CSS to put icon inside an input element in a form Types of CSS (Cascading Style Sheet) HTTP headers | Content-Type Installation of Node.js on Linux Difference between var, let and const keywords in JavaScript How to fetch data from an API in ReactJS ? Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Dec, 2021" }, { "code": null, "e": 254, "s": 28, "text": "Both the tags (<div> and <section>) are used in the webpage, <section> tag means that the content inside relates to a single theme, and <div> tag is used as a block part of the webpage and don’t convey any particular meaning." }, { "code": null, "e": 745, "s": 254, "text": "HTML <div> Tag: It is called a division tag. The <div> tag is a block-level element that only represents its child elements and doesn’t have a special meaning. It takes the Whole Width available on the screen. It is generally used with the title and class attributes. The <div> tag is one of the most used tags in website creation. Use <div> element for style purposes or for wrapping paragraphs within a section that are all to be given similar properties. Requires closing </div> tag too." }, { "code": null, "e": 926, "s": 745, "text": "Note: It is recommended to use the <div> element as a last option and use other various tags such as <main>, <article> or <nav> as this practice is more convenient for the readers." }, { "code": null, "e": 934, "s": 926, "text": "Syntax:" }, { "code": null, "e": 999, "s": 934, "text": "<div>\n <h1>Title</h1>\n <p>Information goes here....</p>\n</div>" }, { "code": null, "e": 1038, "s": 999, "text": "Example: This example shows <div> tag." }, { "code": null, "e": 1043, "s": 1038, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>Div example</title> </head> <body> <h1 style=\"color:green\">GeeksForGeeks</h1> <div style=\"background-color:#189\"> <h2>This is heading inside Div tag</h2> <p>This is paragraph inside Div tag.</p> </div> <p style=\"color:red\">This is outside div tag</p> </body></html>", "e": 1381, "s": 1043, "text": null }, { "code": null, "e": 1389, "s": 1381, "text": "Output:" }, { "code": null, "e": 2033, "s": 1389, "text": "Html <section> Tag: The <section> tag is not a generic container in a web-page. The content inside <section> tag will be grouped i.e. it’ll connect to a single subject and appear as an entry in an outline of the page. A common rule is that the <section> element is valid only if tha element’s contents would be listed explicitly in the document’s outline. Section tag is used to distribute the content with a similar theme. The main advantage of the section tag is, it describes its meaning in a web page. It is mostly used when headers, footers, or any other section of documents are needed in a web page. Requires closing </section> tag too." }, { "code": null, "e": 2044, "s": 2033, "text": "Syntax: " }, { "code": null, "e": 2117, "s": 2044, "text": "<section>\n <h1>Title</h1>\n <p>Information goes here....</p>\n</section>" }, { "code": null, "e": 2159, "s": 2117, "text": "Example: This example shows <section> tag" }, { "code": null, "e": 2164, "s": 2159, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>Title of the document</title> </head> <body> <h1 style=\"color:green\">GeeksForGeeks</h1> <section> <h2>GeeksForGeeks </h2> <ul> <li>Machine learing</li> <li>DSA</li> <li>Competitive programming</li> <li>Web-Development</li> <li>Java</li> </ul> </section> <section> <h3>Books</h3> <p>Learn Machine learing</p> <p>Learn DSA</p> <p>Learn Competitive programming</p> <p>Learn Web-Development</p> <p>Learn Java</p> </section> </body></html>", "e": 2757, "s": 2164, "text": null }, { "code": null, "e": 2765, "s": 2757, "text": "Output:" }, { "code": null, "e": 2811, "s": 2765, "text": "Differences between <div> and <section> tag:" }, { "code": null, "e": 2876, "s": 2811, "text": " use <section> during requirements of headers or footers or any " }, { "code": null, "e": 2904, "s": 2876, "text": "other section of documents." }, { "code": null, "e": 2919, "s": 2904, "text": "sagar0719kumar" }, { "code": null, "e": 2934, "s": 2919, "text": "adnanirshad158" }, { "code": null, "e": 2949, "s": 2934, "text": "HTML-Questions" }, { "code": null, "e": 2959, "s": 2949, "text": "HTML-Tags" }, { "code": null, "e": 2966, "s": 2959, "text": "Picked" }, { "code": null, "e": 2971, "s": 2966, "text": "HTML" }, { "code": null, "e": 2988, "s": 2971, "text": "Web Technologies" }, { "code": null, "e": 2993, "s": 2988, "text": "HTML" }, { "code": null, "e": 3091, "s": 2993, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3139, "s": 3091, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 3163, "s": 3139, "text": "REST API (Introduction)" }, { "code": null, "e": 3213, "s": 3163, "text": "CSS to put icon inside an input element in a form" }, { "code": null, "e": 3250, "s": 3213, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 3278, "s": 3250, "text": "HTTP headers | Content-Type" }, { "code": null, "e": 3311, "s": 3278, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 3372, "s": 3311, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3415, "s": 3372, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 3487, "s": 3415, "text": "Differences between Functional Components and Class Components in React" } ]
TypeScript | toLocaleString() Function
11 Jun, 2020 The toLocaleString() method in TypeScript is to convert the number into a local specific representation of the number using the locale of the environment. Syntax: number.toLocaleString() Return Value: The toLocaleString() method in TypeScript returns a human readable string representing the number using the locale of the environment. Below examples illustrate the working of toLocaleString() function in TypeScript: Example 1: <script> // toLocaleString() methodvar num = new Number(432.3456);console.log(num.toLocaleString());</script> Output: 432.3456 Example 2: <script> // toLocaleString() methodlet Number_1 : number = 23415.456;console.log("Number Method: toLocaleString()"); // returns in US Englishconsole.log(Number_1.toLocaleString()); </script> Output: Number Method: toLocaleString() 23, 415.456 TypeScript 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": "\n11 Jun, 2020" }, { "code": null, "e": 183, "s": 28, "text": "The toLocaleString() method in TypeScript is to convert the number into a local specific representation of the number using the locale of the environment." }, { "code": null, "e": 191, "s": 183, "text": "Syntax:" }, { "code": null, "e": 215, "s": 191, "text": "number.toLocaleString()" }, { "code": null, "e": 364, "s": 215, "text": "Return Value: The toLocaleString() method in TypeScript returns a human readable string representing the number using the locale of the environment." }, { "code": null, "e": 446, "s": 364, "text": "Below examples illustrate the working of toLocaleString() function in TypeScript:" }, { "code": null, "e": 457, "s": 446, "text": "Example 1:" }, { "code": "<script> // toLocaleString() methodvar num = new Number(432.3456);console.log(num.toLocaleString());</script>", "e": 568, "s": 457, "text": null }, { "code": null, "e": 576, "s": 568, "text": "Output:" }, { "code": null, "e": 586, "s": 576, "text": "432.3456\n" }, { "code": null, "e": 597, "s": 586, "text": "Example 2:" }, { "code": "<script> // toLocaleString() methodlet Number_1 : number = 23415.456;console.log(\"Number Method: toLocaleString()\"); // returns in US Englishconsole.log(Number_1.toLocaleString()); </script>", "e": 790, "s": 597, "text": null }, { "code": null, "e": 798, "s": 790, "text": "Output:" }, { "code": null, "e": 843, "s": 798, "text": "Number Method: toLocaleString()\n23, 415.456\n" }, { "code": null, "e": 854, "s": 843, "text": "TypeScript" }, { "code": null, "e": 865, "s": 854, "text": "JavaScript" }, { "code": null, "e": 882, "s": 865, "text": "Web Technologies" } ]
How to display percentage above a bar chart in Matplotlib?
To display percentage above a bar chart in Matplotlib, we can take the following steps − Set the figure size and adjust the padding between and around the subplots. Create x and y data points; initialize a variable, width. Create a figure and a set of subplots using subplots() method. Add bars with x and y data points. Iterate bars patches; put text over the bars using text() method. To display the figure, use show() method. from matplotlib import pyplot as plt import numpy as np plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True x = [1, 2, 3, 4, 5] y = [3, 4, 2, 1, 3] width = 0.35 fig, ax = plt.subplots() pps = ax.bar(x, y, width, align='center') for p in pps: height = p.get_height() ax.text(x=p.get_x() + p.get_width() / 2, y=height+.10, s="{}%".format(height), ha='center') plt.show()
[ { "code": null, "e": 1276, "s": 1187, "text": "To display percentage above a bar chart in Matplotlib, we can take the following steps −" }, { "code": null, "e": 1352, "s": 1276, "text": "Set the figure size and adjust the padding between and around the subplots." }, { "code": null, "e": 1410, "s": 1352, "text": "Create x and y data points; initialize a variable, width." }, { "code": null, "e": 1473, "s": 1410, "text": "Create a figure and a set of subplots using subplots() method." }, { "code": null, "e": 1508, "s": 1473, "text": "Add bars with x and y data points." }, { "code": null, "e": 1574, "s": 1508, "text": "Iterate bars patches; put text over the bars using text() method." }, { "code": null, "e": 1616, "s": 1574, "text": "To display the figure, use show() method." }, { "code": null, "e": 2044, "s": 1616, "text": "from matplotlib import pyplot as plt\nimport numpy as np\n\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\nx = [1, 2, 3, 4, 5]\ny = [3, 4, 2, 1, 3]\n\nwidth = 0.35\nfig, ax = plt.subplots()\n\npps = ax.bar(x, y, width, align='center')\n\nfor p in pps:\n height = p.get_height()\n ax.text(x=p.get_x() + p.get_width() / 2, y=height+.10,\n s=\"{}%\".format(height),\n ha='center')\n\nplt.show()" } ]
Get n-largest values from a particular column in Pandas DataFrame
18 Dec, 2018 Pandas DataFrame is two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). Let’s see how can we can get n-largest values from a particular column in Pandas DataFrame. Observe this dataset first. We’ll use ‘Age’, ‘Weight’ and ‘Salary’ columns of this data in order to get n-largest values from a particular column in Pandas DataFrame. # importing pandas module import pandas as pd # making data frame df = pd.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/nba.csv") df.head(10) Code #1: Getting 5 largest Age # importing pandas module import pandas as pd # making data frame df = pd.read_csv("nba.csv") # five largest values in column agedf.nlargest(5, ['Age']) Output: Code #2: Getting 10 maximum weights # importing pandas module import pandas as pd # making data frame df = pd.read_csv("nba.csv") # Ten largest values in column Weightdf.nlargest(10, ['Weight']) Output: Code #3: Getting 10 maximum salary # importing pandas module import pandas as pd # making data frame df = pd.read_csv("nba.csv") # five largest values in column Salarydf.nlargest(5, ['Salary']) Output: pandas-dataframe-program Python pandas-dataFrame Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe 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 Convert integer to string in Python Introduction To PYTHON
[ { "code": null, "e": 28, "s": 0, "text": "\n18 Dec, 2018" }, { "code": null, "e": 165, "s": 28, "text": "Pandas DataFrame is two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns)." }, { "code": null, "e": 257, "s": 165, "text": "Let’s see how can we can get n-largest values from a particular column in Pandas DataFrame." }, { "code": null, "e": 424, "s": 257, "text": "Observe this dataset first. We’ll use ‘Age’, ‘Weight’ and ‘Salary’ columns of this data in order to get n-largest values from a particular column in Pandas DataFrame." }, { "code": "# importing pandas module import pandas as pd # making data frame df = pd.read_csv(\"https://media.geeksforgeeks.org/wp-content/uploads/nba.csv\") df.head(10)", "e": 587, "s": 424, "text": null }, { "code": null, "e": 618, "s": 587, "text": "Code #1: Getting 5 largest Age" }, { "code": "# importing pandas module import pandas as pd # making data frame df = pd.read_csv(\"nba.csv\") # five largest values in column agedf.nlargest(5, ['Age'])", "e": 777, "s": 618, "text": null }, { "code": null, "e": 786, "s": 777, "text": "Output: " }, { "code": null, "e": 822, "s": 786, "text": "Code #2: Getting 10 maximum weights" }, { "code": "# importing pandas module import pandas as pd # making data frame df = pd.read_csv(\"nba.csv\") # Ten largest values in column Weightdf.nlargest(10, ['Weight'])", "e": 987, "s": 822, "text": null }, { "code": null, "e": 996, "s": 987, "text": "Output: " }, { "code": null, "e": 1031, "s": 996, "text": "Code #3: Getting 10 maximum salary" }, { "code": "# importing pandas module import pandas as pd # making data frame df = pd.read_csv(\"nba.csv\") # five largest values in column Salarydf.nlargest(5, ['Salary'])", "e": 1196, "s": 1031, "text": null }, { "code": null, "e": 1204, "s": 1196, "text": "Output:" }, { "code": null, "e": 1229, "s": 1204, "text": "pandas-dataframe-program" }, { "code": null, "e": 1253, "s": 1229, "text": "Python pandas-dataFrame" }, { "code": null, "e": 1267, "s": 1253, "text": "Python-pandas" }, { "code": null, "e": 1274, "s": 1267, "text": "Python" }, { "code": null, "e": 1372, "s": 1274, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1390, "s": 1372, "text": "Python Dictionary" }, { "code": null, "e": 1432, "s": 1390, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1467, "s": 1432, "text": "Read a file line by line in Python" }, { "code": null, "e": 1493, "s": 1467, "text": "Python String | replace()" }, { "code": null, "e": 1525, "s": 1493, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1554, "s": 1525, "text": "*args and **kwargs in Python" }, { "code": null, "e": 1581, "s": 1554, "text": "Python Classes and Objects" }, { "code": null, "e": 1602, "s": 1581, "text": "Python OOPs Concepts" }, { "code": null, "e": 1638, "s": 1602, "text": "Convert integer to string in Python" } ]
How to add a prefix to column names in R DataFrame ?
28 Apr, 2021 In this article, we will discuss how to add prefixes to column names in DataFrame in R Programming Language. Dataset in use: In order to modify the column names, the paste function in R can be used. The paste() method, can be used for the concatenation of string vectors together to form a larger string or sentence. The string vector arguments are joined using the separator specified in the paste function. The changes have to be saved to the original string and are not retained on their own. The strings are concatenated in the order of specification in the method. The method is applied successively to each string in case we specify it over an R list object. Syntax: paste( prefix1, prefix2.., colnames(df), sep=) Parameter : colnames(df) – Column names of data frame prefix1.. – prefix string to be added to each column name sep – separator to use between the strings Example: R # declaring a data framedf <- data.frame(First = c(1,2,3,4), Second = c("a","ab","cv","dsd"), Third=c(7:10)) # print original data frameprint ("Original DataFrame : ")print (df) # printing original colnames of# data frameoriginal_cols <- colnames(df)print ("Original column names ")print (original_cols) # adding prefix using the paste# function in Rcolnames(df) <- paste("Column" ,original_cols,sep="-") # print changed data frameprint ("Modified DataFrame : ")print (df) Output [1] "Original DataFrame : " First Second Third 1 1 a 7 2 2 ab 8 3 3 cv 9 4 4 dsd 10 [1] "Original column names " [1] "First" "Second" "Third" [1] "Modified DataFrame : " Column-First Column-Second Column-Third 1 1 a 7 2 2 ab 8 3 3 cv 9 4 4 dsd 10 Multiple prefixes can also be prefixed before each column name, by specifying the strings before the column name in this method. Example: R # declaring a data framedf <- data.frame(First = c(1,2,3,4), Second = c("a","ab","cv","dsd"), Third=c(7:10)) # print original data frameprint ("Original DataFrame : ")print (df) # printing original colnames # of data frameoriginal_cols <- colnames(df)print ("Original column names ")print (original_cols) # adding prefix using the paste# function in Rcolnames(df) <- paste("Col" ,"No",original_cols,sep="_") # print changed data frameprint ("Modified DataFrame : ")print (df) Output [1] "Original DataFrame : " First Second Third 1 1 a 7 2 2 ab 8 3 3 cv 9 4 4 dsd 10 [1] "Original column names " [1] "First" "Second" "Third" [1] "Modified DataFrame : " Col_No_First Col_No_Second Col_No_Third 1 1 a 7 2 2 ab 8 3 3 cv 9 4 4 dsd 10 paste0 method is exactly alike like the paste method in functionality, but it does not provide a feature of customized separator between the string arguments. It automatically collapses the string arguments and concatenates them to produce a larger string without any spaces. Multiple prefixes can also be added using this approach. The method is applied successively to each string in case we specify it over an R list object. Syntax: paste0( prefix1, prefix2, colnames(df)) Parameter : colnames(df) – Column names of data frame prefix1.. – prefix string to be added to each column name. The strings are concatenated using sep=””. Example: R # declaring a data framedf <- data.frame(First = c(1,2,3,4), Second = c("a","ab","cv","dsd"), Third=c(7:10)) # print original data frameprint ("Original DataFrame : ")print (df) # printing original colnames # of data frameoriginal_cols <- colnames(df)print ("Original column names ")print (original_cols) # adding prefix using the paste0 # function in Rcolnames(df) <- paste0("Col" ,original_cols) # print changed data frameprint ("Modified DataFrame : ")print (df) Output [1] "Original DataFrame : " First Second Third 1 1 a 7 2 2 ab 8 3 3 cv 9 4 4 dsd 10 [1] "Original column names " [1] "First" "Second" "Third" [1] "Modified DataFrame : " ColFirst ColSecond ColThird 1 1 a 7 2 2 ab 8 3 3 cv 9 4 4 dsd 10 Picked R DataFrame-Programs R-DataFrame R Language R Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. 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? How to Split Column Into Multiple Columns in R DataFrame? How to filter R DataFrame by values in a column? Replace Specific Characters in String in R Merge DataFrames by Column Names in R How to Sort a DataFrame in R ?
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Apr, 2021" }, { "code": null, "e": 137, "s": 28, "text": "In this article, we will discuss how to add prefixes to column names in DataFrame in R Programming Language." }, { "code": null, "e": 153, "s": 137, "text": "Dataset in use:" }, { "code": null, "e": 694, "s": 153, "text": "In order to modify the column names, the paste function in R can be used. The paste() method, can be used for the concatenation of string vectors together to form a larger string or sentence. The string vector arguments are joined using the separator specified in the paste function. The changes have to be saved to the original string and are not retained on their own. The strings are concatenated in the order of specification in the method. The method is applied successively to each string in case we specify it over an R list object. " }, { "code": null, "e": 749, "s": 694, "text": "Syntax: paste( prefix1, prefix2.., colnames(df), sep=)" }, { "code": null, "e": 761, "s": 749, "text": "Parameter :" }, { "code": null, "e": 803, "s": 761, "text": "colnames(df) – Column names of data frame" }, { "code": null, "e": 861, "s": 803, "text": "prefix1.. – prefix string to be added to each column name" }, { "code": null, "e": 904, "s": 861, "text": "sep – separator to use between the strings" }, { "code": null, "e": 913, "s": 904, "text": "Example:" }, { "code": null, "e": 915, "s": 913, "text": "R" }, { "code": "# declaring a data framedf <- data.frame(First = c(1,2,3,4), Second = c(\"a\",\"ab\",\"cv\",\"dsd\"), Third=c(7:10)) # print original data frameprint (\"Original DataFrame : \")print (df) # printing original colnames of# data frameoriginal_cols <- colnames(df)print (\"Original column names \")print (original_cols) # adding prefix using the paste# function in Rcolnames(df) <- paste(\"Column\" ,original_cols,sep=\"-\") # print changed data frameprint (\"Modified DataFrame : \")print (df)", "e": 1424, "s": 915, "text": null }, { "code": null, "e": 1431, "s": 1424, "text": "Output" }, { "code": null, "e": 1859, "s": 1431, "text": "[1] \"Original DataFrame : \"\n First Second Third\n1 1 a 7\n2 2 ab 8\n3 3 cv 9\n4 4 dsd 10\n[1] \"Original column names \"\n[1] \"First\" \"Second\" \"Third\"\n[1] \"Modified DataFrame : \"\n Column-First Column-Second Column-Third\n1 1 a 7\n2 2 ab 8\n3 3 cv 9\n4 4 dsd 10" }, { "code": null, "e": 1989, "s": 1859, "text": "Multiple prefixes can also be prefixed before each column name, by specifying the strings before the column name in this method. " }, { "code": null, "e": 1998, "s": 1989, "text": "Example:" }, { "code": null, "e": 2000, "s": 1998, "text": "R" }, { "code": "# declaring a data framedf <- data.frame(First = c(1,2,3,4), Second = c(\"a\",\"ab\",\"cv\",\"dsd\"), Third=c(7:10)) # print original data frameprint (\"Original DataFrame : \")print (df) # printing original colnames # of data frameoriginal_cols <- colnames(df)print (\"Original column names \")print (original_cols) # adding prefix using the paste# function in Rcolnames(df) <- paste(\"Col\" ,\"No\",original_cols,sep=\"_\") # print changed data frameprint (\"Modified DataFrame : \")print (df)", "e": 2512, "s": 2000, "text": null }, { "code": null, "e": 2519, "s": 2512, "text": "Output" }, { "code": null, "e": 2947, "s": 2519, "text": "[1] \"Original DataFrame : \"\n First Second Third\n1 1 a 7\n2 2 ab 8\n3 3 cv 9\n4 4 dsd 10\n[1] \"Original column names \"\n[1] \"First\" \"Second\" \"Third\"\n[1] \"Modified DataFrame : \"\n Col_No_First Col_No_Second Col_No_Third\n1 1 a 7\n2 2 ab 8\n3 3 cv 9\n4 4 dsd 10" }, { "code": null, "e": 3376, "s": 2947, "text": "paste0 method is exactly alike like the paste method in functionality, but it does not provide a feature of customized separator between the string arguments. It automatically collapses the string arguments and concatenates them to produce a larger string without any spaces. Multiple prefixes can also be added using this approach. The method is applied successively to each string in case we specify it over an R list object. " }, { "code": null, "e": 3424, "s": 3376, "text": "Syntax: paste0( prefix1, prefix2, colnames(df))" }, { "code": null, "e": 3436, "s": 3424, "text": "Parameter :" }, { "code": null, "e": 3478, "s": 3436, "text": "colnames(df) – Column names of data frame" }, { "code": null, "e": 3580, "s": 3478, "text": "prefix1.. – prefix string to be added to each column name. The strings are concatenated using sep=””." }, { "code": null, "e": 3589, "s": 3580, "text": "Example:" }, { "code": null, "e": 3591, "s": 3589, "text": "R" }, { "code": "# declaring a data framedf <- data.frame(First = c(1,2,3,4), Second = c(\"a\",\"ab\",\"cv\",\"dsd\"), Third=c(7:10)) # print original data frameprint (\"Original DataFrame : \")print (df) # printing original colnames # of data frameoriginal_cols <- colnames(df)print (\"Original column names \")print (original_cols) # adding prefix using the paste0 # function in Rcolnames(df) <- paste0(\"Col\" ,original_cols) # print changed data frameprint (\"Modified DataFrame : \")print (df)", "e": 4093, "s": 3591, "text": null }, { "code": null, "e": 4100, "s": 4093, "text": "Output" }, { "code": null, "e": 4468, "s": 4100, "text": "[1] \"Original DataFrame : \"\n First Second Third\n1 1 a 7\n2 2 ab 8\n3 3 cv 9\n4 4 dsd 10\n[1] \"Original column names \"\n[1] \"First\" \"Second\" \"Third\"\n[1] \"Modified DataFrame : \"\n ColFirst ColSecond ColThird\n1 1 a 7\n2 2 ab 8\n3 3 cv 9\n4 4 dsd 10" }, { "code": null, "e": 4475, "s": 4468, "text": "Picked" }, { "code": null, "e": 4496, "s": 4475, "text": "R DataFrame-Programs" }, { "code": null, "e": 4508, "s": 4496, "text": "R-DataFrame" }, { "code": null, "e": 4519, "s": 4508, "text": "R Language" }, { "code": null, "e": 4530, "s": 4519, "text": "R Programs" }, { "code": null, "e": 4628, "s": 4530, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4680, "s": 4628, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 4738, "s": 4680, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 4773, "s": 4738, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 4811, "s": 4773, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 4860, "s": 4811, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 4918, "s": 4860, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 4967, "s": 4918, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 5010, "s": 4967, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 5048, "s": 5010, "text": "Merge DataFrames by Column Names in R" } ]
Numpy | Sorting, Searching and Counting - GeeksforGeeks
15 Nov, 2018 Sorting refers to arranging data in a particular format. Sorting algorithm specifies the way to arrange data in a particular order. Most common orders are in numerical or lexicographical order. In Numpy, we can perform various sorting operations using the various functions that are provided in the library like sort, lexsort, argsort etc. numpy.sort() : This function returns a sorted copy of an array. Output : Along first axis : [[10 1] [12 15]] Along first axis : [[10 15] [ 1 12]] Along none axis : [ 1 10 12 15] numpy.argsort() : This function returns the indices that would sort an array. Output: Original array: [9 3 1 7 4 3 6] Sorted indices of original array-> [2 1 5 4 6 3 0] Sorted array-> [1 3 3 4 6 7 9] numpy.lexsort() : This function returns an indirect stable sort using a sequence of keys. Output : column a, column b 9 4 3 6 1 9 3 2 4 1 3 8 6 7 Sorted indices-> [2 3 1 5 4 6 0] Searching is an operation or a technique that helps finds the place of a given element or value in the list. Any search is said to be successful or unsuccessful depending upon whether the element that is being searched is found or not. In Numpy, we can perform various searching operations using the various functions that are provided in the library like argmax, argmin, nanaargmax etc. numpy.argmax() : This function returns indices of the max element of the array in a particular axis. Output : INPUT ARRAY : [[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11]] Max element : 11 Indices of Max element : [2 2 2 2] Indices of Max element : [3 3 3] numpy.nanargmax() : This function returns indices of the max element of the array in a particular axis ignoring NaNs.The results cannot be trusted if a slice contains only NaNs and Infs. Output : INPUT ARRAY 1 : [nan, 4, 2, 3, 1] Indices of max in array1 : 1 INPUT ARRAY 2 : [[ nan 4.] [ 1. 3.]] Indices of max in array2 : 1 Indices at axis 1 of array2 : [1 1] numpy.argmin() : This function returns the indices of the minimum values along an axis. Output : INPUT ARRAY : [0 1 2 3 4 5 6 7] Indices of min element : 0 numpy.count_nonzero() : Counts the number of non-zero values in the array . Output : Number of nonzero values is : 5 Number of nonzero values is : [1, 1, 1, 1, 1] Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ... Learn C++ Programming Step by Step - A 20 Day Curriculum! Must Do Coding Questions for Product Based Companies CSS Interview Questions and Answers 50 Common Ports You Should Know GeeksforGeeks Jobathon - Are You Ready For This Hiring Challenge? How to Find Length of String in Bash Script? Samsung R&D Internship Interview Experience (On-Campus) Tiger Analytics Interview Experience for Data Analyst (On-Campus) Amazon Interview Experience for SDE-1
[ { "code": null, "e": 43445, "s": 43417, "text": "\n15 Nov, 2018" }, { "code": null, "e": 43785, "s": 43445, "text": "Sorting refers to arranging data in a particular format. Sorting algorithm specifies the way to arrange data in a particular order. Most common orders are in numerical or lexicographical order. In Numpy, we can perform various sorting operations using the various functions that are provided in the library like sort, lexsort, argsort etc." }, { "code": null, "e": 43849, "s": 43785, "text": "numpy.sort() : This function returns a sorted copy of an array." }, { "code": null, "e": 43858, "s": 43849, "text": "Output :" }, { "code": null, "e": 43974, "s": 43858, "text": "Along first axis : \n [[10 1]\n [12 15]]\n\nAlong first axis : \n [[10 15]\n [ 1 12]]\n\nAlong none axis : \n [ 1 10 12 15]" }, { "code": null, "e": 44053, "s": 43974, "text": " numpy.argsort() : This function returns the indices that would sort an array." }, { "code": null, "e": 44061, "s": 44053, "text": "Output:" }, { "code": null, "e": 44177, "s": 44061, "text": "Original array:\n [9 3 1 7 4 3 6]\nSorted indices of original array-> [2 1 5 4 6 3 0]\nSorted array-> [1 3 3 4 6 7 9]\n" }, { "code": null, "e": 44268, "s": 44177, "text": " numpy.lexsort() : This function returns an indirect stable sort using a sequence of keys." }, { "code": null, "e": 44277, "s": 44268, "text": "Output :" }, { "code": null, "e": 44372, "s": 44277, "text": "column a, column b\n9 4\n3 6\n1 9\n3 2\n4 1\n3 8\n6 7\nSorted indices-> [2 3 1 5 4 6 0]\n" }, { "code": null, "e": 44762, "s": 44374, "text": "Searching is an operation or a technique that helps finds the place of a given element or value in the list. Any search is said to be successful or unsuccessful depending upon whether the element that is being searched is found or not. In Numpy, we can perform various searching operations using the various functions that are provided in the library like argmax, argmin, nanaargmax etc." }, { "code": null, "e": 44863, "s": 44762, "text": "numpy.argmax() : This function returns indices of the max element of the array in a particular axis." }, { "code": null, "e": 44872, "s": 44863, "text": "Output :" }, { "code": null, "e": 45026, "s": 44872, "text": "INPUT ARRAY : \n [[ 0 1 2 3]\n [ 4 5 6 7]\n [ 8 9 10 11]]\n\nMax element : 11\n\nIndices of Max element : [2 2 2 2]\n\nIndices of Max element : [3 3 3]\n" }, { "code": null, "e": 45214, "s": 45026, "text": " numpy.nanargmax() : This function returns indices of the max element of the array in a particular axis ignoring NaNs.The results cannot be trusted if a slice contains only NaNs and Infs." }, { "code": null, "e": 45223, "s": 45214, "text": "Output :" }, { "code": null, "e": 45406, "s": 45223, "text": "INPUT ARRAY 1 : \n [nan, 4, 2, 3, 1]\n\nIndices of max in array1 : 1\n\nINPUT ARRAY 2 : \n [[ nan 4.]\n [ 1. 3.]]\n\nIndices of max in array2 : 1\n\nIndices at axis 1 of array2 : [1 1]\n" }, { "code": null, "e": 45495, "s": 45406, "text": " numpy.argmin() : This function returns the indices of the minimum values along an axis." }, { "code": null, "e": 45504, "s": 45495, "text": "Output :" }, { "code": null, "e": 45568, "s": 45504, "text": "INPUT ARRAY : \n [0 1 2 3 4 5 6 7]\n\nIndices of min element : 0\n" }, { "code": null, "e": 45646, "s": 45570, "text": "numpy.count_nonzero() : Counts the number of non-zero values in the array ." }, { "code": null, "e": 45655, "s": 45646, "text": "Output :" }, { "code": null, "e": 45734, "s": 45655, "text": "Number of nonzero values is : 5\nNumber of nonzero values is : [1, 1, 1, 1, 1]\n" }, { "code": null, "e": 45834, "s": 45736, "text": "Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here." }, { "code": null, "e": 45908, "s": 45834, "text": "Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ..." }, { "code": null, "e": 45966, "s": 45908, "text": "Learn C++ Programming Step by Step - A 20 Day Curriculum!" }, { "code": null, "e": 46019, "s": 45966, "text": "Must Do Coding Questions for Product Based Companies" }, { "code": null, "e": 46055, "s": 46019, "text": "CSS Interview Questions and Answers" }, { "code": null, "e": 46087, "s": 46055, "text": "50 Common Ports You Should Know" }, { "code": null, "e": 46153, "s": 46087, "text": "GeeksforGeeks Jobathon - Are You Ready For This Hiring Challenge?" }, { "code": null, "e": 46198, "s": 46153, "text": "How to Find Length of String in Bash Script?" }, { "code": null, "e": 46254, "s": 46198, "text": "Samsung R&D Internship Interview Experience (On-Campus)" }, { "code": null, "e": 46320, "s": 46254, "text": "Tiger Analytics Interview Experience for Data Analyst (On-Campus)" } ]
How to convert a double value to String in Java?
The double data type in Java stores double-precision 64-bit IEEE 754 floating point number. It is used as the default type for decimal value in Java. Like all other primitive variables double also have a wrapper class (Double) wrapping the primitive data type. Since java supports auto boxing, the primitive value and the object can be used interchangeably. You can convert a double value into String in various different ways in Java − The + operator is an addition operator but when used with Strings it acts as a concatenation operator. It concatenates the other operand to String and returns a String object. You can convert a double value into a String by simply adding it to an empty String using the “+” operator. In-fact it is the easy way to convert a double value to a String. Example import java.util.Scanner; public class ConversionOfDouble { public static void main(String args[]) { Scanner sc = new Scanner(System.in); System.out.println("Enter a double value:"); Double d = sc.nextDouble(); String result = ""+d; System.out.println("The result is: "+result); } } Output Enter a double value: 2548.2325 The result is: 2548.2325 The toString() method of the wrapper class Double returns the String format of the current Double object. Read the required primitive double value in to the Double class reference variable (auto-boxing happens) and, convert it into a String using the toString() method. Example import java.util.Scanner; public class ConversionOfDouble { public static void main(String args[]) { Scanner sc = new Scanner(System.in); System.out.println("Enter a double value:"); Double d = sc.nextDouble(); String result = d.toString(); System.out.println("The result is: "+result); } } Output Enter a double value: 2548.2325 The result is: 2548.2325 Or, you can directly pass the double value to the toString() method directly − public class ConversionOfDouble { public static void main(String args[]) { Scanner sc = new Scanner(System.in); System.out.println("Enter a double value:"); double d = sc.nextDouble(); String result = Double.toString(d); System.out.println("The result is: "+result); } } The valueOf() method of the String class accepts a char or, char array or, double or, float or, int or, long or an object as a parameter and returns its String representation. You can pass the required double value as a parameter to this method and retrieve its Sting format. Example import java.util.Scanner; public class ConversionOfDouble { public static void main(String args[]) { Scanner sc = new Scanner(System.in); System.out.println("Enter a double value:"); Double d = sc.nextDouble(); String result = "".valueOf(d); System.out.println("The result is: "+result); } } Output Enter a double value: 2548.2325 The result is: 2548.2325 This method accepts a format String and arguments (var-args) and returns a String object of the given variable(s) in the specified format. You can format a double value into a String using the format() method. To it pass “%f” as the format string (along with the required double value). Example import java.util.Scanner; public class ConversionOfDouble { public static void main(String args[]) { Scanner sc = new Scanner(System.in); System.out.println("Enter a double value:"); double d = sc.nextDouble(); String result = String.format("%f", d); System.out.println("The result is: "+result); } } Output Enter a double value: 2548.2325 The result is: 2548.2325 The append method of the StringBuilder or StringBuffer objects accept a Boolean or, char or, char array or, double or, float or, int or, long or, String value as parameter and adds it to the current object. You can append the required double value to the method and retrieve a String from obtained StringBuffer (or, StringBuilder) objects. Example import java.util.Scanner; public class ConversionOfDouble { public static void main(String args[]) { Scanner sc = new Scanner(System.in); System.out.println("Enter a double value:"); double d = sc.nextDouble(); StringBuffer sb = new StringBuffer(); sb.append(d); String result = sb.toString(); System.out.println("The result is: "+result); } } Output Enter a double value: 2548.2325 The result is: 2548.2325
[ { "code": null, "e": 1337, "s": 1187, "text": "The double data type in Java stores double-precision 64-bit IEEE 754 floating point number. It is used as the default type for decimal value in Java." }, { "code": null, "e": 1545, "s": 1337, "text": "Like all other primitive variables double also have a wrapper class (Double) wrapping the primitive data type. Since java supports auto boxing, the primitive value and the object can be used interchangeably." }, { "code": null, "e": 1624, "s": 1545, "text": "You can convert a double value into String in various different ways in Java −" }, { "code": null, "e": 1800, "s": 1624, "text": "The + operator is an addition operator but when used with Strings it acts as a concatenation operator. It concatenates the other operand to String and returns a String object." }, { "code": null, "e": 1974, "s": 1800, "text": "You can convert a double value into a String by simply adding it to an empty String using the “+” operator. In-fact it is the easy way to convert a double value to a String." }, { "code": null, "e": 1982, "s": 1974, "text": "Example" }, { "code": null, "e": 2301, "s": 1982, "text": "import java.util.Scanner;\npublic class ConversionOfDouble {\n public static void main(String args[]) {\n Scanner sc = new Scanner(System.in);\n System.out.println(\"Enter a double value:\");\n Double d = sc.nextDouble();\n String result = \"\"+d;\n System.out.println(\"The result is: \"+result);\n }\n}" }, { "code": null, "e": 2308, "s": 2301, "text": "Output" }, { "code": null, "e": 2365, "s": 2308, "text": "Enter a double value:\n2548.2325\nThe result is: 2548.2325" }, { "code": null, "e": 2471, "s": 2365, "text": "The toString() method of the wrapper class Double returns the String format of the current Double object." }, { "code": null, "e": 2635, "s": 2471, "text": "Read the required primitive double value in to the Double class reference variable (auto-boxing happens) and, convert it into a String using the toString() method." }, { "code": null, "e": 2643, "s": 2635, "text": "Example" }, { "code": null, "e": 2970, "s": 2643, "text": "import java.util.Scanner;\npublic class ConversionOfDouble {\n public static void main(String args[]) {\n Scanner sc = new Scanner(System.in);\n System.out.println(\"Enter a double value:\");\n Double d = sc.nextDouble();\n String result = d.toString();\n System.out.println(\"The result is: \"+result);\n }\n}" }, { "code": null, "e": 2977, "s": 2970, "text": "Output" }, { "code": null, "e": 3034, "s": 2977, "text": "Enter a double value:\n2548.2325\nThe result is: 2548.2325" }, { "code": null, "e": 3113, "s": 3034, "text": "Or, you can directly pass the double value to the toString() method directly −" }, { "code": null, "e": 3403, "s": 3113, "text": "public class ConversionOfDouble {\n public static void main(String args[]) {\n Scanner sc = new Scanner(System.in);\n System.out.println(\"Enter a double value:\");\n double d = sc.nextDouble();\nString result = Double.toString(d);\nSystem.out.println(\"The result is: \"+result);\n}\n}" }, { "code": null, "e": 3579, "s": 3403, "text": "The valueOf() method of the String class accepts a char or, char array or, double or, float or, int or, long or an object as a parameter and returns its String representation." }, { "code": null, "e": 3679, "s": 3579, "text": "You can pass the required double value as a parameter to this method and retrieve its Sting format." }, { "code": null, "e": 3687, "s": 3679, "text": "Example" }, { "code": null, "e": 3979, "s": 3687, "text": "import java.util.Scanner;\npublic class ConversionOfDouble {\npublic static void main(String args[]) {\nScanner sc = new Scanner(System.in);\nSystem.out.println(\"Enter a double value:\");\nDouble d = sc.nextDouble();\nString result = \"\".valueOf(d);\nSystem.out.println(\"The result is: \"+result);\n}\n}" }, { "code": null, "e": 3986, "s": 3979, "text": "Output" }, { "code": null, "e": 4043, "s": 3986, "text": "Enter a double value:\n2548.2325\nThe result is: 2548.2325" }, { "code": null, "e": 4182, "s": 4043, "text": "This method accepts a format String and arguments (var-args) and returns a String object of the given variable(s) in the specified format." }, { "code": null, "e": 4330, "s": 4182, "text": "You can format a double value into a String using the format() method. To it pass “%f” as the format string (along with the required double value)." }, { "code": null, "e": 4338, "s": 4330, "text": "Example" }, { "code": null, "e": 4675, "s": 4338, "text": "import java.util.Scanner;\npublic class ConversionOfDouble {\n public static void main(String args[]) {\n Scanner sc = new Scanner(System.in);\n System.out.println(\"Enter a double value:\");\n double d = sc.nextDouble();\n String result = String.format(\"%f\", d);\n System.out.println(\"The result is: \"+result);\n }\n}" }, { "code": null, "e": 4682, "s": 4675, "text": "Output" }, { "code": null, "e": 4739, "s": 4682, "text": "Enter a double value:\n2548.2325\nThe result is: 2548.2325" }, { "code": null, "e": 4946, "s": 4739, "text": "The append method of the StringBuilder or StringBuffer objects accept a Boolean or, char or, char array or, double or, float or, int or, long or, String value as parameter and adds it to the current object." }, { "code": null, "e": 5079, "s": 4946, "text": "You can append the required double value to the method and retrieve a String from obtained StringBuffer (or, StringBuilder) objects." }, { "code": null, "e": 5087, "s": 5079, "text": "Example" }, { "code": null, "e": 5431, "s": 5087, "text": "import java.util.Scanner;\npublic class ConversionOfDouble {\npublic static void main(String args[]) {\nScanner sc = new Scanner(System.in);\nSystem.out.println(\"Enter a double value:\");\ndouble d = sc.nextDouble();\nStringBuffer sb = new StringBuffer();\nsb.append(d);\nString result = sb.toString();\nSystem.out.println(\"The result is: \"+result);\n}\n}" }, { "code": null, "e": 5438, "s": 5431, "text": "Output" }, { "code": null, "e": 5495, "s": 5438, "text": "Enter a double value:\n2548.2325\nThe result is: 2548.2325" } ]
How to convert a currency string to a double value with jQuery or Javascript?
17 Jun, 2019 There are two popular ways to convert currency string into float string using different JavaScript inbuilt libraries. Method 1: This is a simple approach in which we will match character one by one from starting using the loop and if any character comes out to be of integer type or numeric type then we will use substring() method to take out substring from original string. After taking out substring we will use parseFloat() method to convert that string to float ot double value.To check whether the character is of numeric type or not, we use charCodeAt() method to get the Unicode value of the specified character. string.substring(Startindex, Endindex)The string.substring() is an inbuilt function in JavaScript which is used to return the part of the given string from start index to end index. Indexing start from zero (0). string.substring(Startindex, Endindex) The string.substring() is an inbuilt function in JavaScript which is used to return the part of the given string from start index to end index. Indexing start from zero (0). parseFloat(value)The parseFloat() is an inbuilt function in JavaScript which is used to accept the string and convert it into a floating point number. If the string does not contain a numeral value or If the first character of the string is not a Number then it returns NaN i.e, not a number. It actually returns a floating point number parsed up to that point where it encounters a character which is not a Number. parseFloat(value) The parseFloat() is an inbuilt function in JavaScript which is used to accept the string and convert it into a floating point number. If the string does not contain a numeral value or If the first character of the string is not a Number then it returns NaN i.e, not a number. It actually returns a floating point number parsed up to that point where it encounters a character which is not a Number. str.charCodeAt(index)str.charCodeAt() function returns a Unicode character set code unit of the character present at the index in the string specified as the argument. str.charCodeAt(index) str.charCodeAt() function returns a Unicode character set code unit of the character present at the index in the string specified as the argument. Example 1: <script> // JavaScript script to convert // string currency to double // Function to convert function convert(currency){ var k, temp; // Loop to make substring for(var i = 0; i < currency.length; i++){ // Getting Unicode value k = currency.charCodeAt(i); // Checking whether the character // is of numeric type or not if(k > 47 && k < 58){ // Making substring temp = currency.substring(i); break; } } // If currency is in format like // 458, 656.75 then we used replace // method to replace every ', ' with '' temp = temp.replace(/, /, ''); // Converting string to float // or double and return return parseFloat(temp); } // Driver code // Currency in string var string_currency = "$450.45"; document.write("Currency value: " + string_currency +"</br>"); // Converting currency var doubleValue = convert(string_currency); // Display currency document.write("Double value: " +doubleValue + "</br>"); // Currency in string string_currency = "$45, 645.45"; document.write("Currency value: " + string_currency +"</br>"); // Converting currency doubleValue = convert(string_currency); // Display currency document.write("Double value: " + doubleValue + "</br>"); </script> Output: Currency value: $450.45 Double value: 450.45 Currency value: $45, 645.45 Double value: 45645.45 Method 2: In this method we will use replace()method of JavaScript to replace every character other than numbers and decimal (.) with blank (“”). After then we can use parseFloat() method to make string to float or double. This method is more efficient than method 1. str.replace(A, B)The string.replace() is an inbuilt function in JavaScript which is used to replace a part of the given string with some another string or a regular expression. The original string will remain unchanged. str.replace(A, B) The string.replace() is an inbuilt function in JavaScript which is used to replace a part of the given string with some another string or a regular expression. The original string will remain unchanged. parseFloat(value)The parseFloat() is an inbuilt function in JavaScript which is used to accept the string and convert it into a floating point number. If the string does not contain a numeral value or If the first character of the string is not a Number then it returns NaN i.e, not a number. It actually returns a floating point number parsed up to that point where it encounters a character which is not a Number. parseFloat(value) The parseFloat() is an inbuilt function in JavaScript which is used to accept the string and convert it into a floating point number. If the string does not contain a numeral value or If the first character of the string is not a Number then it returns NaN i.e, not a number. It actually returns a floating point number parsed up to that point where it encounters a character which is not a Number. Example 2: <script> // JavaScript script to convert // string currency to double // Function to convert function convert(currency){ // Using replace() method // to make currency string suitable // for parseFloat() to convert var temp = currency.replace(/[^0-9.-]+/g,""); // Converting string to float // or double and return return parseFloat(temp); } // Driver code // Currency in string var string_currency = "$6542.45"; document.write("Currency value: " + string_currency +"</br>"); // Converting currency var doubleValue = convert(string_currency); // Display currency document.write("Converted to double: " + doubleValue +"</br>"); // Currency in string string_currency = "$357,545.45"; document.write("Currency value: " + string_currency +"</br>"); // Converting currency doubleValue = convert(string_currency); // Display currency document.write("Converted to double: " + doubleValue +"</br>"); </script> Output: Currency value: $6542.45 Converted to double: 6542.45 Currency value: $357,545.45 Converted to double: 357545.45 javascript-string Picked JavaScript Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Remove elements from a JavaScript Array Difference Between PUT and PATCH Request Roadmap to Learn JavaScript For Beginners JavaScript | Promises How to filter object array based on attributes? Lodash _.debounce() Method JavaScript String includes() Method JavaScript | fetch() Method Async/Await Function in JavaScript
[ { "code": null, "e": 52, "s": 24, "text": "\n17 Jun, 2019" }, { "code": null, "e": 170, "s": 52, "text": "There are two popular ways to convert currency string into float string using different JavaScript inbuilt libraries." }, { "code": null, "e": 673, "s": 170, "text": "Method 1: This is a simple approach in which we will match character one by one from starting using the loop and if any character comes out to be of integer type or numeric type then we will use substring() method to take out substring from original string. After taking out substring we will use parseFloat() method to convert that string to float ot double value.To check whether the character is of numeric type or not, we use charCodeAt() method to get the Unicode value of the specified character." }, { "code": null, "e": 885, "s": 673, "text": "string.substring(Startindex, Endindex)The string.substring() is an inbuilt function in JavaScript which is used to return the part of the given string from start index to end index. Indexing start from zero (0)." }, { "code": null, "e": 924, "s": 885, "text": "string.substring(Startindex, Endindex)" }, { "code": null, "e": 1098, "s": 924, "text": "The string.substring() is an inbuilt function in JavaScript which is used to return the part of the given string from start index to end index. Indexing start from zero (0)." }, { "code": null, "e": 1514, "s": 1098, "text": "parseFloat(value)The parseFloat() is an inbuilt function in JavaScript which is used to accept the string and convert it into a floating point number. If the string does not contain a numeral value or If the first character of the string is not a Number then it returns NaN i.e, not a number. It actually returns a floating point number parsed up to that point where it encounters a character which is not a Number." }, { "code": null, "e": 1532, "s": 1514, "text": "parseFloat(value)" }, { "code": null, "e": 1931, "s": 1532, "text": "The parseFloat() is an inbuilt function in JavaScript which is used to accept the string and convert it into a floating point number. If the string does not contain a numeral value or If the first character of the string is not a Number then it returns NaN i.e, not a number. It actually returns a floating point number parsed up to that point where it encounters a character which is not a Number." }, { "code": null, "e": 2099, "s": 1931, "text": "str.charCodeAt(index)str.charCodeAt() function returns a Unicode character set code unit of the character present at the index in the string specified as the argument." }, { "code": null, "e": 2121, "s": 2099, "text": "str.charCodeAt(index)" }, { "code": null, "e": 2268, "s": 2121, "text": "str.charCodeAt() function returns a Unicode character set code unit of the character present at the index in the string specified as the argument." }, { "code": null, "e": 2279, "s": 2268, "text": "Example 1:" }, { "code": "<script> // JavaScript script to convert // string currency to double // Function to convert function convert(currency){ var k, temp; // Loop to make substring for(var i = 0; i < currency.length; i++){ // Getting Unicode value k = currency.charCodeAt(i); // Checking whether the character // is of numeric type or not if(k > 47 && k < 58){ // Making substring temp = currency.substring(i); break; } } // If currency is in format like // 458, 656.75 then we used replace // method to replace every ', ' with '' temp = temp.replace(/, /, ''); // Converting string to float // or double and return return parseFloat(temp); } // Driver code // Currency in string var string_currency = \"$450.45\"; document.write(\"Currency value: \" + string_currency +\"</br>\"); // Converting currency var doubleValue = convert(string_currency); // Display currency document.write(\"Double value: \" +doubleValue + \"</br>\"); // Currency in string string_currency = \"$45, 645.45\"; document.write(\"Currency value: \" + string_currency +\"</br>\"); // Converting currency doubleValue = convert(string_currency); // Display currency document.write(\"Double value: \" + doubleValue + \"</br>\"); </script> ", "e": 3779, "s": 2279, "text": null }, { "code": null, "e": 3787, "s": 3779, "text": "Output:" }, { "code": null, "e": 3884, "s": 3787, "text": "Currency value: $450.45\nDouble value: 450.45\nCurrency value: $45, 645.45\nDouble value: 45645.45\n" }, { "code": null, "e": 4152, "s": 3884, "text": "Method 2: In this method we will use replace()method of JavaScript to replace every character other than numbers and decimal (.) with blank (“”). After then we can use parseFloat() method to make string to float or double. This method is more efficient than method 1." }, { "code": null, "e": 4372, "s": 4152, "text": "str.replace(A, B)The string.replace() is an inbuilt function in JavaScript which is used to replace a part of the given string with some another string or a regular expression. The original string will remain unchanged." }, { "code": null, "e": 4390, "s": 4372, "text": "str.replace(A, B)" }, { "code": null, "e": 4593, "s": 4390, "text": "The string.replace() is an inbuilt function in JavaScript which is used to replace a part of the given string with some another string or a regular expression. The original string will remain unchanged." }, { "code": null, "e": 5009, "s": 4593, "text": "parseFloat(value)The parseFloat() is an inbuilt function in JavaScript which is used to accept the string and convert it into a floating point number. If the string does not contain a numeral value or If the first character of the string is not a Number then it returns NaN i.e, not a number. It actually returns a floating point number parsed up to that point where it encounters a character which is not a Number." }, { "code": null, "e": 5027, "s": 5009, "text": "parseFloat(value)" }, { "code": null, "e": 5426, "s": 5027, "text": "The parseFloat() is an inbuilt function in JavaScript which is used to accept the string and convert it into a floating point number. If the string does not contain a numeral value or If the first character of the string is not a Number then it returns NaN i.e, not a number. It actually returns a floating point number parsed up to that point where it encounters a character which is not a Number." }, { "code": null, "e": 5437, "s": 5426, "text": "Example 2:" }, { "code": " <script> // JavaScript script to convert // string currency to double // Function to convert function convert(currency){ // Using replace() method // to make currency string suitable // for parseFloat() to convert var temp = currency.replace(/[^0-9.-]+/g,\"\"); // Converting string to float // or double and return return parseFloat(temp); } // Driver code // Currency in string var string_currency = \"$6542.45\"; document.write(\"Currency value: \" + string_currency +\"</br>\"); // Converting currency var doubleValue = convert(string_currency); // Display currency document.write(\"Converted to double: \" + doubleValue +\"</br>\"); // Currency in string string_currency = \"$357,545.45\"; document.write(\"Currency value: \" + string_currency +\"</br>\"); // Converting currency doubleValue = convert(string_currency); // Display currency document.write(\"Converted to double: \" + doubleValue +\"</br>\"); </script> ", "e": 6524, "s": 5437, "text": null }, { "code": null, "e": 6532, "s": 6524, "text": "Output:" }, { "code": null, "e": 6646, "s": 6532, "text": "Currency value: $6542.45\nConverted to double: 6542.45\nCurrency value: $357,545.45\nConverted to double: 357545.45\n" }, { "code": null, "e": 6664, "s": 6646, "text": "javascript-string" }, { "code": null, "e": 6671, "s": 6664, "text": "Picked" }, { "code": null, "e": 6682, "s": 6671, "text": "JavaScript" }, { "code": null, "e": 6780, "s": 6682, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6841, "s": 6780, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 6881, "s": 6841, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 6922, "s": 6881, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 6964, "s": 6922, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 6986, "s": 6964, "text": "JavaScript | Promises" }, { "code": null, "e": 7034, "s": 6986, "text": "How to filter object array based on attributes?" }, { "code": null, "e": 7061, "s": 7034, "text": "Lodash _.debounce() Method" }, { "code": null, "e": 7097, "s": 7061, "text": "JavaScript String includes() Method" }, { "code": null, "e": 7125, "s": 7097, "text": "JavaScript | fetch() Method" } ]
How to Develop User Registration Form in ReactJS ?
10 Jan, 2022 Form is usually defined inside the <form> tag in conventional HTML code and also in ReactJS. It can have the usual form submission behavior that can take to a new page but that will not make use of react full potential, instead, as we all know it is done using react components. Approach: As we all know React is famous for the components and hooks and its reusability, we are going to use the component to create a form. This form component just like an ordinary HTML form can have labels, input fields, text area, radio button, check box, etc. On top of that, it can also have different attributes with little modification i.e. “for” attribute is replaced by “htmlfor”, “class” is replaced by “className”. It still can have some of the old practices such as “value” property is still there. As we are having the strength of React, we will handle the form by creating different methods for that i.e. to handle the change in any field of the form there will be a method when submit button is clicked there will be a method for it, likewise. We will not hold the value received by the form in a normal JavaScript variable instead we will use high-powerful react hooks. i.e. useState hook. For that let us, first of all, see how we can use this useState hook with form. Using useState with the form data: Every component can have its own states, these states can be updated using the hook useState and the effect will be reflected through the component. Here, the “name” has been given to be the state variable and it has an initial value as “GFG”. We have also given the property onChange which is used to specify the method that should be executed whenever the value of that input field is changed, we have set it to the handleChange, which is yet to define as shown below. Javascript import React,{useState} from 'react' export default function test() { const [name, setName] = useState("GFG"); // HandleChange method to update the states const handleChange = () => (); return ( <div> <form> <input value={name} onChange={handleChange}/> </form> </div> )} Example: Now, let us extend our understanding of useState hook by creating the user form, which will take name, email, and password as the input. It will have one submit button to handle the submission. We will also validate the fields, if either of the fields is empty we will show an error message if not we will show a success message to the user. Create React Application: Create a React application using the following command. npx create-react-app yourappname Project Directory: Then in your “src” folder erase the content of App.css and App.js files and also create one more file named Form.js, finally, your project structure will look like this. Project Structure Filename: App.css This file contains all the CSS that we need for this example which is not only self-explanatory but also out of the scope of this article. Although it is given here for your reference. CSS .App { text-align: center; background-color:green;} .label{ display: block; font-size: larger; color: white; padding: 5px;} .input{ font-size: larger; padding: 5px; margin: 2px; }.btn{ color: white; background-color: red; border-radius: 5px; font-size: larger; display: block; padding: 5px; margin: 10px auto;} .messages{ display: flex; justify-content: center;} .error{ display: block; background-color: red; color: white; width: fit-content; height: 50px; padding: 5px;} .success{ display: block; background-color: lightblue; color: black; width: fit-content; height: 50px; padding: 5px;} Filename: App.js This App.js is the file, which is being rendered by React by default in the index.js file, we will not touch that index.js file, instead all our components which we make will be rendered inside this App.js as shown below. Javascript import './App.css';import Form from "./Form" function App() { return ( <div className="App"> <Form /> </div> );} export default App; Filename: Form.js This file has all the necessary components, functions for our form. First of all, we have imported useState from the react. then we have exported the form component which is having all the states and methods. We have defined states for name, email, and password for holding form data. We also have some other states such as submitted and error for the functionality of the form. Then, we have defined the handleName, handleEmail, handlePassword methods which are used to update the states. After that, we are having a method for handling the submission of the form. It is checking if either of the fields is empty it set errors to true, otherwise, it sets success to true. Then we have defined a success message, which is only displayed if the success is set to true. Then we have an error message which is only displayed if an error is set to true. Then we are returning the component, first of all, we have an h1 to hold the heading of the form. Then we have one division to hold the successMessage() and errorMessage(). And at last, the division which holds the form. It has usual labels and input fields. The onChange to give their respective methods and their value to associate them with the states. Note: The states can only be updated using set methods as shown in the methods. Javascript import { useState } from 'react'; export default function Form() { // States for registration const [name, setName] = useState(''); const [email, setEmail] = useState(''); const [password, setPassword] = useState(''); // States for checking the errors const [submitted, setSubmitted] = useState(false); const [error, setError] = useState(false); // Handling the name change const handleName = (e) => { setName(e.target.value); setSubmitted(false); }; // Handling the email change const handleEmail = (e) => { setEmail(e.target.value); setSubmitted(false); }; // Handling the password change const handlePassword = (e) => { setPassword(e.target.value); setSubmitted(false); }; // Handling the form submission const handleSubmit = (e) => { e.preventDefault(); if (name === '' || email === '' || password === '') { setError(true); } else { setSubmitted(true); setError(false); } }; // Showing success message const successMessage = () => { return ( <div className="success" style={{ display: submitted ? '' : 'none', }}> <h1>User {name} successfully registered!!</h1> </div> ); }; // Showing error message if error is true const errorMessage = () => { return ( <div className="error" style={{ display: error ? '' : 'none', }}> <h1>Please enter all the fields</h1> </div> ); }; return ( <div className="form"> <div> <h1>User Registration</h1> </div> {/* Calling to the methods */} <div className="messages"> {errorMessage()} {successMessage()} </div> <form> {/* Labels and inputs for form data */} <label className="label">Name</label> <input onChange={handleName} className="input" value={name} type="text" /> <label className="label">Email</label> <input onChange={handleEmail} className="input" value={email} type="email" /> <label className="label">Password</label> <input onChange={handlePassword} className="input" value={password} type="password" /> <button onClick={handleSubmit} className="btn" type="submit"> Submit </button> </form> </div> );} Run the application using the following command: npm start Output: Output References: https://reactjs.org/docs/forms.html sratcliffjones rkbhola5 CSS-Properties Picked React-Questions ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Axios in React: A Guide for Beginners Re-rendering Components in ReactJS How to create a table in ReactJS ? ReactJS useNavigate() Hook How to set background images in ReactJS ? 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? Differences between Functional Components and Class Components in React
[ { "code": null, "e": 54, "s": 26, "text": "\n10 Jan, 2022" }, { "code": null, "e": 333, "s": 54, "text": "Form is usually defined inside the <form> tag in conventional HTML code and also in ReactJS. It can have the usual form submission behavior that can take to a new page but that will not make use of react full potential, instead, as we all know it is done using react components." }, { "code": null, "e": 847, "s": 333, "text": "Approach: As we all know React is famous for the components and hooks and its reusability, we are going to use the component to create a form. This form component just like an ordinary HTML form can have labels, input fields, text area, radio button, check box, etc. On top of that, it can also have different attributes with little modification i.e. “for” attribute is replaced by “htmlfor”, “class” is replaced by “className”. It still can have some of the old practices such as “value” property is still there." }, { "code": null, "e": 1095, "s": 847, "text": "As we are having the strength of React, we will handle the form by creating different methods for that i.e. to handle the change in any field of the form there will be a method when submit button is clicked there will be a method for it, likewise." }, { "code": null, "e": 1322, "s": 1095, "text": "We will not hold the value received by the form in a normal JavaScript variable instead we will use high-powerful react hooks. i.e. useState hook. For that let us, first of all, see how we can use this useState hook with form." }, { "code": null, "e": 1506, "s": 1322, "text": "Using useState with the form data: Every component can have its own states, these states can be updated using the hook useState and the effect will be reflected through the component." }, { "code": null, "e": 1828, "s": 1506, "text": "Here, the “name” has been given to be the state variable and it has an initial value as “GFG”. We have also given the property onChange which is used to specify the method that should be executed whenever the value of that input field is changed, we have set it to the handleChange, which is yet to define as shown below." }, { "code": null, "e": 1839, "s": 1828, "text": "Javascript" }, { "code": "import React,{useState} from 'react' export default function test() { const [name, setName] = useState(\"GFG\"); // HandleChange method to update the states const handleChange = () => (); return ( <div> <form> <input value={name} onChange={handleChange}/> </form> </div> )}", "e": 2188, "s": 1839, "text": null }, { "code": null, "e": 2542, "s": 2191, "text": "Example: Now, let us extend our understanding of useState hook by creating the user form, which will take name, email, and password as the input. It will have one submit button to handle the submission. We will also validate the fields, if either of the fields is empty we will show an error message if not we will show a success message to the user." }, { "code": null, "e": 2626, "s": 2544, "text": "Create React Application: Create a React application using the following command." }, { "code": null, "e": 2661, "s": 2628, "text": "npx create-react-app yourappname" }, { "code": null, "e": 2850, "s": 2661, "text": "Project Directory: Then in your “src” folder erase the content of App.css and App.js files and also create one more file named Form.js, finally, your project structure will look like this." }, { "code": null, "e": 2870, "s": 2852, "text": "Project Structure" }, { "code": null, "e": 3073, "s": 2870, "text": "Filename: App.css This file contains all the CSS that we need for this example which is not only self-explanatory but also out of the scope of this article. Although it is given here for your reference." }, { "code": null, "e": 3079, "s": 3075, "text": "CSS" }, { "code": ".App { text-align: center; background-color:green;} .label{ display: block; font-size: larger; color: white; padding: 5px;} .input{ font-size: larger; padding: 5px; margin: 2px; }.btn{ color: white; background-color: red; border-radius: 5px; font-size: larger; display: block; padding: 5px; margin: 10px auto;} .messages{ display: flex; justify-content: center;} .error{ display: block; background-color: red; color: white; width: fit-content; height: 50px; padding: 5px;} .success{ display: block; background-color: lightblue; color: black; width: fit-content; height: 50px; padding: 5px;}", "e": 3701, "s": 3079, "text": null }, { "code": null, "e": 3943, "s": 3704, "text": "Filename: App.js This App.js is the file, which is being rendered by React by default in the index.js file, we will not touch that index.js file, instead all our components which we make will be rendered inside this App.js as shown below." }, { "code": null, "e": 3956, "s": 3945, "text": "Javascript" }, { "code": "import './App.css';import Form from \"./Form\" function App() { return ( <div className=\"App\"> <Form /> </div> );} export default App;", "e": 4107, "s": 3956, "text": null }, { "code": null, "e": 4337, "s": 4110, "text": "Filename: Form.js This file has all the necessary components, functions for our form. First of all, we have imported useState from the react. then we have exported the form component which is having all the states and methods." }, { "code": null, "e": 4621, "s": 4339, "text": "We have defined states for name, email, and password for holding form data. We also have some other states such as submitted and error for the functionality of the form. Then, we have defined the handleName, handleEmail, handlePassword methods which are used to update the states. " }, { "code": null, "e": 4983, "s": 4623, "text": "After that, we are having a method for handling the submission of the form. It is checking if either of the fields is empty it set errors to true, otherwise, it sets success to true. Then we have defined a success message, which is only displayed if the success is set to true. Then we have an error message which is only displayed if an error is set to true." }, { "code": null, "e": 5341, "s": 4985, "text": "Then we are returning the component, first of all, we have an h1 to hold the heading of the form. Then we have one division to hold the successMessage() and errorMessage(). And at last, the division which holds the form. It has usual labels and input fields. The onChange to give their respective methods and their value to associate them with the states." }, { "code": null, "e": 5423, "s": 5343, "text": "Note: The states can only be updated using set methods as shown in the methods." }, { "code": null, "e": 5436, "s": 5425, "text": "Javascript" }, { "code": "import { useState } from 'react'; export default function Form() { // States for registration const [name, setName] = useState(''); const [email, setEmail] = useState(''); const [password, setPassword] = useState(''); // States for checking the errors const [submitted, setSubmitted] = useState(false); const [error, setError] = useState(false); // Handling the name change const handleName = (e) => { setName(e.target.value); setSubmitted(false); }; // Handling the email change const handleEmail = (e) => { setEmail(e.target.value); setSubmitted(false); }; // Handling the password change const handlePassword = (e) => { setPassword(e.target.value); setSubmitted(false); }; // Handling the form submission const handleSubmit = (e) => { e.preventDefault(); if (name === '' || email === '' || password === '') { setError(true); } else { setSubmitted(true); setError(false); } }; // Showing success message const successMessage = () => { return ( <div className=\"success\" style={{ display: submitted ? '' : 'none', }}> <h1>User {name} successfully registered!!</h1> </div> ); }; // Showing error message if error is true const errorMessage = () => { return ( <div className=\"error\" style={{ display: error ? '' : 'none', }}> <h1>Please enter all the fields</h1> </div> ); }; return ( <div className=\"form\"> <div> <h1>User Registration</h1> </div> {/* Calling to the methods */} <div className=\"messages\"> {errorMessage()} {successMessage()} </div> <form> {/* Labels and inputs for form data */} <label className=\"label\">Name</label> <input onChange={handleName} className=\"input\" value={name} type=\"text\" /> <label className=\"label\">Email</label> <input onChange={handleEmail} className=\"input\" value={email} type=\"email\" /> <label className=\"label\">Password</label> <input onChange={handlePassword} className=\"input\" value={password} type=\"password\" /> <button onClick={handleSubmit} className=\"btn\" type=\"submit\"> Submit </button> </form> </div> );}", "e": 7740, "s": 5436, "text": null }, { "code": null, "e": 7792, "s": 7743, "text": "Run the application using the following command:" }, { "code": null, "e": 7804, "s": 7794, "text": "npm start" }, { "code": null, "e": 7812, "s": 7804, "text": "Output:" }, { "code": null, "e": 7821, "s": 7814, "text": "Output" }, { "code": null, "e": 7869, "s": 7821, "text": "References: https://reactjs.org/docs/forms.html" }, { "code": null, "e": 7886, "s": 7871, "text": "sratcliffjones" }, { "code": null, "e": 7895, "s": 7886, "text": "rkbhola5" }, { "code": null, "e": 7910, "s": 7895, "text": "CSS-Properties" }, { "code": null, "e": 7917, "s": 7910, "text": "Picked" }, { "code": null, "e": 7933, "s": 7917, "text": "React-Questions" }, { "code": null, "e": 7941, "s": 7933, "text": "ReactJS" }, { "code": null, "e": 7958, "s": 7941, "text": "Web Technologies" }, { "code": null, "e": 8056, "s": 7958, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8094, "s": 8056, "text": "Axios in React: A Guide for Beginners" }, { "code": null, "e": 8129, "s": 8094, "text": "Re-rendering Components in ReactJS" }, { "code": null, "e": 8164, "s": 8129, "text": "How to create a table in ReactJS ?" }, { "code": null, "e": 8191, "s": 8164, "text": "ReactJS useNavigate() Hook" }, { "code": null, "e": 8233, "s": 8191, "text": "How to set background images in ReactJS ?" }, { "code": null, "e": 8295, "s": 8233, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 8328, "s": 8295, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 8389, "s": 8328, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 8439, "s": 8389, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Python – Element Index in Range Tuples
16 Jan, 2022 Sometimes, while working with Python data, we can have a problem in which we need to find the element position in continuous equi ranged tuples in list. This problem has applications in many domains including day-day programming and competitive programming. Let’s discuss certain ways in which this task can be performed. Input : test_list = [(0, 10), (11, 20), (21, 30), (31, 40)] K = 37 Output : 3Input : test_list = [(0, 9), (10, 19), (20, 29), (30, 39)] K = 37 Output : 3 Method #1 : Using loop This is brute force way in which this task can be performed. In this, we iterate for all the elements in the list and then using comparison operators, find the position of the desired element. Python3 # Python3 code to demonstrate working of# Element Index in Range Tuples# Using loop # initializing listtest_list = [(0, 10), (11, 20), (21, 30), (31, 40), (41, 50)] # printing original listprint("The original list is : " + str(test_list)) # initializing ElementK = 37 # Element Index in Range Tuples# Using loopres = Nonefor idx, ele in enumerate(test_list): if K >= ele[0] and K <= ele[1]: res = idx # printing resultprint("The position of element : " + str(res)) The original list is : [(0, 10), (11, 20), (21, 30), (31, 40), (41, 50)] The position of element : 3 Method #2 : Using formula The element position can also be divided without using a loop, but to extract the same using division of element with the range size, being it consistent. Python3 # Python3 code to demonstrate working of# Element Index in Range Tuples# Using formula # initializing listtest_list = [(0, 10), (11, 20), (21, 30), (31, 40), (41, 50)] # printing original listprint("The original list is : " + str(test_list)) # initializing ElementK = 37 # Element Index in Range Tuples# Using formulares = (K // (test_list[0][1] - test_list[0][0])) # printing resultprint("The position of element : " + str(res)) The original list is : [(0, 10), (11, 20), (21, 30), (31, 40), (41, 50)] The position of element : 3 akshaysingh98088 adnanirshad158 Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n16 Jan, 2022" }, { "code": null, "e": 351, "s": 28, "text": "Sometimes, while working with Python data, we can have a problem in which we need to find the element position in continuous equi ranged tuples in list. This problem has applications in many domains including day-day programming and competitive programming. Let’s discuss certain ways in which this task can be performed. " }, { "code": null, "e": 507, "s": 351, "text": "Input : test_list = [(0, 10), (11, 20), (21, 30), (31, 40)] K = 37 Output : 3Input : test_list = [(0, 9), (10, 19), (20, 29), (30, 39)] K = 37 Output : 3 " }, { "code": null, "e": 724, "s": 507, "text": "Method #1 : Using loop This is brute force way in which this task can be performed. In this, we iterate for all the elements in the list and then using comparison operators, find the position of the desired element. " }, { "code": null, "e": 732, "s": 724, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of# Element Index in Range Tuples# Using loop # initializing listtest_list = [(0, 10), (11, 20), (21, 30), (31, 40), (41, 50)] # printing original listprint(\"The original list is : \" + str(test_list)) # initializing ElementK = 37 # Element Index in Range Tuples# Using loopres = Nonefor idx, ele in enumerate(test_list): if K >= ele[0] and K <= ele[1]: res = idx # printing resultprint(\"The position of element : \" + str(res))", "e": 1215, "s": 732, "text": null }, { "code": null, "e": 1316, "s": 1215, "text": "The original list is : [(0, 10), (11, 20), (21, 30), (31, 40), (41, 50)]\nThe position of element : 3" }, { "code": null, "e": 1501, "s": 1318, "text": " Method #2 : Using formula The element position can also be divided without using a loop, but to extract the same using division of element with the range size, being it consistent. " }, { "code": null, "e": 1509, "s": 1501, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of# Element Index in Range Tuples# Using formula # initializing listtest_list = [(0, 10), (11, 20), (21, 30), (31, 40), (41, 50)] # printing original listprint(\"The original list is : \" + str(test_list)) # initializing ElementK = 37 # Element Index in Range Tuples# Using formulares = (K // (test_list[0][1] - test_list[0][0])) # printing resultprint(\"The position of element : \" + str(res))", "e": 1947, "s": 1509, "text": null }, { "code": null, "e": 2048, "s": 1947, "text": "The original list is : [(0, 10), (11, 20), (21, 30), (31, 40), (41, 50)]\nThe position of element : 3" }, { "code": null, "e": 2067, "s": 2050, "text": "akshaysingh98088" }, { "code": null, "e": 2082, "s": 2067, "text": "adnanirshad158" }, { "code": null, "e": 2103, "s": 2082, "text": "Python list-programs" }, { "code": null, "e": 2110, "s": 2103, "text": "Python" }, { "code": null, "e": 2126, "s": 2110, "text": "Python Programs" } ]
Huffman Coding using Priority Queue
11 Aug, 2021 Prerequisite: Greedy Algorithms | Set 3 (Huffman Coding), priority_queue::push() and priority_queue::pop() in C++ STL Given a char array ch[] and frequency of each character as freq[]. The task is to find Huffman Codes for every character in ch[] using Priority Queue. Example Input: ch[] = { ‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’ }, freq[] = { 5, 9, 12, 13, 16, 45 } Output: f 0 c 100 d 101 a 1100 b 1101 e 111 Approach: Push all the characters in ch[] mapped to corresponding frequency freq[] in priority queue.To create Huffman Tree, pop two nodes from priority queue.Assign two popped node from priority queue as left and right child of new node.Push the new node formed in priority queue.Repeat all above steps until size of priority queue becomes 1.Traverse the Huffman Tree (whose root is the only node left in the priority queue) to store the Huffman CodePrint all the stored Huffman Code for every character in ch[]. Push all the characters in ch[] mapped to corresponding frequency freq[] in priority queue. To create Huffman Tree, pop two nodes from priority queue. Assign two popped node from priority queue as left and right child of new node. Push the new node formed in priority queue. Repeat all above steps until size of priority queue becomes 1. Traverse the Huffman Tree (whose root is the only node left in the priority queue) to store the Huffman Code Print all the stored Huffman Code for every character in ch[]. Below is the implementation of the above approach: C++ // C++ Program for Huffman Coding// using Priority Queue#include <iostream>#include <queue>using namespace std; // Maximum Height of Huffman Tree.#define MAX_SIZE 100 class HuffmanTreeNode {public: // Stores character char data; // Stores frequency of // the character int freq; // Left child of the // current node HuffmanTreeNode* left; // Right child of the // current node HuffmanTreeNode* right; // Initializing the // current node HuffmanTreeNode(char character, int frequency) { data = character; freq = frequency; left = right = NULL; }}; // Custom comparator classclass Compare {public: bool operator()(HuffmanTreeNode* a, HuffmanTreeNode* b) { // Defining priority on // the basis of frequency return a->freq > b->freq; }}; // Function to generate Huffman// Encoding TreeHuffmanTreeNode* generateTree(priority_queue<HuffmanTreeNode*, vector<HuffmanTreeNode*>, Compare> pq){ // We keep on looping till // only one node remains in // the Priority Queue while (pq.size() != 1) { // Node which has least // frequency HuffmanTreeNode* left = pq.top(); // Remove node from // Priority Queue pq.pop(); // Node which has least // frequency HuffmanTreeNode* right = pq.top(); // Remove node from // Priority Queue pq.pop(); // A new node is formed // with frequency left->freq // + right->freq // We take data as '$' // because we are only // concerned with the // frequency HuffmanTreeNode* node = new HuffmanTreeNode('$', left->freq + right->freq); node->left = left; node->right = right; // Push back node // created to the // Priority Queue pq.push(node); } return pq.top();} // Function to print the// huffman code for each// character. // It uses arr to store the codesvoid printCodes(HuffmanTreeNode* root, int arr[], int top){ // Assign 0 to the left node // and recur if (root->left) { arr[top] = 0; printCodes(root->left, arr, top + 1); } // Assign 1 to the right // node and recur if (root->right) { arr[top] = 1; printCodes(root->right, arr, top + 1); } // If this is a leaf node, // then we print root->data // We also print the code // for this character from arr if (!root->left && !root->right) { cout << root->data << " "; for (int i = 0; i < top; i++) { cout << arr[i]; } cout << endl; }} void HuffmanCodes(char data[], int freq[], int size){ // Declaring priority queue // using custom comparator priority_queue<HuffmanTreeNode*, vector<HuffmanTreeNode*>, Compare> pq; // Populating the priority // queue for (int i = 0; i < size; i++) { HuffmanTreeNode* newNode = new HuffmanTreeNode(data[i], freq[i]); pq.push(newNode); } // Generate Huffman Encoding // Tree and get the root node HuffmanTreeNode* root = generateTree(pq); // Print Huffman Codes int arr[MAX_SIZE], top = 0; printCodes(root, arr, top);} // Driver Codeint main(){ char data[] = { 'a', 'b', 'c', 'd', 'e', 'f' }; int freq[] = { 5, 9, 12, 13, 16, 45 }; int size = sizeof(data) / sizeof(data[0]); HuffmanCodes(data, freq, size); return 0;} f 0 c 100 d 101 a 1100 b 1101 e 111 Time Complexity: O(n*logn) where n is the number of unique charactersAuxiliary Space: O(n) namang133 akshaysingh98088 pankajsharmagfg arorakashish0911 priority-queue Algorithms Greedy Greedy priority-queue Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n11 Aug, 2021" }, { "code": null, "e": 323, "s": 54, "text": "Prerequisite: Greedy Algorithms | Set 3 (Huffman Coding), priority_queue::push() and priority_queue::pop() in C++ STL Given a char array ch[] and frequency of each character as freq[]. The task is to find Huffman Codes for every character in ch[] using Priority Queue." }, { "code": null, "e": 332, "s": 323, "text": "Example " }, { "code": null, "e": 461, "s": 332, "text": "Input: ch[] = { ‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’ }, freq[] = { 5, 9, 12, 13, 16, 45 } Output: f 0 c 100 d 101 a 1100 b 1101 e 111 " }, { "code": null, "e": 472, "s": 461, "text": "Approach: " }, { "code": null, "e": 976, "s": 472, "text": "Push all the characters in ch[] mapped to corresponding frequency freq[] in priority queue.To create Huffman Tree, pop two nodes from priority queue.Assign two popped node from priority queue as left and right child of new node.Push the new node formed in priority queue.Repeat all above steps until size of priority queue becomes 1.Traverse the Huffman Tree (whose root is the only node left in the priority queue) to store the Huffman CodePrint all the stored Huffman Code for every character in ch[]." }, { "code": null, "e": 1068, "s": 976, "text": "Push all the characters in ch[] mapped to corresponding frequency freq[] in priority queue." }, { "code": null, "e": 1127, "s": 1068, "text": "To create Huffman Tree, pop two nodes from priority queue." }, { "code": null, "e": 1207, "s": 1127, "text": "Assign two popped node from priority queue as left and right child of new node." }, { "code": null, "e": 1251, "s": 1207, "text": "Push the new node formed in priority queue." }, { "code": null, "e": 1314, "s": 1251, "text": "Repeat all above steps until size of priority queue becomes 1." }, { "code": null, "e": 1423, "s": 1314, "text": "Traverse the Huffman Tree (whose root is the only node left in the priority queue) to store the Huffman Code" }, { "code": null, "e": 1486, "s": 1423, "text": "Print all the stored Huffman Code for every character in ch[]." }, { "code": null, "e": 1539, "s": 1486, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 1543, "s": 1539, "text": "C++" }, { "code": "// C++ Program for Huffman Coding// using Priority Queue#include <iostream>#include <queue>using namespace std; // Maximum Height of Huffman Tree.#define MAX_SIZE 100 class HuffmanTreeNode {public: // Stores character char data; // Stores frequency of // the character int freq; // Left child of the // current node HuffmanTreeNode* left; // Right child of the // current node HuffmanTreeNode* right; // Initializing the // current node HuffmanTreeNode(char character, int frequency) { data = character; freq = frequency; left = right = NULL; }}; // Custom comparator classclass Compare {public: bool operator()(HuffmanTreeNode* a, HuffmanTreeNode* b) { // Defining priority on // the basis of frequency return a->freq > b->freq; }}; // Function to generate Huffman// Encoding TreeHuffmanTreeNode* generateTree(priority_queue<HuffmanTreeNode*, vector<HuffmanTreeNode*>, Compare> pq){ // We keep on looping till // only one node remains in // the Priority Queue while (pq.size() != 1) { // Node which has least // frequency HuffmanTreeNode* left = pq.top(); // Remove node from // Priority Queue pq.pop(); // Node which has least // frequency HuffmanTreeNode* right = pq.top(); // Remove node from // Priority Queue pq.pop(); // A new node is formed // with frequency left->freq // + right->freq // We take data as '$' // because we are only // concerned with the // frequency HuffmanTreeNode* node = new HuffmanTreeNode('$', left->freq + right->freq); node->left = left; node->right = right; // Push back node // created to the // Priority Queue pq.push(node); } return pq.top();} // Function to print the// huffman code for each// character. // It uses arr to store the codesvoid printCodes(HuffmanTreeNode* root, int arr[], int top){ // Assign 0 to the left node // and recur if (root->left) { arr[top] = 0; printCodes(root->left, arr, top + 1); } // Assign 1 to the right // node and recur if (root->right) { arr[top] = 1; printCodes(root->right, arr, top + 1); } // If this is a leaf node, // then we print root->data // We also print the code // for this character from arr if (!root->left && !root->right) { cout << root->data << \" \"; for (int i = 0; i < top; i++) { cout << arr[i]; } cout << endl; }} void HuffmanCodes(char data[], int freq[], int size){ // Declaring priority queue // using custom comparator priority_queue<HuffmanTreeNode*, vector<HuffmanTreeNode*>, Compare> pq; // Populating the priority // queue for (int i = 0; i < size; i++) { HuffmanTreeNode* newNode = new HuffmanTreeNode(data[i], freq[i]); pq.push(newNode); } // Generate Huffman Encoding // Tree and get the root node HuffmanTreeNode* root = generateTree(pq); // Print Huffman Codes int arr[MAX_SIZE], top = 0; printCodes(root, arr, top);} // Driver Codeint main(){ char data[] = { 'a', 'b', 'c', 'd', 'e', 'f' }; int freq[] = { 5, 9, 12, 13, 16, 45 }; int size = sizeof(data) / sizeof(data[0]); HuffmanCodes(data, freq, size); return 0;}", "e": 5212, "s": 1543, "text": null }, { "code": null, "e": 5248, "s": 5212, "text": "f 0\nc 100\nd 101\na 1100\nb 1101\ne 111" }, { "code": null, "e": 5341, "s": 5250, "text": "Time Complexity: O(n*logn) where n is the number of unique charactersAuxiliary Space: O(n)" }, { "code": null, "e": 5351, "s": 5341, "text": "namang133" }, { "code": null, "e": 5368, "s": 5351, "text": "akshaysingh98088" }, { "code": null, "e": 5384, "s": 5368, "text": "pankajsharmagfg" }, { "code": null, "e": 5401, "s": 5384, "text": "arorakashish0911" }, { "code": null, "e": 5416, "s": 5401, "text": "priority-queue" }, { "code": null, "e": 5427, "s": 5416, "text": "Algorithms" }, { "code": null, "e": 5434, "s": 5427, "text": "Greedy" }, { "code": null, "e": 5441, "s": 5434, "text": "Greedy" }, { "code": null, "e": 5456, "s": 5441, "text": "priority-queue" }, { "code": null, "e": 5467, "s": 5456, "text": "Algorithms" } ]
How to get IP address settings using PowerShell?
To get the IP address of the system we can use IPConfig command in cmd and the same command can be used in PowerShell. IPConfig command shows all the connected and disconnected adapters including IPv4 and IPv6. For example, PS C:\Users\Administrator> Ipconfig Windows IP Configuration Ethernet adapter Ethernet0: Connection-specific DNS Suffix . : IPv4 Address. . . . . . . . . . . : 192.168.0.104 Subnet Mask . . . . . . . . . . . : 255.255.255.0 Default Gateway . . . . . . . . . : 192.168.0.1 Tunnel adapter isatap.{27E40122-664A-404D-A4C9-4E48C0363BC5}: Media State . . . . . . . . . . . : Media disconnected Connection-specific DNS Suffix . : Tunnel adapter Local Area Connection* 3: Connection-specific DNS Suffix . : Link-local IPv6 Address . . . . . : fe80::2ca8:29d5:3f57:ff97%5 Default Gateway . . . . . . . . . : But the problem with this utility is if you need to filter specific property like adapter name or the IP family (IPv4 or IPv6), string operation is required to filter the result out and this takes a bunch of lines of code to write. PowerShell also supports the similar command Get-NetIPAddress. Get-NetIPAddress | ft -AutoSize To retrieve only IPv4 addresses, Get-NetIPAddress -AddressFamily IPv4 | ft -AutoSize Similarly, you can retrieve IPv6 addresses. Get-NetIPAddress -AddressFamily IPv6 | ft -AutoSize You can also check if the IP is through DHCP or configured manually. Check the PrefixOrigin and SuffixOrigin properties in the above IPv4 example and that is DHCP. If you have static IP configured then the same will be reflected in both the properties. For Example, To retrieve the IP address for the specific interface, use -InterfaceIndex parameter. For example, Get-NetIPAddress -InterfaceIndex 3 | ft -AutoSize To get the IP address settings for the remote computer, there is -CimSession parameter supported. $sess = New-CimSession -ComputerName Test1-win2k16 Get-NetIPAddress -CimSession $sess | ft -AutoSize You can apply the other parameters to filter out the result as mentioned in the above examples.
[ { "code": null, "e": 1286, "s": 1062, "text": "To get the IP address of the system we can use IPConfig command in cmd and the same command can be used in PowerShell. IPConfig command shows all the connected and disconnected adapters including IPv4 and IPv6. For example," }, { "code": null, "e": 1924, "s": 1286, "text": "PS C:\\Users\\Administrator> Ipconfig\n\nWindows IP Configuration\n\nEthernet adapter Ethernet0:\n\n Connection-specific DNS Suffix . :\n IPv4 Address. . . . . . . . . . . : 192.168.0.104\n Subnet Mask . . . . . . . . . . . : 255.255.255.0\n Default Gateway . . . . . . . . . : 192.168.0.1\n\nTunnel adapter isatap.{27E40122-664A-404D-A4C9-4E48C0363BC5}:\n\n Media State . . . . . . . . . . . : Media disconnected\n Connection-specific DNS Suffix . :\n\nTunnel adapter Local Area Connection* 3:\n\n Connection-specific DNS Suffix . :\n Link-local IPv6 Address . . . . . : fe80::2ca8:29d5:3f57:ff97%5\n Default Gateway . . . . . . . . . :\n" }, { "code": null, "e": 2219, "s": 1924, "text": "But the problem with this utility is if you need to filter specific property like adapter name or the IP family (IPv4 or IPv6), string operation is required to filter the result out and this takes a bunch of lines of code to write. PowerShell also supports the similar command Get-NetIPAddress." }, { "code": null, "e": 2251, "s": 2219, "text": "Get-NetIPAddress | ft -AutoSize" }, { "code": null, "e": 2284, "s": 2251, "text": "To retrieve only IPv4 addresses," }, { "code": null, "e": 2337, "s": 2284, "text": "Get-NetIPAddress -AddressFamily IPv4 | ft -AutoSize\n" }, { "code": null, "e": 2381, "s": 2337, "text": "Similarly, you can retrieve IPv6 addresses." }, { "code": null, "e": 2433, "s": 2381, "text": "Get-NetIPAddress -AddressFamily IPv6 | ft -AutoSize" }, { "code": null, "e": 2699, "s": 2433, "text": "You can also check if the IP is through DHCP or configured manually. Check the PrefixOrigin and SuffixOrigin properties in the above IPv4 example and that is DHCP. If you have static IP configured then the same will be reflected in both the properties. For Example," }, { "code": null, "e": 2798, "s": 2699, "text": "To retrieve the IP address for the specific interface, use -InterfaceIndex parameter. For example," }, { "code": null, "e": 2849, "s": 2798, "text": "Get-NetIPAddress -InterfaceIndex 3 | ft -AutoSize\n" }, { "code": null, "e": 2947, "s": 2849, "text": "To get the IP address settings for the remote computer, there is -CimSession parameter supported." }, { "code": null, "e": 3048, "s": 2947, "text": "$sess = New-CimSession -ComputerName Test1-win2k16\nGet-NetIPAddress -CimSession $sess | ft -AutoSize" }, { "code": null, "e": 3144, "s": 3048, "text": "You can apply the other parameters to filter out the result as mentioned in the above examples." } ]
How to create a responsive side navigation menu with CSS?
Following is the code to create a responsive side navigation menu with CSS − Live Demo <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <style> body { margin: 0; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; } nav { margin: 0; padding: 0; width: 150px; background-color: #2f77e4; position: fixed; height: 100%; overflow: auto; } nav a { display: block; color: rgb(255, 255, 255); font-weight: bolder; font-size: 20px; padding: 16px; text-decoration: none; } nav a.selected { background-color: rgb(15, 189, 20); color: rgb(255, 255, 255); } nav a:hover:not(.selected) { background-color: white; color: #2f77e4; } div.content { margin-left: 200px; padding: 1px 16px; height: 1000px; } @media screen and (max-width: 700px) { nav { width: 100%; height: auto; position: relative; } nav a {float: left;} div.content {margin-left: 0;} } </style> </head> <body> <nav class="sideBar"> <a class="selected" href="#">Home</a> <a href="#">Login</a> <a href="#">Register</a> <a href="#">Message Us</a> <a href="#">Contact Us</a> </nav> <div class="content"> <h1>Sample Text</h1> <h2>Resize the browser to 700px to change vertical navbar to horizontal navbar</h2> </div> </body> </html> This will produce the following output − On resizing the window to 700px −
[ { "code": null, "e": 1139, "s": 1062, "text": "Following is the code to create a responsive side navigation menu with CSS −" }, { "code": null, "e": 1150, "s": 1139, "text": " Live Demo" }, { "code": null, "e": 2378, "s": 1150, "text": "<!DOCTYPE html>\n<html>\n<head>\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n<style>\nbody {\n margin: 0;\n font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;\n}\nnav {\n margin: 0;\n padding: 0;\n width: 150px;\n background-color: #2f77e4;\n position: fixed;\n height: 100%;\n overflow: auto;\n}\nnav a {\n display: block;\n color: rgb(255, 255, 255);\n font-weight: bolder;\n font-size: 20px;\n padding: 16px;\n text-decoration: none;\n}\nnav a.selected {\n background-color: rgb(15, 189, 20);\n color: rgb(255, 255, 255);\n}\nnav a:hover:not(.selected) {\n background-color: white;\n color: #2f77e4;\n}\ndiv.content {\n margin-left: 200px;\n padding: 1px 16px;\n height: 1000px;\n}\n@media screen and (max-width: 700px) {\nnav {\n width: 100%;\n height: auto;\n position: relative;\n}\nnav a {float: left;}\ndiv.content {margin-left: 0;}\n}\n</style>\n</head>\n<body>\n<nav class=\"sideBar\">\n<a class=\"selected\" href=\"#\">Home</a>\n<a href=\"#\">Login</a>\n<a href=\"#\">Register</a>\n<a href=\"#\">Message Us</a>\n<a href=\"#\">Contact Us</a>\n</nav>\n<div class=\"content\">\n<h1>Sample Text</h1>\n<h2>Resize the browser to 700px to change vertical navbar to horizontal navbar</h2>\n</div>\n</body>\n</html>" }, { "code": null, "e": 2419, "s": 2378, "text": "This will produce the following output −" }, { "code": null, "e": 2453, "s": 2419, "text": "On resizing the window to 700px −" } ]
Common Machine Learning Programming Errors in Python | by Sadrach Pierre, Ph.D. | Towards Data Science
In this post I will go over some of the most common errors I come across in python during the model building and development process. For demonstration purposes we will use height/weight data which can be found here on Kaggle. The data contains gender, height in inches and weight in pounds. The most common errors I have come accross in my experience are the following: IMPORTS NameErrorModuleNotFoundErrorAttributeErrorImportError NameError ModuleNotFoundError AttributeError ImportError READING DATA 6. FileNotFoundError SELECTING COLUMNS 7. KeyError DATA PROCESSING 8. ValueError We will build a simple linear regression model and modify the code to show how the above errors arise in practice. First let’s import the data using pandas and print the first five rows: import pandas as pddf = pd.read_csv("weight-height.csv")print(df.head()) As you can see the data set is very simple, with gender, height and weight columns. The next thing we can do is visualize the data using matplotlib and seaborn: import matplotlib.pyplot as pltplt.scatter(df['Weight'], df['Height'])plt.xlabel("Weight")plt.ylabel("Height")plt.show() Looking at the scatter plot of the weight vs height we see that the relationship is linear. Next let’s define our input (X) and output (y) and split the data for training and testing: from sklearn.model_selection import train_test_splitimport numpy as npX = np.array(df["Weight"]).reshape(-1,1)y = np.array(df["Height"]).reshape(-1,1)X_train, X_test, y_train, y_test = train_test_split(X, y, random_state = 42, test_size = 0.33) We can then define a linear regression model, fit to our training data, make predictions on the test set, and evaluate the performance of the model: from sklearn.linear_model import LinearRegressionreg = LinearRegression()reg.fit(X_train, y_train)y_pred = reg.predict(X_test)print("R^2 Accuracy: ", reg.score(X_test, y_test)) The first error I’ll discuss is the NameError which occurs if, for example, I forget to import a package. In the following code I have removed “import numpy as np” : from sklearn.model_selection import train_test_splitX = np.array(df["Weight"]).reshape(-1,1)y = np.array(df["Height"]).reshape(-1,1)X_train, X_test, y_train, y_test = train_test_split(X, y, random_state = 42, test_size = 0.33) If I attempt to run the script with that line of code missing I get the following error: I would receive similar messages for leaving out the import statements for seaborn, matplotlib and pandas: Another issue is accidentally trying to import a package that doesn’t exist due to misspelling, which results in a ModuleNotFoundError. For example if I misspell ‘pandas’ as ‘pandnas’: import pandnas as pd Or if I forgot ‘pyplot’ in the matplotlib scatterplot import we get an AttributeError: import matplotlib as plt Similarly if I forgot the linear_regression and model_selection attributes in the sklearn import, I’ll get an ImportError: from sklearn import LinearRegression from sklearn import train_test_split In terms of reading files, if I misspell the name of the file I get a FileNotFoundError: df = pd.read_csv("weight-heigh1t.csv") Additionally, if I try to select a column from a pandas data frame that doesn’t exist I get a KeyError : plt.scatter(df['Weight1'], df['Height']) If I forget to convert the pandas series for “Weight” and “Height” into numpy arrays I get a ValueError. This is because sklearn methods only accept numpy arrays. I frequently find myself forgetting this simple step of converting from a pandas series to a numpy array: X = df["Weight"]y = df["Height"]X_train, X_test, y_train, y_test = train_test_split(X, y, random_state = 42, test_size = 0.33)reg = LinearRegression()reg.fit(X_train, y_train) or If I forget to reshape the numpy array into a 2 dimensional array I also get a ValueError: X = np.array(df["Weight"])y = np.array(df["Height"])X_train, X_test, y_train, y_test = train_test_split(X, y, random_state = 42, test_size = 0.33)reg = LinearRegression()reg.fit(X_train, y_train) Another common cause of a ValueError is when carrying out the train test split. I often forget the order of the X and y arrays: X_train, X_test, y_train, y_test = train_test_split(X, y, random_state = 42, test_size = 0.33) Where I switch X_test and y_train: X_train, y_train, X_test, y_test = train_test_split(X, y, random_state = 42, test_size = 0.33) which gives the following error upon fitting: Finally, when trying to fit a model data corresponding to a specific category or population I often come across the issue of not having enough data. Let’s filter our dataframe to replicate this issue. Let’s filter the data to only include records where the ‘Weight’ = 241.893563. This will result in exactly one row of data: df = df[df['Weight'] == 241.893563] If we try to build our model we get the following error in the line where we split out data:: X_train, X_test, y_train, y_test = train_test_split(X, y, random_state = 42, test_size = 0.33)reg = LinearRegression()reg.fit(X_train, y_train)y_pred = reg.predict(X_test)print("R^2 Accuracy: ", reg.score(X_test, y_test)) And if we try to fit we get the following error:: #X_train, X_test, y_train, y_test = train_test_split(X, y, random_state = 42, test_size = 0.33)reg = LinearRegression()reg.fit(X, y) Finally, if the data has missing or infinite values the fitting while throw an error. Let’s redefine the weight column with ‘nan ‘ (Not a Number) values to generate this error: df['Weight'] = np.nanX = np.array(df["Weight"]).reshape(-1,1)y = np.array(df["Height"]).reshape(-1,1)X_train, X_test, y_train, y_test = train_test_split(X, y, random_state = 42, test_size = 0.33)reg = LinearRegression()reg.fit(X_train, y_train) We would get the same error message with infinite values: df['Weight'] = np.infX = np.array(df["Weight"]).reshape(-1,1)y = np.array(df["Height"]).reshape(-1,1)X_train, X_test, y_train, y_test = train_test_split(X, y, random_state = 42, test_size = 0.33)reg = LinearRegression()reg.fit(X_train, y_train) In this post we reviewed different errors that arise when developing models in python. We reviewed errors related to importing packages, reading files, selecting columns and processing data. Having solid knowledge of the different types of errors that arise when developing machine learning models can be useful when productionizing machine learning code. Having this knowledge can prevent errors from occurring as well as inform the logic that can be used to catch these errors when they occur. There are many more errors that I come across daily but the errors I’ve listed in this post are most common in my experience. I hope this post was useful. The code from this post is available on GitHub. Thank you for reading!
[ { "code": null, "e": 463, "s": 171, "text": "In this post I will go over some of the most common errors I come across in python during the model building and development process. For demonstration purposes we will use height/weight data which can be found here on Kaggle. The data contains gender, height in inches and weight in pounds." }, { "code": null, "e": 542, "s": 463, "text": "The most common errors I have come accross in my experience are the following:" }, { "code": null, "e": 550, "s": 542, "text": "IMPORTS" }, { "code": null, "e": 604, "s": 550, "text": "NameErrorModuleNotFoundErrorAttributeErrorImportError" }, { "code": null, "e": 614, "s": 604, "text": "NameError" }, { "code": null, "e": 634, "s": 614, "text": "ModuleNotFoundError" }, { "code": null, "e": 649, "s": 634, "text": "AttributeError" }, { "code": null, "e": 661, "s": 649, "text": "ImportError" }, { "code": null, "e": 674, "s": 661, "text": "READING DATA" }, { "code": null, "e": 695, "s": 674, "text": "6. FileNotFoundError" }, { "code": null, "e": 713, "s": 695, "text": "SELECTING COLUMNS" }, { "code": null, "e": 725, "s": 713, "text": "7. KeyError" }, { "code": null, "e": 741, "s": 725, "text": "DATA PROCESSING" }, { "code": null, "e": 755, "s": 741, "text": "8. ValueError" }, { "code": null, "e": 870, "s": 755, "text": "We will build a simple linear regression model and modify the code to show how the above errors arise in practice." }, { "code": null, "e": 942, "s": 870, "text": "First let’s import the data using pandas and print the first five rows:" }, { "code": null, "e": 1015, "s": 942, "text": "import pandas as pddf = pd.read_csv(\"weight-height.csv\")print(df.head())" }, { "code": null, "e": 1176, "s": 1015, "text": "As you can see the data set is very simple, with gender, height and weight columns. The next thing we can do is visualize the data using matplotlib and seaborn:" }, { "code": null, "e": 1298, "s": 1176, "text": "import matplotlib.pyplot as pltplt.scatter(df['Weight'], df['Height'])plt.xlabel(\"Weight\")plt.ylabel(\"Height\")plt.show()" }, { "code": null, "e": 1390, "s": 1298, "text": "Looking at the scatter plot of the weight vs height we see that the relationship is linear." }, { "code": null, "e": 1482, "s": 1390, "text": "Next let’s define our input (X) and output (y) and split the data for training and testing:" }, { "code": null, "e": 1727, "s": 1482, "text": "from sklearn.model_selection import train_test_splitimport numpy as npX = np.array(df[\"Weight\"]).reshape(-1,1)y = np.array(df[\"Height\"]).reshape(-1,1)X_train, X_test, y_train, y_test = train_test_split(X, y, random_state = 42, test_size = 0.33)" }, { "code": null, "e": 1876, "s": 1727, "text": "We can then define a linear regression model, fit to our training data, make predictions on the test set, and evaluate the performance of the model:" }, { "code": null, "e": 2053, "s": 1876, "text": "from sklearn.linear_model import LinearRegressionreg = LinearRegression()reg.fit(X_train, y_train)y_pred = reg.predict(X_test)print(\"R^2 Accuracy: \", reg.score(X_test, y_test))" }, { "code": null, "e": 2219, "s": 2053, "text": "The first error I’ll discuss is the NameError which occurs if, for example, I forget to import a package. In the following code I have removed “import numpy as np” :" }, { "code": null, "e": 2446, "s": 2219, "text": "from sklearn.model_selection import train_test_splitX = np.array(df[\"Weight\"]).reshape(-1,1)y = np.array(df[\"Height\"]).reshape(-1,1)X_train, X_test, y_train, y_test = train_test_split(X, y, random_state = 42, test_size = 0.33)" }, { "code": null, "e": 2535, "s": 2446, "text": "If I attempt to run the script with that line of code missing I get the following error:" }, { "code": null, "e": 2642, "s": 2535, "text": "I would receive similar messages for leaving out the import statements for seaborn, matplotlib and pandas:" }, { "code": null, "e": 2827, "s": 2642, "text": "Another issue is accidentally trying to import a package that doesn’t exist due to misspelling, which results in a ModuleNotFoundError. For example if I misspell ‘pandas’ as ‘pandnas’:" }, { "code": null, "e": 2848, "s": 2827, "text": "import pandnas as pd" }, { "code": null, "e": 2935, "s": 2848, "text": "Or if I forgot ‘pyplot’ in the matplotlib scatterplot import we get an AttributeError:" }, { "code": null, "e": 2960, "s": 2935, "text": "import matplotlib as plt" }, { "code": null, "e": 3083, "s": 2960, "text": "Similarly if I forgot the linear_regression and model_selection attributes in the sklearn import, I’ll get an ImportError:" }, { "code": null, "e": 3157, "s": 3083, "text": "from sklearn import LinearRegression from sklearn import train_test_split" }, { "code": null, "e": 3246, "s": 3157, "text": "In terms of reading files, if I misspell the name of the file I get a FileNotFoundError:" }, { "code": null, "e": 3285, "s": 3246, "text": "df = pd.read_csv(\"weight-heigh1t.csv\")" }, { "code": null, "e": 3390, "s": 3285, "text": "Additionally, if I try to select a column from a pandas data frame that doesn’t exist I get a KeyError :" }, { "code": null, "e": 3432, "s": 3390, "text": "plt.scatter(df['Weight1'], df['Height'])" }, { "code": null, "e": 3701, "s": 3432, "text": "If I forget to convert the pandas series for “Weight” and “Height” into numpy arrays I get a ValueError. This is because sklearn methods only accept numpy arrays. I frequently find myself forgetting this simple step of converting from a pandas series to a numpy array:" }, { "code": null, "e": 3877, "s": 3701, "text": "X = df[\"Weight\"]y = df[\"Height\"]X_train, X_test, y_train, y_test = train_test_split(X, y, random_state = 42, test_size = 0.33)reg = LinearRegression()reg.fit(X_train, y_train)" }, { "code": null, "e": 3971, "s": 3877, "text": "or If I forget to reshape the numpy array into a 2 dimensional array I also get a ValueError:" }, { "code": null, "e": 4167, "s": 3971, "text": "X = np.array(df[\"Weight\"])y = np.array(df[\"Height\"])X_train, X_test, y_train, y_test = train_test_split(X, y, random_state = 42, test_size = 0.33)reg = LinearRegression()reg.fit(X_train, y_train)" }, { "code": null, "e": 4295, "s": 4167, "text": "Another common cause of a ValueError is when carrying out the train test split. I often forget the order of the X and y arrays:" }, { "code": null, "e": 4390, "s": 4295, "text": "X_train, X_test, y_train, y_test = train_test_split(X, y, random_state = 42, test_size = 0.33)" }, { "code": null, "e": 4425, "s": 4390, "text": "Where I switch X_test and y_train:" }, { "code": null, "e": 4520, "s": 4425, "text": "X_train, y_train, X_test, y_test = train_test_split(X, y, random_state = 42, test_size = 0.33)" }, { "code": null, "e": 4566, "s": 4520, "text": "which gives the following error upon fitting:" }, { "code": null, "e": 4891, "s": 4566, "text": "Finally, when trying to fit a model data corresponding to a specific category or population I often come across the issue of not having enough data. Let’s filter our dataframe to replicate this issue. Let’s filter the data to only include records where the ‘Weight’ = 241.893563. This will result in exactly one row of data:" }, { "code": null, "e": 4927, "s": 4891, "text": "df = df[df['Weight'] == 241.893563]" }, { "code": null, "e": 5021, "s": 4927, "text": "If we try to build our model we get the following error in the line where we split out data::" }, { "code": null, "e": 5243, "s": 5021, "text": "X_train, X_test, y_train, y_test = train_test_split(X, y, random_state = 42, test_size = 0.33)reg = LinearRegression()reg.fit(X_train, y_train)y_pred = reg.predict(X_test)print(\"R^2 Accuracy: \", reg.score(X_test, y_test))" }, { "code": null, "e": 5293, "s": 5243, "text": "And if we try to fit we get the following error::" }, { "code": null, "e": 5426, "s": 5293, "text": "#X_train, X_test, y_train, y_test = train_test_split(X, y, random_state = 42, test_size = 0.33)reg = LinearRegression()reg.fit(X, y)" }, { "code": null, "e": 5603, "s": 5426, "text": "Finally, if the data has missing or infinite values the fitting while throw an error. Let’s redefine the weight column with ‘nan ‘ (Not a Number) values to generate this error:" }, { "code": null, "e": 5848, "s": 5603, "text": "df['Weight'] = np.nanX = np.array(df[\"Weight\"]).reshape(-1,1)y = np.array(df[\"Height\"]).reshape(-1,1)X_train, X_test, y_train, y_test = train_test_split(X, y, random_state = 42, test_size = 0.33)reg = LinearRegression()reg.fit(X_train, y_train)" }, { "code": null, "e": 5906, "s": 5848, "text": "We would get the same error message with infinite values:" }, { "code": null, "e": 6151, "s": 5906, "text": "df['Weight'] = np.infX = np.array(df[\"Weight\"]).reshape(-1,1)y = np.array(df[\"Height\"]).reshape(-1,1)X_train, X_test, y_train, y_test = train_test_split(X, y, random_state = 42, test_size = 0.33)reg = LinearRegression()reg.fit(X_train, y_train)" }, { "code": null, "e": 6647, "s": 6151, "text": "In this post we reviewed different errors that arise when developing models in python. We reviewed errors related to importing packages, reading files, selecting columns and processing data. Having solid knowledge of the different types of errors that arise when developing machine learning models can be useful when productionizing machine learning code. Having this knowledge can prevent errors from occurring as well as inform the logic that can be used to catch these errors when they occur." } ]
Python - math.ulp(x) function - GeeksforGeeks
23 Aug, 2021 ULP stands for “Unit in the Last Place”. math.ulp() is introduced in python 3.9.0 version, it returns the value of the least significant bit of the float x. In numerical analysis and computer science, unit of least precision (ULP) or unit in the last place is the spacing between floating-point numbers. Note: If the argument is a NaN (not a number), output is NaN. If input x is negative, output is ulp(-x). If input x is positive infinity, output is inf. If the input is zero, the smallest positive denormalized representable float is the output(smaller than the minimum positive normalized float, sys.float_info.min). If input value x is the largest positive representable float, the value of the least significant bit of x is the output, such that the first float smaller than x is x – ulp(x). Otherwise, if input value x is a positive finite number, the value of the least significant bit of x is the output, such that the first float bigger than x is x + ulp(x). Syntax: math.ulp(x) Parameter: x: float whose ulp is returned Return: Return the value of the least significant bit of the float x. Example: To show the working of math.ulp(x) method. Python3 # python program to explain# math.ulp(x) for different values of ximport mathimport sys # when x is NaNx = float('nan')print(math.ulp(x)) # when x is positive infinityx = float('inf')print(math.ulp(x)) # when x is negative infinityprint(math.ulp(-x)) # when x = 0x = 0.0print(math.ulp(x)) # when x is maximum representable floatx = sys.float_info.maxprint(math.ulp(x)) # x is a positive finite numberx = 5print(math.ulp(x)) # when x is a negative numberx = -5print(math.ulp(x)) Output: nan inf inf 5e-324 1.99584030953472e+292 8.881784197001252e-16 8.881784197001252e-16 rs1686740 Python math-library Python math-library-functions Technical Scripter 2020 Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Defaultdict in Python Python | os.path.join() method Python | Get unique values from a list Selecting rows in pandas DataFrame based on conditions Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 24292, "s": 24264, "text": "\n23 Aug, 2021" }, { "code": null, "e": 24596, "s": 24292, "text": "ULP stands for “Unit in the Last Place”. math.ulp() is introduced in python 3.9.0 version, it returns the value of the least significant bit of the float x. In numerical analysis and computer science, unit of least precision (ULP) or unit in the last place is the spacing between floating-point numbers." }, { "code": null, "e": 24602, "s": 24596, "text": "Note:" }, { "code": null, "e": 24658, "s": 24602, "text": "If the argument is a NaN (not a number), output is NaN." }, { "code": null, "e": 24701, "s": 24658, "text": "If input x is negative, output is ulp(-x)." }, { "code": null, "e": 24749, "s": 24701, "text": "If input x is positive infinity, output is inf." }, { "code": null, "e": 24913, "s": 24749, "text": "If the input is zero, the smallest positive denormalized representable float is the output(smaller than the minimum positive normalized float, sys.float_info.min)." }, { "code": null, "e": 25090, "s": 24913, "text": "If input value x is the largest positive representable float, the value of the least significant bit of x is the output, such that the first float smaller than x is x – ulp(x)." }, { "code": null, "e": 25261, "s": 25090, "text": "Otherwise, if input value x is a positive finite number, the value of the least significant bit of x is the output, such that the first float bigger than x is x + ulp(x)." }, { "code": null, "e": 25281, "s": 25261, "text": "Syntax: math.ulp(x)" }, { "code": null, "e": 25292, "s": 25281, "text": "Parameter:" }, { "code": null, "e": 25323, "s": 25292, "text": "x: float whose ulp is returned" }, { "code": null, "e": 25331, "s": 25323, "text": "Return:" }, { "code": null, "e": 25393, "s": 25331, "text": "Return the value of the least significant bit of the float x." }, { "code": null, "e": 25445, "s": 25393, "text": "Example: To show the working of math.ulp(x) method." }, { "code": null, "e": 25453, "s": 25445, "text": "Python3" }, { "code": "# python program to explain# math.ulp(x) for different values of ximport mathimport sys # when x is NaNx = float('nan')print(math.ulp(x)) # when x is positive infinityx = float('inf')print(math.ulp(x)) # when x is negative infinityprint(math.ulp(-x)) # when x = 0x = 0.0print(math.ulp(x)) # when x is maximum representable floatx = sys.float_info.maxprint(math.ulp(x)) # x is a positive finite numberx = 5print(math.ulp(x)) # when x is a negative numberx = -5print(math.ulp(x))", "e": 25931, "s": 25453, "text": null }, { "code": null, "e": 25939, "s": 25931, "text": "Output:" }, { "code": null, "e": 26024, "s": 25939, "text": "nan\ninf\ninf\n5e-324\n1.99584030953472e+292\n8.881784197001252e-16\n8.881784197001252e-16" }, { "code": null, "e": 26034, "s": 26024, "text": "rs1686740" }, { "code": null, "e": 26054, "s": 26034, "text": "Python math-library" }, { "code": null, "e": 26084, "s": 26054, "text": "Python math-library-functions" }, { "code": null, "e": 26108, "s": 26084, "text": "Technical Scripter 2020" }, { "code": null, "e": 26115, "s": 26108, "text": "Python" }, { "code": null, "e": 26134, "s": 26115, "text": "Technical Scripter" }, { "code": null, "e": 26232, "s": 26134, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26264, "s": 26232, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26320, "s": 26264, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26362, "s": 26320, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26404, "s": 26362, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26426, "s": 26404, "text": "Defaultdict in Python" }, { "code": null, "e": 26457, "s": 26426, "text": "Python | os.path.join() method" }, { "code": null, "e": 26496, "s": 26457, "text": "Python | Get unique values from a list" }, { "code": null, "e": 26551, "s": 26496, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 26580, "s": 26551, "text": "Create a directory in Python" } ]
Intellij Idea - Quick Guide
IntelliJ is one of the most powerful and popular Integrated Development Environments (IDE) for Java. It is developed and maintained by JetBrains and available as community and ultimate edition. This feature rich IDE enables rapid development and helps in improving code quality. IDE stands for Integrated Development Environment. It is a combination of multiple tools, which make software development process easier, robust and less error-prone. It has following benefits over plain text editor − Integration with useful tools like compiler, debugger, version control system, build tools, various frameworks, application profilers and so on. Integration with useful tools like compiler, debugger, version control system, build tools, various frameworks, application profilers and so on. Supports code navigation, code completion, code refactoring and code generation features which boosts development process. Supports code navigation, code completion, code refactoring and code generation features which boosts development process. Supports unit testing, integration testing and code coverage via plug-ins. Supports unit testing, integration testing and code coverage via plug-ins. Provides rich set of plug-ins to enhance IDE functionality further. Provides rich set of plug-ins to enhance IDE functionality further. IntelliJ IDEA has some top productive Java code completion features. Its predictive algorithm can accurately assume what a coder is attempting to type, and completes it for him, even if he doesn’t know the exact name of a particular class, member or any other resource. IntelliJ IDEA really understands and has a deep insight into your code, as well as the context of the coder, which makes it so unique among other Java IDEs. Smart code completion − It supports context based code completion. It gives a list of the most relevant symbols applicable in the current context. Smart code completion − It supports context based code completion. It gives a list of the most relevant symbols applicable in the current context. Chain code completion − It is an advanced code completion feature which lists applicable symbols accessible via methods or getters in the current context. Chain code completion − It is an advanced code completion feature which lists applicable symbols accessible via methods or getters in the current context. Static member's completion − It allows you to use static methods or constants and automatically adds the required import statements to avoid compilation error. Static member's completion − It allows you to use static methods or constants and automatically adds the required import statements to avoid compilation error. Detecting duplicates − It finds the duplicate code fragments on the fly and gives notification/suggestion about it to user. Detecting duplicates − It finds the duplicate code fragments on the fly and gives notification/suggestion about it to user. Inspections and quick-fixes − Whenever IntelliJ detects that you're about to make a mistake, a little light bulb notification pops up on same line. Clicking it shows the suggestion list. Inspections and quick-fixes − Whenever IntelliJ detects that you're about to make a mistake, a little light bulb notification pops up on same line. Clicking it shows the suggestion list. IntelliJ IDEA is designed around the coding principle that developers should be allowed to write codes with as less distraction as possible. That is why in this case, the editor is the only thing visible on the screen, with dedicated shortcuts for all other coding-unrelated functions. Editor-centric environment − Quick pop-ups help in checking additional information without leaving the current context. Editor-centric environment − Quick pop-ups help in checking additional information without leaving the current context. Shortcuts for everything − IntelliJ IDEA has keyboard shortcuts for nearly everything, including rapid selection and switching between tool windows and many more. Shortcuts for everything − IntelliJ IDEA has keyboard shortcuts for nearly everything, including rapid selection and switching between tool windows and many more. Inline debugger − Inline debugger allows you to debug application in IDE itself. It makes the development and debugging process seamless. Inline debugger − Inline debugger allows you to debug application in IDE itself. It makes the development and debugging process seamless. To help the developers organize their workflow, IntelliJ IDEA offers them an amazing toolset, which comprises of a decompiler, Docker support, bytecode viewer, FTP and many other tools − Version control − IntelliJ supports most of the popular version control system like Git, Subversion, Mercurial, CVS, Perforce, and TFS. Version control − IntelliJ supports most of the popular version control system like Git, Subversion, Mercurial, CVS, Perforce, and TFS. Build tools − IntelliJ supports Java and other build tools like Maven, Gradle, Ant, Gant, SBT, NPM, Webpack, Grunt, and Gulp. Build tools − IntelliJ supports Java and other build tools like Maven, Gradle, Ant, Gant, SBT, NPM, Webpack, Grunt, and Gulp. Test runner and code coverage − IntelliJ IDEA lets you perform unit testing with ease. The IDE includes test runners and coverage tools for major test frameworks, including JUnit, TestNG, Spock, Cucumber, ScalaTest, spec2, and Karma. Test runner and code coverage − IntelliJ IDEA lets you perform unit testing with ease. The IDE includes test runners and coverage tools for major test frameworks, including JUnit, TestNG, Spock, Cucumber, ScalaTest, spec2, and Karma. Decompiler − IntelliJ comes with a built-in decompiler for Java classes. When you want to take a look inside a library that you do not have the source code for, you can do it without using any third-party plug-ins. Decompiler − IntelliJ comes with a built-in decompiler for Java classes. When you want to take a look inside a library that you do not have the source code for, you can do it without using any third-party plug-ins. Terminal − IntelliJ provides built-in terminal. Depending on your platform, you can work with the command line prompt, like PowerShell or Bash. Terminal − IntelliJ provides built-in terminal. Depending on your platform, you can work with the command line prompt, like PowerShell or Bash. Database tools − IntelliJ provides database tools, which allow you to connect to live databases; run queries; browse and update data; and even manage your schemas in a visual interface from IDE itself. Database tools − IntelliJ provides database tools, which allow you to connect to live databases; run queries; browse and update data; and even manage your schemas in a visual interface from IDE itself. Application server − IntelliJ supports major application servers: Tomcat, JBoss, WebSphere, WebLogic, Glassfish, and many others. You can deploy your artifacts onto application servers and debug the deployed applications in IDE itself. Application server − IntelliJ supports major application servers: Tomcat, JBoss, WebSphere, WebLogic, Glassfish, and many others. You can deploy your artifacts onto application servers and debug the deployed applications in IDE itself. Docker support − Via a separate plug-in, IntelliJ provides a dedicated tool window that lets you connect to locally running Docker machines. Docker support − Via a separate plug-in, IntelliJ provides a dedicated tool window that lets you connect to locally running Docker machines. The Ultimate Edition is designed to assist in web and enterprise development, whereas the Community Edition is designed for JVM and Android Development. Let us consider a few important points that will help us understand the comparison between the two editions − In this chapter, we will understand how to install and configure IntelliJ IDEA. The first step of the process starts with choosing the edition. As per your requirements, you can download community or ultimate edition. As name suggests, community edition is absolutely free and we can use it for commercial development as well. However, ultimate edition is paid version and we can evaluate it freely for 30 days. IntelliJ is compatible with almost all versions of Windows prior to 2003. A comprehensive list will be: Windows 10/8/7/Vista/2003/XP. It is recommended that you shut down all other applications before you install IntelliJ on Windows. A minimum 2 GB of RAM capacity is recommended for seamless performance. A minimum 2 GB of RAM capacity is recommended for seamless performance. For better visualization, 1024x768 screen resolution is recommended. For better visualization, 1024x768 screen resolution is recommended. Minimum 300 MB disk space for installation and additional 1 GB for cache. Minimum 300 MB disk space for installation and additional 1 GB for cache. Downloading − You can download windows installer from their official website. Downloading − You can download windows installer from their official website. Installation − Let us begin with the installation followed by the configuration steps. Installation of IntelliJ is similar to other software packages. Just double-click on the installer and follow the on-screen instructions to complete the installation process. Installation − Let us begin with the installation followed by the configuration steps. Installation of IntelliJ is similar to other software packages. Just double-click on the installer and follow the on-screen instructions to complete the installation process. For installation of IntelliJ on Linux platforms, you need to note that a 32-bit JDK is not bundled, so a 64-bit system is recommended. GNOME, KDE or XFCE desktop environment GNOME, KDE or XFCE desktop environment Minimum 2 GB of RAM is recommended for seamless usage Minimum 2 GB of RAM is recommended for seamless usage 300 MB of disk space for installation and addition 1 GB for caches 300 MB of disk space for installation and addition 1 GB for caches For better visualization, 1024x768 screen resolution is recommended For better visualization, 1024x768 screen resolution is recommended Downloading − You can download IntelliJ for Linux from their official website. Downloading − You can download IntelliJ for Linux from their official website. Installation − We have downloaded tar.gz bundle. Note that in our case bundle’s name was ideaIC-2017.2.5.tar.gz. It may change with the edition/version. Please use the appropriate bundle name. Installation − We have downloaded tar.gz bundle. Note that in our case bundle’s name was ideaIC-2017.2.5.tar.gz. It may change with the edition/version. Please use the appropriate bundle name. First extract it using following command: $ tar xvf ideaIC-2017.2.5.tar.gz It will create new directory with idea-IC-172.4343.14 name. Now change directory to idea-IC-172.4343.14/bin/ and execute idea.sh shell script as shown below: $ cd idea-IC-172.4343.14/bin/ $ ./idea.sh Follow on-screen instructions to complete installation procedure. The configuration steps are similar on both platforms. To begin configuration, launch IntelliJ application. Optionally, you can import the existing configuration from this wizard. Click on the next button to continue. Step1 − If you are using the ultimate edition, then a license activation window will pop-up. Select evaluate for free option and click on the evaluate button as shown in the following image. Step 2 − Accept the license agreement to proceed and follow on-screen instruction to start IntelliJ. You will see the Welcome screen of IntelliJ. Step 3 − Now, it is time to configure the Java Development Kit (hereafter, we will refer to it as JDK) with IntelliJ. If JDK is not installed already then follow the instruction as in here. On the Welcome screen, click on ‘configure’ On the Welcome screen, click on ‘configure’ Select ‘project defaults’ from the drop-down list Select ‘project defaults’ from the drop-down list Select the ‘project structure’ option Select the ‘project structure’ option Select the ‘SDKs’ option from the ‘platform settings’ menu. Select the ‘SDKs’ option from the ‘platform settings’ menu. Click on the ‘plus’ icon and select the ‘JDK’ option. Click on the ‘plus’ icon and select the ‘JDK’ option. Select JDK’s home directory and follow the on-screen instructions. Select JDK’s home directory and follow the on-screen instructions. In this chapter, we will get more familiar with IntelliJ IDEA. To discuss the advantages and functionality of any tool, one must be familiar with that tool and IntelliJ is no exception to that. This chapter gives you an overview of IntelliJ. The chapter begins with a discussion about IDE’s visual elements, configuration settings and finally ends by discussing JVM and platform properties. One of the important things about IDE is its visual elements. Identifying and understanding the visual elements enables to you do action in a quicker and easier manner. The following screenshot and the labels on it show the main interface of IntelliJ. Menu bar − The Menu bar provides options to create new projects and other important actions related to projects like code refactoring, builds, run, debug, version-controlling options and so on. Tool bar − The Tool bar provides shortcuts to compile, debug and run options. You can customize it according to your requirements. Navigation bar − The Navigation bar enables easier navigation within a project. This feature comes handy as code base increases. Tools tab − The Tools tab shows on either side of the main window. From here, you can access important tools like databases; Maven/Ant builds and so on. Project perspective − Project perspective window shows various elements of projects like packages, modules, classes, external libraries and so on. Editor window − This is a place where developer spends most of his/her time. Editor window allows you edit/write code with syntax highlighting and other useful features. Menu bar − The Menu bar provides options to create new projects and other important actions related to projects like code refactoring, builds, run, debug, version-controlling options and so on. Menu bar − The Menu bar provides options to create new projects and other important actions related to projects like code refactoring, builds, run, debug, version-controlling options and so on. Tool bar − The Tool bar provides shortcuts to compile, debug and run options. You can customize it according to your requirements. Tool bar − The Tool bar provides shortcuts to compile, debug and run options. You can customize it according to your requirements. Navigation bar − The Navigation bar enables easier navigation within a project. This feature comes handy as code base increases. Navigation bar − The Navigation bar enables easier navigation within a project. This feature comes handy as code base increases. Tools tab − The Tools tab shows on either side of the main window. From here, you can access important tools like databases; Maven/Ant builds and so on. Tools tab − The Tools tab shows on either side of the main window. From here, you can access important tools like databases; Maven/Ant builds and so on. Project perspective − Project perspective window shows various elements of projects like packages, modules, classes, external libraries and so on. Project perspective − Project perspective window shows various elements of projects like packages, modules, classes, external libraries and so on. Editor window − This is a place where developer spends most of his/her time. Editor window allows you edit/write code with syntax highlighting and other useful features. Editor window − This is a place where developer spends most of his/her time. Editor window allows you edit/write code with syntax highlighting and other useful features. At the bottom of the main window, there is a status bar, which shows some additional attributes about the file - like its format and the encoding type. It also provides option to toggle the read-only attribute of the current file. You can also manage inspection level from here. Plug-ins help to extend functionality of IntelliJ. It provides a large number of plug-ins ranging from databases, version controlling, profiling and this list goes on. Follow these steps to manage plug-ins − Go to the File → Settings menu. Go to the File → Settings menu. Select the Plugins tab on the left pane. Select the Plugins tab on the left pane. This window lists all installed plug-ins. There is a checkbox on the right side of each plug-in name. Toggling that checkbox enables/disables the plug-ins. This window lists all installed plug-ins. There is a checkbox on the right side of each plug-in name. Toggling that checkbox enables/disables the plug-ins. IntelliJ online plug-in repository is available here. To add/remove plug-in repository, click on the browse repository button and it will provide a way to do needful. IntelliJ online plug-in repository is available here. To add/remove plug-in repository, click on the browse repository button and it will provide a way to do needful. In addition to this, it allows offline plug-in installation. For this, download plug-in and select install plug-in from the disk button and navigate to the download path. In addition to this, it allows offline plug-in installation. For this, download plug-in and select install plug-in from the disk button and navigate to the download path. To perform other actions on plug-ins like uninstalling, updating and sorting, right-click on any plug-in. It will show a dropdown menu from which you can select one of the actions. This section provides a few important tips to manage settings. It enables you to import, export and share IntelliJ settings. It allows exporting the current settings as a jar file. Go to File → Export Settings. Go to File → Export Settings. Export setting windows list the available settings related to UI, debugger, SDK along with others. Export setting windows list the available settings related to UI, debugger, SDK along with others. It provides a checkbox for selection. Once the selection is done, click on the OK button to save the settings on the local disk. It provides a checkbox for selection. Once the selection is done, click on the OK button to save the settings on the local disk. It allows importing the settings stored in the jar file. Go to File → Import settings. Select the Setting jar by navigating folder structure Click on the OK button. IntelliJ IDEA allows you to share your IDE settings between different instances. This is particularly useful when you want to apply the same settings within a team or organization. The prerequisite for this is to enable the Settings Repository plug-in. It is installed and enabled by default. To ensure its status − Go to File → Settings → Plugins Search settings repository plug-in We can store the current setting on GitHub/Bitbucket and apply them on other instances. To store the current setting − Go to the File → Settings Repository. Go to the File → Settings Repository. Type the Git repository URL in upstream URL dialog box. Type the Git repository URL in upstream URL dialog box. Click on the Overwrite remote button. Click on the Overwrite remote button. To apply the same settings to other instances, click on the Overwrite local button. To apply the same settings to other instances, click on the Overwrite local button. We can configure the JVM options by navigating to the Help → Edit Custom VM Options menu. Following are a few important JVM options we can set. –server − It allows the selection of the Java HotSpot Server VM –server − It allows the selection of the Java HotSpot Server VM -Xms<size> − It sets the initial Java heap size. The default value is 128 MB. -Xms<size> − It sets the initial Java heap size. The default value is 128 MB. -Xmx<size> − It sets the maximum Java heap size. The default value is 750 MB. -Xmx<size> − It sets the maximum Java heap size. The default value is 750 MB. -Xss<size> − It sets the Java thread stack size. -Xss<size> − It sets the Java thread stack size. –XX − It allows setting GC algorithm and other properties. –XX − It allows setting GC algorithm and other properties. It is time we got a hands-on experience with IntelliJ. In this chapter, we will create our first Java Project. We will write and execute the traditional Hello World program. This chapter explains the compilation and running of Java application. For anything related to development, a developer has to create a new project with IntelliJ. Let us follow these steps to create a project − Launch IntelliJ. Launch IntelliJ. Go to File → New → Project menu. Go to File → New → Project menu. Select the Java project and appropriate SDK and click on the Next button. Select the Java project and appropriate SDK and click on the Next button. If you want to create a Java class with the main method, then select Create Project from the template checkbox. If you want to create a Java class with the main method, then select Create Project from the template checkbox. Select the command line app from the dialog box shown below and continue. Select the command line app from the dialog box shown below and continue. Enter the project name and the directory location. Enter the project name and the directory location. Click on the Finish button. Click on the Finish button. A package is created under Java project and can be created separately, or at the same time of creating a class. Let us follow these steps to create a package − Go to the project perspective. Go to the project perspective. Right-click on Project, select the New->Module option. Right-click on Project, select the New->Module option. The new module window will be similar to the new project. Select the Java option and appropriate SDK and click on the Next button. The new module window will be similar to the new project. Select the Java option and appropriate SDK and click on the Next button. Enter the module name. Enter the module name. Click on the Finish button. Click on the Finish button. In this section, we will learn how to create a Java class. A Java class can be created under a Java module. Follow these steps to create a module − Go to the Project perspective. Go to the Project perspective. Expand Project and select the src directory from the module. Expand Project and select the src directory from the module. Right click on it; select the New->Java Class option. Right click on it; select the New->Java Class option. Enter the class name in the dialog-box and click on the OK button. Enter the class name in the dialog-box and click on the OK button. It will open the Editor window with the class declaration. It will open the Editor window with the class declaration. We will now see how to run a Java application. Follow these steps and see how it runs − Let us write a simple code, which will print a message on the console. Enter the following code in the Editor window − Let us write a simple code, which will print a message on the console. Enter the following code in the Editor window − public class HelloWorld { public static void main(String[] args) { System.out.println("Hello, World !!!"); } } Go to the Run menu and select the Run option. Go to the Run menu and select the Run option. Select the Class name and click on Run. Select the Class name and click on Run. If there are no compilation errors, then it will show output at the bottom of the window. If there are no compilation errors, then it will show output at the bottom of the window. The first four chapters of this tutorial were designed to give beginners a basic-level overview of IntelliJ. This section dives deep into IntelliJ and discusses more about projects, its format along with other things. A project is an application or software on which you are working. It can contain multiple modules, classes, libraries, configuration, and so on. It is the topmost element in the hierarchy. Modules feature one rung below ‘Project’. A module is a separate entity that can be compiled, debugged and run independently of other modules. A single project can contain multiple modules. You may add or remove modules from a project any time. In addition to this, we can also import the existing modules. Follow these steps to import the existing modules − Go to File → Project structure. Select modules and click on plus icon. It will show the option to import module. Content root is a folder that contains all the files that make up your module. A module can have more than one content folder. Folders are categorized into the following types − Sources − By assigning this category to folder, we instruct IntelliJ that this and its subfolder contain java source code and it should be compiled as part of the compilation process. Sources − By assigning this category to folder, we instruct IntelliJ that this and its subfolder contain java source code and it should be compiled as part of the compilation process. Tests − By assigning this category to folder, we instruct IntelliJ that it is the location for unit tests. This folder can access classes from the Sources folder. Tests − By assigning this category to folder, we instruct IntelliJ that it is the location for unit tests. This folder can access classes from the Sources folder. Resources − It represents various resource files used in project, for instance, images, XML and properties files. During the compilation process, contents of this folder is copied as is to the output folder. Resources − It represents various resource files used in project, for instance, images, XML and properties files. During the compilation process, contents of this folder is copied as is to the output folder. Excluded − Contents from the excluded folder will not be indexed by IntelliJ. This means that IntelliJ will not provide the code completion suggestion and other hints. For example, the output directory and the target directory are excluded by default. Excluded − Contents from the excluded folder will not be indexed by IntelliJ. This means that IntelliJ will not provide the code completion suggestion and other hints. For example, the output directory and the target directory are excluded by default. Test resources − This is similar to the resources and used for unit tests. Test resources − This is similar to the resources and used for unit tests. Library is a compilation of different classes. Library enables code reusability. In Java, library can be enclosed in ZIP, Jar or simply folder. We can define libraries at three different levels. The levels are - global, project and module level. Global level − Shared by all projects. Global level − Shared by all projects. Project level − Shared by all the modules of project. Project level − Shared by all the modules of project. Module level − Shared by the classes of those modules. Module level − Shared by the classes of those modules. Facets are the extensions to the modules. They add support to the frameworks and technologies. When a facet is added to a module, IntelliJ identifies it adds support. For instance, hints and help in editor, new tools in window bar, dependency downloading and so on. You can add facets from the File → Project Structure window as shown below − Artifacts are the output of a project. It can be a simple JAR file, Java EE application, or Java EJB application. If we are using external build tools like Gradle or Maven, then IntelliJ will add artifact for them automatically. Artifacts can be created by navigating to the File → Project Structure as shown below − In this section, we will understand how to import an existing project. We can import a project in two ways − Import it from existing source Import it from the build model. At present, it supports Gradle and Maven build tools. To import project − Navigating to File → New → Project from the existing source. Select directory of the existing project, Maven’s pom.xml or Gradle’s build script. Click on the OK button. IntelliJ supports two types of project format one is directory-based and other is file-based. Directory based format is newer one it is recommended. By default, IntelliJ creates directory based project format. You can select project format while creating new project. On new project window just click on more settings as show in below image − This format helps create an idea folder in your project and keep all configuration files inside that folder. Settings are grouped into the xml files. For instance, it will create misc.xml, modules.xml, workspace.xml and so on. The following screenshot will help you understand how this works − It will create two project files with ..ipr and wpr extensions. The ipr file will contain project-specific settings and the wpr file will contain workspace-specific settings. To convert a file-based project to a directory-based project, go to the File → Save as a Directory-Based format. Compared to the file-based project format, the directory-based project format stores settings in a separate folder with meaningful names. Other differences are − Related settings getting stored in a single file makes it easier to manage in directory-based project format. Related settings getting stored in a single file makes it easier to manage in directory-based project format. If folder contains the idea subfolder then IntelliJ recognizes that project. Because of this, you don’t have select the ipr project explicitly. If folder contains the idea subfolder then IntelliJ recognizes that project. Because of this, you don’t have select the ipr project explicitly. Directory-based project format breaks settings into multiple files hence it is easier to select particular type of setting to store in version control system. Directory-based project format breaks settings into multiple files hence it is easier to select particular type of setting to store in version control system. Editor is that area where a developer spends most of his/her time. Mastering the editor is the first step at improving the productivity of any resource. This chapter discusses visual elements of editor, the most common editor actions and SonarLint plug-in, which provides lint checking. IntelliJ has many provisions that include visual elements designed to assist developers in navigating through and understanding the real status of their coding. Let us now go through the different provision − Editor’s gutter area is located on the left side of IDE as shown in the following image − We will now understand how the labels work. The above screenshot is marked in numbers. We will now see what the numbers have to show − Here we can see line numbers along with other useful options. If you observe carefully just before class name and main method there is a small green triangle. It provides option to run, debug and run application with coverage. Just click on the triangle icon and it will provide options. Here we can see line numbers along with other useful options. If you observe carefully just before class name and main method there is a small green triangle. It provides option to run, debug and run application with coverage. Just click on the triangle icon and it will provide options. You can see the small plus symbol at line number 6. This is the code folding functionality. If you click on that icon, then it will unfold it. Code folding can be done at class, method, loop and other block levels. You can see the small plus symbol at line number 6. This is the code folding functionality. If you click on that icon, then it will unfold it. Code folding can be done at class, method, loop and other block levels. At line numbers 11 and 14, there are 2 arrows which point towards each other. The marker represents the method’s start and end position. If you click on any arrow, then it will perform the fold action on that code block. The Gutter area will show various symbols when certain actions are taken; for instance, it will show symbols for breakpoints, Java annotations. At line numbers 11 and 14, there are 2 arrows which point towards each other. The marker represents the method’s start and end position. If you click on any arrow, then it will perform the fold action on that code block. The Gutter area will show various symbols when certain actions are taken; for instance, it will show symbols for breakpoints, Java annotations. At the bottom of the Editor window, there is a status bar, which shows information about the current file and the project status. In the first image, 16:1 represents the current line number and the column number respectively. In the first image, 16:1 represents the current line number and the column number respectively. Next is the line separator, for UNIX and mac OS it’s \n and for windows it’s \r. Next is the line separator, for UNIX and mac OS it’s \n and for windows it’s \r. UTF-8 represents the file encoding. UTF-8 represents the file encoding. Next is the lock icon. We can toggle file’s read-only attribute by clicking on it. Next is the lock icon. We can toggle file’s read-only attribute by clicking on it. At the end, there is a symbol with a man’s face. It allows managing the code inspection level. When we type code in Editor, IntelliJ inspects code on the fly and shows hints/suggestion. We can decide the inspection level from here. For instance, we can completely disable it or allow inspection only for syntax and so on. We can also enable the Power Save mode from here, which will disable background code analysis and other background jobs. At the end, there is a symbol with a man’s face. It allows managing the code inspection level. When we type code in Editor, IntelliJ inspects code on the fly and shows hints/suggestion. We can decide the inspection level from here. For instance, we can completely disable it or allow inspection only for syntax and so on. When we type code in Editor, IntelliJ inspects code on the fly and shows hints/suggestion. We can decide the inspection level from here. For instance, we can completely disable it or allow inspection only for syntax and so on. We can also enable the Power Save mode from here, which will disable background code analysis and other background jobs. We can also enable the Power Save mode from here, which will disable background code analysis and other background jobs. The Status bar also shows information about project actions. For instance, second image show information about project compilation. The Status bar also shows information about project actions. For instance, second image show information about project compilation. IntelliJ provides a temporary Editor. You can create text or piece of code without modifying the current project structure. It provides two types of temporary files − They are functional, run-able and debug-able. To create a scratch file − Go to File → New → Scratch file. Go to File → New → Scratch file. Select the language of your choice. Select the language of your choice. It will create a file in the IntelliJ-Installation-Directory\ config \scratches folder. It will create a file in the IntelliJ-Installation-Directory\ config \scratches folder. This is used only for creating any text. To create a scratch buffer − Press Ctrl + Shift + A or click on Search Everywhere icon Press Ctrl + Shift + A or click on Search Everywhere icon It will pop up dialog box. It will pop up dialog box. Enter new scratch buffer text in that box and press enter. Enter new scratch buffer text in that box and press enter. It’ll open scratch buffer in editor window. It’ll open scratch buffer in editor window. Like the scratch files, scratch buffers are also stored in the IntelliJ-Installation-Directory\config\scratches folder. Scrollbar highlights warnings/error messages/TODO markers from the code. For instance, the sayHello() and sayGoodBye() method is never used; hence, the scrollbar shows yellow marker for them. At line number 8, there is the TODO comment, scrollbar highlights it using the blue marker. Errors are highlighted using red marker. In this section, we will discuss the Editor actions in IntelliJ. To search text in the current file − Navigate to the file in the Editor window and press Ctrl+F. Navigate to the file in the Editor window and press Ctrl+F. It will show text box, type text to be searched there. It will show text box, type text to be searched there. You can provide various options here - case sensitive match, exact match, regular expression and so on. You can provide various options here - case sensitive match, exact match, regular expression and so on. You can perform the search operation at a very granular level. For instance, search can be done at project, module or directory level − Press the Ctrl+Shift+F key combination. Press the Ctrl+Shift+F key combination. A new window will appear; from here, you can select the appropriate level. A new window will appear; from here, you can select the appropriate level. To perform a replace action in the current file − Press the Ctrl+R key combination. Press the Ctrl+R key combination. A dialog box will appear, enter the text to be replaced here. A dialog box will appear, enter the text to be replaced here. This operation allows you to replace single match, all matches or skip current match. This operation allows you to replace single match, all matches or skip current match. To perform the replace action at a granular level − Press the Shift+Ctrl+R key combination. Press the Shift+Ctrl+R key combination. It will allow you replace text at project, module, directory and other scopes. It will allow you replace text at project, module, directory and other scopes. To enable the column mode selection, hold the Alt key while selecting the text. To enable the column selection mode on a permanent basis, select Edit → Column selection mode. When we copy any text, it goes to the clipboard history. IntelliJ maintains the clipboard history. To view this history, pressthe Ctrl+Shift+V key combination. You can select the content to paste from this window. IntelliJ inspects the code on the fly and provides accurate code completion. For instance, when I type the word say - it suggests sayHello() and sayGoodBye() methods. Code completion suggests class attributes and class methods while working with the class objects. IntelliJ provides a way to generate useful code like constructor, getter, setter, toString() method, override methods and so on. Follow these steps to generate right-click in the Editor window. Select the Generate option. Select the Generate option. It will list the methods for which code can be can generated. It will list the methods for which code can be can generated. We have already seen that IntelliJ identifies syntax errors, warning messages and TODO markers. In addition to this, it suggests code improvement, identifies dead code, code optimization. For instance, in the code given below, the value of flag is always true. Hence, the else part will never be executed. boolean flag = true; if (flag == true) { System.out.println("Value of flag is true"); } else { System.out.println("Value of flag is false"); } IntelliJ identifies this and suggests removing this code block. Follow these steps to compare files and folders − Hold the Ctrl key and select files to be compared from the project perspective. Hold the Ctrl key and select files to be compared from the project perspective. Right-click on it and select the Compare Files option. Right-click on it and select the Compare Files option. It will open the Compare window where the changes are highlighted. It will open the Compare window where the changes are highlighted. You can also apply the changes from one file to another. If you observe, there are two arrow markers highlighted in red color. Click on them to apply changes from other file. Press Ctrl+Z to undo the changes. Similarly, to compare the folders, select folders from project perspective instead of files. It is useful if you get details about code easily. Like the method description, its return type, arguments type and number of arguments - IntelliJ can provide these details in the Editor window itself. As the name suggests, IntelliJ can access documentation by extracting it from the code. If you provide Java Docs for your code, then IntelliJ can show help about it. To access inline documentation, hover click on method name and press the Ctrl+Q key combination. To view definition, hover the mouse over method name and press the Ctrl+Shift+I key combination. To view method usage, click on method declaration/definition and press the Alt+Ctrl+F7 key combination. To view the method parameters, type method name and press the Ctrl+P key combination. Linting is a process in which the lint tool analyzes the source codes and reports potential issues related to the coding standard. It helps in improving the code quality. IntelliJ supports SonarLint plug-in which lints the code. Once you install and enable the SonarLint plug-in, it will start analyzing the code automatically when you open a file in the Editor window. It will report issues in the SonarLint panel. We will discuss more about it in this section. SonarLint supports popular programming languages like Java, JavaScript, PHP and Python. Follow these steps to install SonarLint − Download SonarLint from here. Download SonarLint from here. Go to File → Settings → Select plugins. Go to File → Settings → Select plugins. Click on the Install plugin from disk button. Click on the Install plugin from disk button. Follow on-screen installation to complete the installation procedure. Follow on-screen installation to complete the installation procedure. Once the plug-in is installed and enabled, it will start analyzing code on the fly. It will report issues in the SonarLint panel. Follow these steps to view issues of the current file − Click on the Current file tab. Click on the Current file tab. It will report issues like unused local variables, unused class attributes, message logging and so on. It will report issues like unused local variables, unused class attributes, message logging and so on. To know more about issue, click on issue from SolarLint panel. To know more about issue, click on issue from SolarLint panel. In the right side of the window, it will show its severity as Major, Minor and so on. In the right side of the window, it will show its severity as Major, Minor and so on. If you are not comfortable with on-the-fly code analysis, then you can disable it and perform one time code analysis once you are ready with code. Follow these steps to disable on-the-fly code analysis − Go to File → Settings → Other Setting → SonarLint General Settings Go to File → Settings → Other Setting → SonarLint General Settings Uncheck Automatically Trigger Analysis checkbox from the settings tab. Uncheck Automatically Trigger Analysis checkbox from the settings tab. Click on Apply followed by Ok button. Click on Apply followed by Ok button. In this chapter, we will learn about Code Refactoring and how it works in IntelliJ. Code refactoring is restructuring of code without changing its functionality and usability. Code refactoring can be done to improve code readability, performance or to remove unused/duplicate functionality. IntelliJ provides great support for code refactoring. This chapter discusses various code refactoring actions. Rename actions can be used to rename methods, its parameters, class attributes, local variables and so on. Let us create the following class in IntelliJ. public class Employee { private String name; private String address; private int age; public Employee() { this("Jarvis", "Palo Alto", 35); } public Employee(String name, String address, int age) { this.name = name; this.address = address; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "Employee{" + "name='" + name + '\'' + ", address='" + address + '\'' + ", age=" + age + '}'; } public static void main(String args[]) { Employee e = new Employee(); System.out.println(e); } } Now, let us rename Employee class to Person. This action will do modifications in constructors and the main() method − Select Employee word Select Employee word Go to Refactor → Rename and rename it with Person. Go to Refactor → Rename and rename it with Person. This is one of the powerful refactoring actions. IntelliJ identifies code duplicates and replaces it with appropriate code. Let us introduce code duplication and refactor it. Type the following code in the Editor − public class Employee { private String name; private String address; private int age; public Employee() { this("Jarvis", "Palo Alto", 35); } public Employee(String name, String address, int age) { this.name = name; this.address = address; this.age = age; } public void setData(String name, String address, int age) { this.name = name; this.address = address; this.age = age; } public void showEmployeeDetail() { System.out.println("Name = " + name + ", Address = " + address + ", Age = " + age); } public static void main(String args[]) { Employee e = new Employee(); e.showEmployeeDetail(); } } In this example, Employee(String name, String address, int age) constructor and public void setData(String name, String address, int age) method are exactly identical. After refactoring, the Employee(String name, String address, int age) constructor gets modified as follows − public Employee(String name, String address, int age) { setData(name, address, age); } To replace the duplicates − Go to Refactor → Find and Replace Code Duplicates. Go to Refactor → Find and Replace Code Duplicates. Select refactor scope and follow on-screen steps to complete action. Select refactor scope and follow on-screen steps to complete action. In this section, we will understand how to copy one class to another. Let us copy Employee class to Person class. We can copy it to the existing module or a new one. IntelliJ will do the required changes depending on it. Follow these steps to perform copy refactoring − Go to Refactor → Copy, it will open the dialog box. Go to Refactor → Copy, it will open the dialog box. Enter new name and destination package. Enter new name and destination package. Click on the OK button and it will do the needful. Click on the OK button and it will do the needful. Move refactoring is similar to copy but instead of making another copy it moves the code to a different package or make it as inner class of another class. Follow these steps to perform move refactoring − Go to, Refactor → Move. Go to, Refactor → Move. A new window will appear. A new window will appear. Select one of the options according to your choice and click on Refactor. Select one of the options according to your choice and click on Refactor. The Safe Delete action will delete object only when it is not referenced anywhere in the project. The target for this option can be class, interface, method, field or parameter. Let us see this in action. Type the following code in Editor − public class HelloWorld { static void sayHello() { System.out.println("Hello, World !!!"); } public static void main(String[] args) { sayHello(); } } Follow these steps to perform the safe delete action − Select the sayHello() method. Select the sayHello() method. Right-click on it and select the Refactor → Safe Delete option. Right-click on it and select the Refactor → Safe Delete option. As the sayHello() method is being used it will show an error as in the following screenshot − As the sayHello() method is being used it will show an error as in the following screenshot − The action modifies method signature. It can change the method name, its parameters, types, return values and so on. Let us take a method from the above example and change its signature. Follow these steps to perform the Change Signature action − Select method. Select method. Right-click on it and select the Refactor → Change signature action Right-click on it and select the Refactor → Change signature action A new window will appear wherein you can perform the above actions. A new window will appear wherein you can perform the above actions. At the bottom of the window, it shows the preview of new signature. At the bottom of the window, it shows the preview of new signature. The Type Migration changes the type of the symbol. This symbol can be a method parameter or class attribute. Let us consider the following method before performing the required action − static void sayHello(String name) { System.out.println(name); } Follow these steps to perform type migration − Select the “String” data type. Select the “String” data type. Right-click on it and select Refactor → Type migration. Right-click on it and select Refactor → Type migration. Enter the required data type in the given text box. Enter the required data type in the given text box. Choose scope and click on the Refactor button. Choose scope and click on the Refactor button. IntelliJ provides multiple ways to create configuration. This chapter discusses the options to create temporary, permanent configuration. It also discusses method to share configuration among other users. Temporary configuration is created when you run or debug Java class or test case. Consider the following steps to understand how this works − Create a Java class. Right-click on it and select the Run option. After the first Run, temporary configuration is added to the run menu. Temporary configuration can be converted to permanent configuration by saving it with IntelliJ. To save configuration, click on the Save Configuration option from the Run menu − You can also modify the existing configuration by editing it. In this section, we will understand how to create new configuration. Follow these steps to create new configuration − Navigate to the Run → Edit Configuration. Navigate to the Run → Edit Configuration. Click on the Plus button to add new configuration. Click on the Plus button to add new configuration. Select Application from the dropdown list. Select Application from the dropdown list. It will create un-named configuration. It will create un-named configuration. Configure it according to your requirements and click on the OK button. Configure it according to your requirements and click on the OK button. This saved configuration will be accessible from the Run menu along with other configurations. This saved configuration will be accessible from the Run menu along with other configurations. Follow these steps to share configuration with others − Navigate to the Run → Edit Configuration. Navigate to the Run → Edit Configuration. Select configuration from the left pane and click on the Share checkbox. Select configuration from the left pane and click on the Share checkbox. It will store configuration on disk. It will store configuration on disk. If directory based format is used, it will save configuration in separate file under runConfiguration folder. Otherwise, it will store configuration in the .ipr file. To run project with specific configuration − Select configuration from the Run menu. Select configuration from the Run menu. Run the project as shown in the following screenshot − Run the project as shown in the following screenshot − IntelliJ provides a way to build and package Java package. It supports external build tools like Maven and Gradle. This chapter discusses about these build tools. Follow these steps to create a Maven project − Navigate to File → Project. Navigate to File → Project. Select Maven option and click on Next button. Select Maven option and click on Next button. In the new project window enter tutorialspoint.com as GroupId and HelloWorld as ArtifactId. In the new project window enter tutorialspoint.com as GroupId and HelloWorld as ArtifactId. In the New window, it will open the pom.xml file. In the New window, it will open the pom.xml file. We need to add properties to this file; the final pom.xml file should look like this − We need to add properties to this file; the final pom.xml file should look like this − <?xml version = "1.0" encoding = "UTF-8"?> <project xmlns = "http://maven.apache.org/POM/4.0.0" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.tutorialspoing</groupId> <artifactId>HelloWorld</artifactId> <version>1.0-SNAPSHOT</version> <properties> <maven.compiler.source>1.7</maven.compiler.source> <maven.compiler.target>1.7</maven.compiler.target> </properties> </project> Now, let us create a Java class inside the src/main/java directory of the Maven project. Follow these steps to create the class − Navigate to the src/main/java directory. Navigate to the src/main/java directory. Right click on it and select New → Java Class. Right click on it and select New → Java Class. Follow these steps to compile this class using Maven − Navigate to Run → Edit Configuration. Navigate to Run → Edit Configuration. Click on the green plus icon and select the Maven option from the dropdown menu. Click on the green plus icon and select the Maven option from the dropdown menu. Enter the project name as Maven-Package. Enter the project name as Maven-Package. Provide package as the command line. Provide package as the command line. Click on the OK button. Click on the OK button. Navigate to Run and select the Maven-Package option. Navigate to Run and select the Maven-Package option. It will start building package. Upon successful building of the package, you will see the following result − It will start building package. Upon successful building of the package, you will see the following result − In this section, we will learn how to create a Gradle project − Navigate to File → Project and select Gradle. Navigate to File → Project and select Gradle. Click on the Next button. Click on the Next button. In the new project window, enter tutorialspoint as GroupId and HelloWorld as ArtifactId. In the new project window, enter tutorialspoint as GroupId and HelloWorld as ArtifactId. Click on the Next button, verify the project details and click on the Finish button. Click on the Next button, verify the project details and click on the Finish button. Follow the on-screen instructions to complete the process. Follow the on-screen instructions to complete the process. Open the buildl.gradle file and write Hello task as shown in the above screenshot. Open the buildl.gradle file and write Hello task as shown in the above screenshot. To compile this task, navigate to the Run → Build-Gradle option. To compile this task, navigate to the Run → Build-Gradle option. Unit testing plays an important role in software development. IntelliJ supports various unit testing frameworks like JUnit, TestNG, Spock and many more. In this chapter, we are going to use JUnit3. In this section, we will learn how to create a Unit Test. Follow these steps to create the test − Select the Navigate → Test option. Select the Navigate → Test option. A dialog box will appear wherein, you have to select Create New Test. A dialog box will appear wherein, you have to select Create New Test. Follow the on-screen instructions to continue − Follow the on-screen instructions to continue − Provide the details about the test like testing library, class details, setUp, tearDown methods and so on. Provide the details about the test like testing library, class details, setUp, tearDown methods and so on. Click on the OK button to continue. Click on the OK button to continue. A test class will be created. Initially it may fail to resolve some symbols. Navigate the cursor to the error line, it will show the hint symbol. A test class will be created. Initially it may fail to resolve some symbols. Navigate the cursor to the error line, it will show the hint symbol. Select the appropriate option from the dropdown menu. We have selected the Add library ‘junit.jar!’ to classpath option − Select the appropriate option from the dropdown menu. We have selected the Add library ‘junit.jar!’ to classpath option − You can add logic inside each test according to your business requirement. I have kept it empty for simplicity. Follow these steps to run unit test − Select unit test class from the Editor window. Select unit test class from the Editor window. Navigate to the Run menu and select the Run option. Navigate to the Run menu and select the Run option. The following result will be generated The following result will be generated Debugger makes application debugging much easier. Using debugger, we can stop the execution of program at a certain point, inspect variables, step into function and do many things. IntelliJ provides inbuilt Java debugger. Breakpoint allows stopping program execution at certain point. Breakpoints can be set by hovering the mouse over the Editor’s gutter area and clicking on it. Breakpoints are denoted using red circle symbols. Consider the breakpoint set at line 3. Consider the following steps to understand more on how the breakpoints work − Right-click on the red circle symbol. Right-click on the red circle symbol. Select the More options. Select the More options. To remove breakpoint just click on same symbol. To remove breakpoint just click on same symbol. Follow these steps to start the debugger − Navigate to the Run menu. Select the Debug option. While debugging, if a function is encountered and a step into action is selected, then debugger will stop program execution at each point of that function as if debugging is enabled for that function. For instance, when program execution reaches at line 9 and if we select the step into action then it stops the execution at each line in the sayGoodBye() function. The Step out action is exactly the reverse of Step in action. For instance, if you perform the step out action with the above scenario then debugger will return from the sayGoodBye() method and start execution at line 10. The Step over action does not enter into function instead, it will jump to the next line of code. For instance, if you are at line 9 and execute the step over action then it will move execution to line 10. The Resume Program action will continue execution of program by ignoring all breakpoints. The Stop action helps stop the debugger. While debugging, we may sometimes reach a line of code that calls several methods. When debugging these lines of code, the debugger typically allows us to use step into and leads us through all child functions and then back to the parent function. However, what if we only wanted to step into one child function? With Smart step-into, it allows us to choose the function to step into. Now, let us create a Java class with the following line of code − public class HelloWorld { public static void main(String[] args) { allFunctions(); } static void allFunctions() { System.out.println(function1() + " " + function2() + " " + function3()); } static String function1() { return "function1"; } static String function2() { return "function2"; } static String function3() { return "function3"; } } In the above code, allFunctions() calls 3 more functions. Let us set the breakpoint at this function. Follow these steps to perform smart step into − Go to run Select smart step into. Select the child function to go. During debugging, IntelliJ shows value of variable in the Editor window itself. We can also view the same information in the Debug window. Evaluate expression allows to evaluate expression on the fly. Follow these steps to perform this action − Start application in debugger Start application in debugger Navigate to Run->Evaluate expression. Navigate to Run->Evaluate expression. Enter expression. In the example given below, the current value of variable ‘i’ is 0; hence, expression ‘i > 100’ will evaluate to false Enter expression. In the example given below, the current value of variable ‘i’ is 0; hence, expression ‘i > 100’ will evaluate to false Profiler gives insights about your application like its CPU, memory and heap usage. It also gives details about the application threads. This chapter discusses the usage of VisualVM tool for Java application profiling. It can profile entities such as CPU and heap. It is recommended that the readers of this tutorial are familiar with the application profiler concepts. VisualVM is a visual tool that integrates JDK tools and gives you powerful profiling capabilities. It allows you to generate and analyze heap data, track down memory leaks,monitor the garbage collector and perform memory and CPU profiling. Visual interface for local and remote Java applications running on JVM. Visual interface for local and remote Java applications running on JVM. Monitoring of application’s memory usage and application’s runtime behavior. Monitoring of application’s memory usage and application’s runtime behavior. Monitoring of application threads Monitoring of application threads Analyzing the memory allocations to different applications. Analyzing the memory allocations to different applications. Thread dumps − very handy in case of deadlocks and race conditions. Thread dumps − very handy in case of deadlocks and race conditions. Heap dumps − very handy in analyzing the heap memory allocation. Heap dumps − very handy in analyzing the heap memory allocation. In this section, we will learn the steps performed to configure VisualVM. The steps are as follow − Download it from here. Download it from here. Extract the zip file. Extract the zip file. Navigate to etc/visualvm.conf file and add the following line in this file − Navigate to etc/visualvm.conf file and add the following line in this file − visualvm_jdkhome=<path of JDK> If your JDK is installed in the C:\Program Files\Java\jdk-9.0.1 directory then it should look like this − If your JDK is installed in the C:\Program Files\Java\jdk-9.0.1 directory then it should look like this − visualvm_jdkhome="C:\Program Files\Java\jdk-9.0.1" Let us now see how to monitor the application. Consider the following steps to understand the same − Double-click on the visualvm.exe file. Select the application from left pane. Select the monitor tab. You will be directed to a window where you will get the details about CPU, Heap, Classes and threads. To be specific with the usage, hover the mouse over any graph. We can see the usage of Heap in the above screenshot. Java application can contain multiple threads of execution. To know more about threads, select the Threads tab of a particular application. It will give various statistics about threads like number of live threads and daemon threads. The different thread states are Running, Sleeping, Waiting, Park and Monitor. VisualVM supports CPU, memory sampling and memory leak detection. To sample application, select application and choose the sample tab − For CPU sampling, click on the CPU button as show in the following screenshot − For memory profiling, click on the Memory button as shown in the following screenshot − A memory leak occurs when an application, while running, slowly fills up the heap with objects that are not automatically deleted by the program. If an object that is not used by the program is not deleted, then it remains in memory and the GC cannot reclaim its space. If the number of bytes and number of instances in your application were to increase constantly and significantly in your program to the point of using up all the space, this can be an indication of a memory leak. In this section, we will learn how to profile an application. To profile an application, select application from left pane and click the profile tab − To perform CPU profiling, click on the CPU button as shown in the screenshot below − To perform CPU profiling, click on the CPU button as shown in the screenshot below − IntelliJ supports various version control systems like Git, Subversion, Mercurial, CVS, GitHub and TFS. You can perform version control related action from the IDE itself. In this chapter, we will discuss Git and Subversion (hereafter referred to as SVN). We assume that the reader is familiar with Git and SVN tool and its terminology. In this section, we will learn how to work with Git. To clone an existing Git repository − Navigate to File->New->Project from Version Control->Git. Navigate to File->New->Project from Version Control->Git. Enter the repository URL, Parent directory and Directory name. Enter the repository URL, Parent directory and Directory name. Click on the clone button to continue. Click on the clone button to continue. Upon successful running of the above steps, the repository will get cloned. Upon successful running of the above steps, the repository will get cloned. Git will track the changes that you make in repository. Let us modify any file from the repository and compare it with the repository. Navigate to VCS → Git → Compare with Latest Repository Version. Navigate to VCS → Git → Compare with Latest Repository Version. The above step will open the diff window. The above step will open the diff window. You can see there is a new line on the right side with green background colour. You can see there is a new line on the right side with green background colour. Git shows it in green as we have added new contents. If we remove any contents then it’ll be shown in red colour Git shows it in green as we have added new contents. If we remove any contents then it’ll be shown in red colour Follow these steps to discard the local changes − Navigate to the VCS → Git → Revert option. Navigate to the VCS → Git → Revert option. It will ask for confirmation and remove your changes. It will ask for confirmation and remove your changes. To add file to repository navigate to VCS → Git → Add option. This action is similar to the git add action. The Commit operation will create local commit. It is similar to the git commit action. To perform commit − Navigate to the VCS → Git → Commit File option. Navigate to the VCS → Git → Commit File option. Select files to be committed. Select files to be committed. Enter commit message and click on Commit button. Enter commit message and click on Commit button. The Push action will send local changes to the remote repository. To push changes − Navigate to the VCS → Git → Push option. Navigate to the VCS → Git → Push option. A window will appear. Here, you can see the comitts to be pushed. A window will appear. Here, you can see the comitts to be pushed. Verify commit and click on the Push button to publish your changes. Verify commit and click on the Push button to publish your changes. To show history, navigate to the VCS → Git → Show history option. This action is similar to the git log command. It will show history as follows − Follow these steps to fetch updates from the repository − Navigate to the VCS → Git → Pull option. Navigate to the VCS → Git → Pull option. Select the option according to your requirements. Select the option according to your requirements. Click on the Pull button. Click on the Pull button. To add existing project under Git − Navigate to VCS → Import into Version Control → Create Git repository. Navigate to VCS → Import into Version Control → Create Git repository. Select project by browsing directory. Select project by browsing directory. Click on the OK button. Click on the OK button. In this section, we will understand how Subversion works in IntelliJ. Let us consider a few important actions to understand this. To checkout SVN repository − Navigate to File → New → Project from Version Control → Subversion. Navigate to File → New → Project from Version Control → Subversion. Enter repository URL. Enter repository URL. Click on the OK button. Click on the OK button. SVN will track changes you made in the repository. Let us modify any file from repository and compare it with repository − Navigate to VCS->Subversion->Compare with Latest Repository Version Navigate to VCS->Subversion->Compare with Latest Repository Version You can see there is new line on right side with green background colour. You can see there is new line on right side with green background colour. SVN shows it in with green background to indicated the addition of new content. If we remove any content then it will be shown in red colour. SVN shows it in with green background to indicated the addition of new content. If we remove any content then it will be shown in red colour. Follow these steps to revert the local changes you have made − Navigate to the VCS → Subversion → Revert option. Navigate to the VCS → Subversion → Revert option. It will ask for confirmation and remove your changes. It will ask for confirmation and remove your changes. Follow these steps to commit changes in the remote repository − Navigate to VCS → Subversion → Commit Files option. Navigate to VCS → Subversion → Commit Files option. A new window will appear. Here, you can see the files to be committed to remote respository. A new window will appear. Here, you can see the files to be committed to remote respository. Verify the files and click on the Commit button to publish your changes. Verify the files and click on the Commit button to publish your changes. To show history, navigate to the VCS → Subverion → Show history option. This option is similar to the svn log command. It will show history as follows − To fetch latest changes navigate to VCS → Subversion → Update File/Update Folder option. Follow these steps to add existing project under SVN − Navigate to VCS → Import into Version Control → Import into Subverion. Navigate to VCS → Import into Version Control → Import into Subverion. Enter the repository URL and click on the Import button − Enter the repository URL and click on the Import button − IntelliJ provides database tool which allows you to perform database related operation from the IDE itself. It supports all major databases like MySQL, Oracle, Postgress, SQL server and many more. In this chapter, we will discuss how IntelliJ supports MySQL database. We assume that the reader is familiar with the database concepts and the required databases’ tools are installed and configured on your system. To begin with, we will create a database - test_db. Execute the following command in the command prompt − Follow these steps to connect to a Database − Navigate to View → Tool Windows → Database. Navigate to View → Tool Windows → Database. Click on the green plus icon and select Data Source → MySQL. Click on the green plus icon and select Data Source → MySQL. Enter the host address and click on the Test Connection button. Enter the host address and click on the Test Connection button. If everything goes well then it’ll show Successful as shown in above image. If everything goes well then it’ll show Successful as shown in above image. Click on OK button to save connection. Click on OK button to save connection. Follow these steps to create a new table − Right-click on the database pane and select schema. Right-click on the database pane and select schema. Select the New → Table option Select the New → Table option A new window will appear. Define the table with columns, types and so on. A new window will appear. Define the table with columns, types and so on. Click on the Execute button Click on the Execute button Click on the Execute button Click on the Execute button Follow these steps to insert data − Select table from the database pane. It will open table in the new window. Click on the plus icon to insert new row. Click on the Submit button to make the changes permanent. To retrieve data, double-click on student_table from the database pane. It will show table data in new window. To ensure that the data is inserted into the table, open the command prompt and execute the following commands − NetBeans is another popular Java IDE. If you are a current user of NetBeans and want to migrate from it to IntelliJ then this will serve as a good starting point. This chapter discusses the importing of NetBeans projects in IntelliJ, its terminologies equivalent to NetBeans, popular shortcuts and frequently asked questions. In this section, we will learn how to import NetBeans project. Follow these steps to import the project − Navigate to File → New → Project from Existing Sources Navigate to File → New → Project from Existing Sources Select your NetBeans project directory. Select your NetBeans project directory. When the Import Project wizard opens, select the Create project from existing sources option. When the Import Project wizard opens, select the Create project from existing sources option. Follow the on-screen instructions to continue. Follow the on-screen instructions to continue. The following table compares IntelliJ and NetBeans terminology − IntelliJ is a keyboard-centric IDE. It provides shortcuts for most of the actions. The following table lists a few important shortcuts − The following table lists down a few important debugger shortcuts − In this section, we will go through a few Frequently Answered Questions and Tips. The FAQs and tips are as follows − Navigate to Files → Settings and select Keymap. Navigate to Files → Settings and select Keymap. Select NetBeans from the drop down box Select NetBeans from the drop down box Local history in IntelliJ IDEA, generally, is more detailed. Whatever you do with a directory, file, class, method or field, or a code block is reflected in your local history. The local history also includes VCS operations. Navigate to File → Settings → Build, Execution, Deployment → Compiler Select Build Project Automatically option. Click on the OK button. No, you cannot. It is possible; however, you will not get the same kind of support that you get with NetBeans (wizards, menu actions, etc.). For more details, visit this. Eclipse is yet another popular Java IDE. If you are a current user of Eclipse and want to migrate from it to IntelliJ, then this is a good starting point. This chapter discusses how to import Eclipse projects in IntelliJ, its terminologies equivalent to Eclipse, popular shortcuts and frequently asked questions. In this section, we will discuss how to import an existing project. Follow these steps to import the project − Navigate to File → New → Project from Existing Sources. Navigate to File → New → Project from Existing Sources. Select your NetBeans project directory. Select your NetBeans project directory. When the Import Project wizard opens, select the Create project from existing sources option. When the Import Project wizard opens, select the Create project from existing sources option. Follow the on-screen instructions to continue. Follow the on-screen instructions to continue. The following table compares IntelliJ and NetBeans terminologies − IntelliJ is a keyboard-centric IDE. It provides shortcuts for most of the actions. The following table lists a few popular shortcuts − The following table lists down commonly used debugger shortcuts − In this section, we will see a few Frequently Answered Questions and tips. The FAQs and tips are as follows − While Eclipse uses its own compiler, IntelliJ IDEA uses the javac compiler bundled with the project JDK. If you want to use the Eclipse compiler − Navigate to File → Settings → Build, Execution, Deployment → Compiler → Java Compiler. Navigate to File → Settings → Build, Execution, Deployment → Compiler → Java Compiler. Select the required compiler from User compiler dropdown. Select the required compiler from User compiler dropdown. For Eclipse users who prefer not to learn new shortcuts, IntelliJ IDEA provides the Eclipse keymap that closely mimics its shortcuts − Navigate to File → Settings → Keymap option. Select Eclipse from Keymap dropdown. To import your Eclipse formatter settings − Navigate to File → Settings → Editor → Code Style → Java. Navigate to File → Settings → Editor → Code Style → Java. Select the Eclipse XML profile. Select the Eclipse XML profile. Like Eclipse, IntelliJ does not provide visual forms for editing Maven/Gradle configuration files. Once you have imported/created your Maven/Gradle project, you are free to edit its pom.xml/build.gradle files directly in the text editor. Print Add Notes Bookmark this page
[ { "code": null, "e": 2368, "s": 2089, "text": "IntelliJ is one of the most powerful and popular Integrated Development Environments (IDE) for Java. It is developed and maintained by JetBrains and available as community and ultimate edition. This feature rich IDE enables rapid development and helps in improving code quality." }, { "code": null, "e": 2586, "s": 2368, "text": "IDE stands for Integrated Development Environment. It is a combination of multiple tools, which make software development process easier, robust and less error-prone. It has following benefits over plain text editor −" }, { "code": null, "e": 2731, "s": 2586, "text": "Integration with useful tools like compiler, debugger, version control system, build tools, various frameworks, application profilers and so on." }, { "code": null, "e": 2876, "s": 2731, "text": "Integration with useful tools like compiler, debugger, version control system, build tools, various frameworks, application profilers and so on." }, { "code": null, "e": 2999, "s": 2876, "text": "Supports code navigation, code completion, code refactoring and code generation features which boosts development process." }, { "code": null, "e": 3122, "s": 2999, "text": "Supports code navigation, code completion, code refactoring and code generation features which boosts development process." }, { "code": null, "e": 3197, "s": 3122, "text": "Supports unit testing, integration testing and code coverage via plug-ins." }, { "code": null, "e": 3272, "s": 3197, "text": "Supports unit testing, integration testing and code coverage via plug-ins." }, { "code": null, "e": 3340, "s": 3272, "text": "Provides rich set of plug-ins to enhance IDE functionality further." }, { "code": null, "e": 3408, "s": 3340, "text": "Provides rich set of plug-ins to enhance IDE functionality further." }, { "code": null, "e": 3678, "s": 3408, "text": "IntelliJ IDEA has some top productive Java code completion features. Its predictive algorithm can accurately assume what a coder is attempting to type, and completes it for him, even if he doesn’t know the exact name of a particular class, member or any other resource." }, { "code": null, "e": 3835, "s": 3678, "text": "IntelliJ IDEA really understands and has a deep insight into your code, as well as the context of the coder, which makes it so unique among other Java IDEs." }, { "code": null, "e": 3982, "s": 3835, "text": "Smart code completion − It supports context based code completion. It gives a list of the most relevant symbols applicable in the current context." }, { "code": null, "e": 4129, "s": 3982, "text": "Smart code completion − It supports context based code completion. It gives a list of the most relevant symbols applicable in the current context." }, { "code": null, "e": 4284, "s": 4129, "text": "Chain code completion − It is an advanced code completion feature which lists applicable symbols accessible via methods or getters in the current context." }, { "code": null, "e": 4439, "s": 4284, "text": "Chain code completion − It is an advanced code completion feature which lists applicable symbols accessible via methods or getters in the current context." }, { "code": null, "e": 4599, "s": 4439, "text": "Static member's completion − It allows you to use static methods or constants and automatically adds the required import statements to avoid compilation error." }, { "code": null, "e": 4759, "s": 4599, "text": "Static member's completion − It allows you to use static methods or constants and automatically adds the required import statements to avoid compilation error." }, { "code": null, "e": 4883, "s": 4759, "text": "Detecting duplicates − It finds the duplicate code fragments on the fly and gives notification/suggestion about it to user." }, { "code": null, "e": 5007, "s": 4883, "text": "Detecting duplicates − It finds the duplicate code fragments on the fly and gives notification/suggestion about it to user." }, { "code": null, "e": 5194, "s": 5007, "text": "Inspections and quick-fixes − Whenever IntelliJ detects that you're about to make a mistake, a little light bulb notification pops up on same line. Clicking it shows the suggestion list." }, { "code": null, "e": 5381, "s": 5194, "text": "Inspections and quick-fixes − Whenever IntelliJ detects that you're about to make a mistake, a little light bulb notification pops up on same line. Clicking it shows the suggestion list." }, { "code": null, "e": 5667, "s": 5381, "text": "IntelliJ IDEA is designed around the coding principle that developers should be allowed to write codes with as less distraction as possible. That is why in this case, the editor is the only thing visible on the screen, with dedicated shortcuts for all other coding-unrelated functions." }, { "code": null, "e": 5787, "s": 5667, "text": "Editor-centric environment − Quick pop-ups help in checking additional information without leaving the current context." }, { "code": null, "e": 5907, "s": 5787, "text": "Editor-centric environment − Quick pop-ups help in checking additional information without leaving the current context." }, { "code": null, "e": 6070, "s": 5907, "text": "Shortcuts for everything − IntelliJ IDEA has keyboard shortcuts for nearly everything, including rapid selection and switching between tool windows and many more." }, { "code": null, "e": 6233, "s": 6070, "text": "Shortcuts for everything − IntelliJ IDEA has keyboard shortcuts for nearly everything, including rapid selection and switching between tool windows and many more." }, { "code": null, "e": 6371, "s": 6233, "text": "Inline debugger − Inline debugger allows you to debug application in IDE itself. It makes the development and debugging process seamless." }, { "code": null, "e": 6509, "s": 6371, "text": "Inline debugger − Inline debugger allows you to debug application in IDE itself. It makes the development and debugging process seamless." }, { "code": null, "e": 6696, "s": 6509, "text": "To help the developers organize their workflow, IntelliJ IDEA offers them an amazing toolset, which comprises of a decompiler, Docker support, bytecode viewer, FTP and many other tools −" }, { "code": null, "e": 6832, "s": 6696, "text": "Version control − IntelliJ supports most of the popular version control system like Git, Subversion, Mercurial, CVS, Perforce, and TFS." }, { "code": null, "e": 6968, "s": 6832, "text": "Version control − IntelliJ supports most of the popular version control system like Git, Subversion, Mercurial, CVS, Perforce, and TFS." }, { "code": null, "e": 7094, "s": 6968, "text": "Build tools − IntelliJ supports Java and other build tools like Maven, Gradle, Ant, Gant, SBT, NPM, Webpack, Grunt, and Gulp." }, { "code": null, "e": 7220, "s": 7094, "text": "Build tools − IntelliJ supports Java and other build tools like Maven, Gradle, Ant, Gant, SBT, NPM, Webpack, Grunt, and Gulp." }, { "code": null, "e": 7454, "s": 7220, "text": "Test runner and code coverage − IntelliJ IDEA lets you perform unit testing with ease. The IDE includes test runners and coverage tools for major test frameworks, including JUnit, TestNG, Spock, Cucumber, ScalaTest, spec2, and Karma." }, { "code": null, "e": 7688, "s": 7454, "text": "Test runner and code coverage − IntelliJ IDEA lets you perform unit testing with ease. The IDE includes test runners and coverage tools for major test frameworks, including JUnit, TestNG, Spock, Cucumber, ScalaTest, spec2, and Karma." }, { "code": null, "e": 7903, "s": 7688, "text": "Decompiler − IntelliJ comes with a built-in decompiler for Java classes. When you want to take a look inside a library that you do not have the source code for, you can do it without using any third-party plug-ins." }, { "code": null, "e": 8118, "s": 7903, "text": "Decompiler − IntelliJ comes with a built-in decompiler for Java classes. When you want to take a look inside a library that you do not have the source code for, you can do it without using any third-party plug-ins." }, { "code": null, "e": 8262, "s": 8118, "text": "Terminal − IntelliJ provides built-in terminal. Depending on your platform, you can work with the command line prompt, like PowerShell or Bash." }, { "code": null, "e": 8406, "s": 8262, "text": "Terminal − IntelliJ provides built-in terminal. Depending on your platform, you can work with the command line prompt, like PowerShell or Bash." }, { "code": null, "e": 8608, "s": 8406, "text": "Database tools − IntelliJ provides database tools, which allow you to connect to live databases; run queries; browse and update data; and even manage your schemas in a visual interface from IDE itself." }, { "code": null, "e": 8810, "s": 8608, "text": "Database tools − IntelliJ provides database tools, which allow you to connect to live databases; run queries; browse and update data; and even manage your schemas in a visual interface from IDE itself." }, { "code": null, "e": 9046, "s": 8810, "text": "Application server − IntelliJ supports major application servers: Tomcat, JBoss, WebSphere, WebLogic, Glassfish, and many others. You can deploy your artifacts onto application servers and debug the deployed applications in IDE itself." }, { "code": null, "e": 9282, "s": 9046, "text": "Application server − IntelliJ supports major application servers: Tomcat, JBoss, WebSphere, WebLogic, Glassfish, and many others. You can deploy your artifacts onto application servers and debug the deployed applications in IDE itself." }, { "code": null, "e": 9423, "s": 9282, "text": "Docker support − Via a separate plug-in, IntelliJ provides a dedicated tool window that lets you connect to locally running Docker machines." }, { "code": null, "e": 9564, "s": 9423, "text": "Docker support − Via a separate plug-in, IntelliJ provides a dedicated tool window that lets you connect to locally running Docker machines." }, { "code": null, "e": 9827, "s": 9564, "text": "The Ultimate Edition is designed to assist in web and enterprise development, whereas the Community Edition is designed for JVM and Android Development. Let us consider a few important points that will help us understand the comparison between the two editions −" }, { "code": null, "e": 10239, "s": 9827, "text": "In this chapter, we will understand how to install and configure IntelliJ IDEA. The first step of the process starts with choosing the edition. As per your requirements, you can download community or ultimate edition. As name suggests, community edition is absolutely free and we can use it for commercial development as well. However, ultimate edition is paid version and we can evaluate it freely for 30 days." }, { "code": null, "e": 10473, "s": 10239, "text": "IntelliJ is compatible with almost all versions of Windows prior to 2003. A comprehensive list will be: Windows 10/8/7/Vista/2003/XP. It is recommended that you shut down all other applications before you install IntelliJ on Windows." }, { "code": null, "e": 10545, "s": 10473, "text": "A minimum 2 GB of RAM capacity is recommended for seamless performance." }, { "code": null, "e": 10617, "s": 10545, "text": "A minimum 2 GB of RAM capacity is recommended for seamless performance." }, { "code": null, "e": 10686, "s": 10617, "text": "For better visualization, 1024x768 screen resolution is recommended." }, { "code": null, "e": 10755, "s": 10686, "text": "For better visualization, 1024x768 screen resolution is recommended." }, { "code": null, "e": 10829, "s": 10755, "text": "Minimum 300 MB disk space for installation and additional 1 GB for cache." }, { "code": null, "e": 10903, "s": 10829, "text": "Minimum 300 MB disk space for installation and additional 1 GB for cache." }, { "code": null, "e": 10981, "s": 10903, "text": "Downloading − You can download windows installer from their official website." }, { "code": null, "e": 11059, "s": 10981, "text": "Downloading − You can download windows installer from their official website." }, { "code": null, "e": 11321, "s": 11059, "text": "Installation − Let us begin with the installation followed by the configuration steps. Installation of IntelliJ is similar to other software packages. Just double-click on the installer and follow the on-screen instructions to complete the installation process." }, { "code": null, "e": 11583, "s": 11321, "text": "Installation − Let us begin with the installation followed by the configuration steps. Installation of IntelliJ is similar to other software packages. Just double-click on the installer and follow the on-screen instructions to complete the installation process." }, { "code": null, "e": 11718, "s": 11583, "text": "For installation of IntelliJ on Linux platforms, you need to note that a 32-bit JDK is not bundled, so a 64-bit system is recommended." }, { "code": null, "e": 11757, "s": 11718, "text": "GNOME, KDE or XFCE desktop environment" }, { "code": null, "e": 11796, "s": 11757, "text": "GNOME, KDE or XFCE desktop environment" }, { "code": null, "e": 11850, "s": 11796, "text": "Minimum 2 GB of RAM is recommended for seamless usage" }, { "code": null, "e": 11904, "s": 11850, "text": "Minimum 2 GB of RAM is recommended for seamless usage" }, { "code": null, "e": 11971, "s": 11904, "text": "300 MB of disk space for installation and addition 1 GB for caches" }, { "code": null, "e": 12038, "s": 11971, "text": "300 MB of disk space for installation and addition 1 GB for caches" }, { "code": null, "e": 12106, "s": 12038, "text": "For better visualization, 1024x768 screen resolution is recommended" }, { "code": null, "e": 12174, "s": 12106, "text": "For better visualization, 1024x768 screen resolution is recommended" }, { "code": null, "e": 12253, "s": 12174, "text": "Downloading − You can download IntelliJ for Linux from their official website." }, { "code": null, "e": 12332, "s": 12253, "text": "Downloading − You can download IntelliJ for Linux from their official website." }, { "code": null, "e": 12525, "s": 12332, "text": "Installation − We have downloaded tar.gz bundle. Note that in our case bundle’s name was ideaIC-2017.2.5.tar.gz. It may change with the edition/version. Please use the appropriate bundle name." }, { "code": null, "e": 12718, "s": 12525, "text": "Installation − We have downloaded tar.gz bundle. Note that in our case bundle’s name was ideaIC-2017.2.5.tar.gz. It may change with the edition/version. Please use the appropriate bundle name." }, { "code": null, "e": 13061, "s": 12718, "text": "First extract it using following command:\n$ tar xvf ideaIC-2017.2.5.tar.gz\nIt will create new directory with idea-IC-172.4343.14 name. \nNow change directory to idea-IC-172.4343.14/bin/ and execute idea.sh shell script as shown below:\n$ cd idea-IC-172.4343.14/bin/\n$ ./idea.sh\nFollow on-screen instructions to complete installation procedure.\n" }, { "code": null, "e": 13279, "s": 13061, "text": "The configuration steps are similar on both platforms. To begin configuration, launch IntelliJ application. Optionally, you can import the existing configuration from this wizard. Click on the next button to continue." }, { "code": null, "e": 13470, "s": 13279, "text": "Step1 − If you are using the ultimate edition, then a license activation window will pop-up. Select evaluate for free option and click on the evaluate button as shown in the following image." }, { "code": null, "e": 13616, "s": 13470, "text": "Step 2 − Accept the license agreement to proceed and follow on-screen instruction to start IntelliJ. You will see the Welcome screen of IntelliJ." }, { "code": null, "e": 13806, "s": 13616, "text": "Step 3 − Now, it is time to configure the Java Development Kit (hereafter, we will refer to it as JDK) with IntelliJ. If JDK is not installed already then follow the instruction as in here." }, { "code": null, "e": 13850, "s": 13806, "text": "On the Welcome screen, click on ‘configure’" }, { "code": null, "e": 13894, "s": 13850, "text": "On the Welcome screen, click on ‘configure’" }, { "code": null, "e": 13944, "s": 13894, "text": "Select ‘project defaults’ from the drop-down list" }, { "code": null, "e": 13994, "s": 13944, "text": "Select ‘project defaults’ from the drop-down list" }, { "code": null, "e": 14032, "s": 13994, "text": "Select the ‘project structure’ option" }, { "code": null, "e": 14070, "s": 14032, "text": "Select the ‘project structure’ option" }, { "code": null, "e": 14130, "s": 14070, "text": "Select the ‘SDKs’ option from the ‘platform settings’ menu." }, { "code": null, "e": 14190, "s": 14130, "text": "Select the ‘SDKs’ option from the ‘platform settings’ menu." }, { "code": null, "e": 14244, "s": 14190, "text": "Click on the ‘plus’ icon and select the ‘JDK’ option." }, { "code": null, "e": 14298, "s": 14244, "text": "Click on the ‘plus’ icon and select the ‘JDK’ option." }, { "code": null, "e": 14365, "s": 14298, "text": "Select JDK’s home directory and follow the on-screen instructions." }, { "code": null, "e": 14432, "s": 14365, "text": "Select JDK’s home directory and follow the on-screen instructions." }, { "code": null, "e": 14626, "s": 14432, "text": "In this chapter, we will get more familiar with IntelliJ IDEA. To discuss the advantages and functionality of any tool, one must be familiar with that tool and IntelliJ is no exception to that." }, { "code": null, "e": 14823, "s": 14626, "text": "This chapter gives you an overview of IntelliJ. The chapter begins with a discussion about IDE’s visual elements, configuration settings and finally ends by discussing JVM and platform properties." }, { "code": null, "e": 15075, "s": 14823, "text": "One of the important things about IDE is its visual elements. Identifying and understanding the visual elements enables to you do action in a quicker and easier manner. The following screenshot and the labels on it show the main interface of IntelliJ." }, { "code": null, "e": 16001, "s": 15075, "text": "\nMenu bar − The Menu bar provides options to create new projects and other important actions related to projects like code refactoring, builds, run, debug, version-controlling options and so on.\nTool bar − The Tool bar provides shortcuts to compile, debug and run options. You can customize it according to your requirements.\nNavigation bar − The Navigation bar enables easier navigation within a project. This feature comes handy as code base increases.\nTools tab − The Tools tab shows on either side of the main window. From here, you can access important tools like databases; Maven/Ant builds and so on.\nProject perspective − Project perspective window shows various elements of projects like packages, modules, classes, external libraries and so on.\nEditor window − This is a place where developer spends most of his/her time. Editor window allows you edit/write code with syntax highlighting and other useful features.\n" }, { "code": null, "e": 16195, "s": 16001, "text": "Menu bar − The Menu bar provides options to create new projects and other important actions related to projects like code refactoring, builds, run, debug, version-controlling options and so on." }, { "code": null, "e": 16389, "s": 16195, "text": "Menu bar − The Menu bar provides options to create new projects and other important actions related to projects like code refactoring, builds, run, debug, version-controlling options and so on." }, { "code": null, "e": 16520, "s": 16389, "text": "Tool bar − The Tool bar provides shortcuts to compile, debug and run options. You can customize it according to your requirements." }, { "code": null, "e": 16651, "s": 16520, "text": "Tool bar − The Tool bar provides shortcuts to compile, debug and run options. You can customize it according to your requirements." }, { "code": null, "e": 16780, "s": 16651, "text": "Navigation bar − The Navigation bar enables easier navigation within a project. This feature comes handy as code base increases." }, { "code": null, "e": 16909, "s": 16780, "text": "Navigation bar − The Navigation bar enables easier navigation within a project. This feature comes handy as code base increases." }, { "code": null, "e": 17062, "s": 16909, "text": "Tools tab − The Tools tab shows on either side of the main window. From here, you can access important tools like databases; Maven/Ant builds and so on." }, { "code": null, "e": 17215, "s": 17062, "text": "Tools tab − The Tools tab shows on either side of the main window. From here, you can access important tools like databases; Maven/Ant builds and so on." }, { "code": null, "e": 17362, "s": 17215, "text": "Project perspective − Project perspective window shows various elements of projects like packages, modules, classes, external libraries and so on." }, { "code": null, "e": 17509, "s": 17362, "text": "Project perspective − Project perspective window shows various elements of projects like packages, modules, classes, external libraries and so on." }, { "code": null, "e": 17679, "s": 17509, "text": "Editor window − This is a place where developer spends most of his/her time. Editor window allows you edit/write code with syntax highlighting and other useful features." }, { "code": null, "e": 17849, "s": 17679, "text": "Editor window − This is a place where developer spends most of his/her time. Editor window allows you edit/write code with syntax highlighting and other useful features." }, { "code": null, "e": 18128, "s": 17849, "text": "At the bottom of the main window, there is a status bar, which shows some additional attributes about the file - like its format and the encoding type. It also provides option to toggle the read-only attribute of the current file. You can also manage inspection level from here." }, { "code": null, "e": 18296, "s": 18128, "text": "Plug-ins help to extend functionality of IntelliJ. It provides a large number of plug-ins ranging from databases, version controlling, profiling and this list goes on." }, { "code": null, "e": 18336, "s": 18296, "text": "Follow these steps to manage plug-ins −" }, { "code": null, "e": 18368, "s": 18336, "text": "Go to the File → Settings menu." }, { "code": null, "e": 18400, "s": 18368, "text": "Go to the File → Settings menu." }, { "code": null, "e": 18441, "s": 18400, "text": "Select the Plugins tab on the left pane." }, { "code": null, "e": 18482, "s": 18441, "text": "Select the Plugins tab on the left pane." }, { "code": null, "e": 18638, "s": 18482, "text": "This window lists all installed plug-ins. There is a checkbox on the right side of each plug-in name. Toggling that checkbox enables/disables the plug-ins." }, { "code": null, "e": 18794, "s": 18638, "text": "This window lists all installed plug-ins. There is a checkbox on the right side of each plug-in name. Toggling that checkbox enables/disables the plug-ins." }, { "code": null, "e": 18961, "s": 18794, "text": "IntelliJ online plug-in repository is available here. To add/remove plug-in repository, click on the browse repository button and it will provide a way to do needful." }, { "code": null, "e": 19128, "s": 18961, "text": "IntelliJ online plug-in repository is available here. To add/remove plug-in repository, click on the browse repository button and it will provide a way to do needful." }, { "code": null, "e": 19299, "s": 19128, "text": "In addition to this, it allows offline plug-in installation. For this, download plug-in and select install plug-in from the disk button and navigate to the download path." }, { "code": null, "e": 19470, "s": 19299, "text": "In addition to this, it allows offline plug-in installation. For this, download plug-in and select install plug-in from the disk button and navigate to the download path." }, { "code": null, "e": 19651, "s": 19470, "text": "To perform other actions on plug-ins like uninstalling, updating and sorting, right-click on any plug-in. It will show a dropdown menu from which you can select one of the actions." }, { "code": null, "e": 19776, "s": 19651, "text": "This section provides a few important tips to manage settings. It enables you to import, export and share IntelliJ settings." }, { "code": null, "e": 19832, "s": 19776, "text": "It allows exporting the current settings as a jar file." }, { "code": null, "e": 19862, "s": 19832, "text": "Go to File → Export Settings." }, { "code": null, "e": 19892, "s": 19862, "text": "Go to File → Export Settings." }, { "code": null, "e": 19991, "s": 19892, "text": "Export setting windows list the available settings related to UI, debugger, SDK along with others." }, { "code": null, "e": 20090, "s": 19991, "text": "Export setting windows list the available settings related to UI, debugger, SDK along with others." }, { "code": null, "e": 20219, "s": 20090, "text": "It provides a checkbox for selection. Once the selection is done, click on the OK button to save the settings on the local disk." }, { "code": null, "e": 20348, "s": 20219, "text": "It provides a checkbox for selection. Once the selection is done, click on the OK button to save the settings on the local disk." }, { "code": null, "e": 20405, "s": 20348, "text": "It allows importing the settings stored in the jar file." }, { "code": null, "e": 20435, "s": 20405, "text": "Go to File → Import settings." }, { "code": null, "e": 20489, "s": 20435, "text": "Select the Setting jar by navigating folder structure" }, { "code": null, "e": 20513, "s": 20489, "text": "Click on the OK button." }, { "code": null, "e": 20806, "s": 20513, "text": "IntelliJ IDEA allows you to share your IDE settings between different instances. This is particularly useful when you want to apply the same settings within a team or organization. The prerequisite for this is to enable the Settings Repository plug-in. It is installed and enabled by default." }, { "code": null, "e": 20829, "s": 20806, "text": "To ensure its status −" }, { "code": null, "e": 20861, "s": 20829, "text": "Go to File → Settings → Plugins" }, { "code": null, "e": 20896, "s": 20861, "text": "Search settings repository plug-in" }, { "code": null, "e": 21015, "s": 20896, "text": "We can store the current setting on GitHub/Bitbucket and apply them on other instances. To store the current setting −" }, { "code": null, "e": 21053, "s": 21015, "text": "Go to the File → Settings Repository." }, { "code": null, "e": 21091, "s": 21053, "text": "Go to the File → Settings Repository." }, { "code": null, "e": 21147, "s": 21091, "text": "Type the Git repository URL in upstream URL dialog box." }, { "code": null, "e": 21203, "s": 21147, "text": "Type the Git repository URL in upstream URL dialog box." }, { "code": null, "e": 21241, "s": 21203, "text": "Click on the Overwrite remote button." }, { "code": null, "e": 21279, "s": 21241, "text": "Click on the Overwrite remote button." }, { "code": null, "e": 21363, "s": 21279, "text": "To apply the same settings to other instances, click on the Overwrite local button." }, { "code": null, "e": 21447, "s": 21363, "text": "To apply the same settings to other instances, click on the Overwrite local button." }, { "code": null, "e": 21591, "s": 21447, "text": "We can configure the JVM options by navigating to the Help → Edit Custom VM Options menu. Following are a few important JVM options we can set." }, { "code": null, "e": 21655, "s": 21591, "text": "–server − It allows the selection of the Java HotSpot Server VM" }, { "code": null, "e": 21719, "s": 21655, "text": "–server − It allows the selection of the Java HotSpot Server VM" }, { "code": null, "e": 21797, "s": 21719, "text": "-Xms<size> − It sets the initial Java heap size. The default value is 128 MB." }, { "code": null, "e": 21875, "s": 21797, "text": "-Xms<size> − It sets the initial Java heap size. The default value is 128 MB." }, { "code": null, "e": 21953, "s": 21875, "text": "-Xmx<size> − It sets the maximum Java heap size. The default value is 750 MB." }, { "code": null, "e": 22031, "s": 21953, "text": "-Xmx<size> − It sets the maximum Java heap size. The default value is 750 MB." }, { "code": null, "e": 22080, "s": 22031, "text": "-Xss<size> − It sets the Java thread stack size." }, { "code": null, "e": 22129, "s": 22080, "text": "-Xss<size> − It sets the Java thread stack size." }, { "code": null, "e": 22188, "s": 22129, "text": "–XX − It allows setting GC algorithm and other properties." }, { "code": null, "e": 22247, "s": 22188, "text": "–XX − It allows setting GC algorithm and other properties." }, { "code": null, "e": 22492, "s": 22247, "text": "It is time we got a hands-on experience with IntelliJ. In this chapter, we will create our first Java Project. We will write and execute the traditional Hello World program. This chapter explains the compilation and running of Java application." }, { "code": null, "e": 22632, "s": 22492, "text": "For anything related to development, a developer has to create a new project with IntelliJ. Let us follow these steps to create a project −" }, { "code": null, "e": 22649, "s": 22632, "text": "Launch IntelliJ." }, { "code": null, "e": 22666, "s": 22649, "text": "Launch IntelliJ." }, { "code": null, "e": 22699, "s": 22666, "text": "Go to File → New → Project menu." }, { "code": null, "e": 22732, "s": 22699, "text": "Go to File → New → Project menu." }, { "code": null, "e": 22806, "s": 22732, "text": "Select the Java project and appropriate SDK and click on the Next button." }, { "code": null, "e": 22880, "s": 22806, "text": "Select the Java project and appropriate SDK and click on the Next button." }, { "code": null, "e": 22992, "s": 22880, "text": "If you want to create a Java class with the main method, then select Create Project from the template checkbox." }, { "code": null, "e": 23104, "s": 22992, "text": "If you want to create a Java class with the main method, then select Create Project from the template checkbox." }, { "code": null, "e": 23178, "s": 23104, "text": "Select the command line app from the dialog box shown below and continue." }, { "code": null, "e": 23252, "s": 23178, "text": "Select the command line app from the dialog box shown below and continue." }, { "code": null, "e": 23303, "s": 23252, "text": "Enter the project name and the directory location." }, { "code": null, "e": 23354, "s": 23303, "text": "Enter the project name and the directory location." }, { "code": null, "e": 23382, "s": 23354, "text": "Click on the Finish button." }, { "code": null, "e": 23410, "s": 23382, "text": "Click on the Finish button." }, { "code": null, "e": 23570, "s": 23410, "text": "A package is created under Java project and can be created separately, or at the same time of creating a class. Let us follow these steps to create a package −" }, { "code": null, "e": 23601, "s": 23570, "text": "Go to the project perspective." }, { "code": null, "e": 23632, "s": 23601, "text": "Go to the project perspective." }, { "code": null, "e": 23687, "s": 23632, "text": "Right-click on Project, select the New->Module option." }, { "code": null, "e": 23742, "s": 23687, "text": "Right-click on Project, select the New->Module option." }, { "code": null, "e": 23873, "s": 23742, "text": "The new module window will be similar to the new project. Select the Java option and appropriate SDK and click on the Next button." }, { "code": null, "e": 24004, "s": 23873, "text": "The new module window will be similar to the new project. Select the Java option and appropriate SDK and click on the Next button." }, { "code": null, "e": 24027, "s": 24004, "text": "Enter the module name." }, { "code": null, "e": 24050, "s": 24027, "text": "Enter the module name." }, { "code": null, "e": 24078, "s": 24050, "text": "Click on the Finish button." }, { "code": null, "e": 24106, "s": 24078, "text": "Click on the Finish button." }, { "code": null, "e": 24254, "s": 24106, "text": "In this section, we will learn how to create a Java class. A Java class can be created under a Java module. Follow these steps to create a module −" }, { "code": null, "e": 24285, "s": 24254, "text": "Go to the Project perspective." }, { "code": null, "e": 24316, "s": 24285, "text": "Go to the Project perspective." }, { "code": null, "e": 24377, "s": 24316, "text": "Expand Project and select the src directory from the module." }, { "code": null, "e": 24438, "s": 24377, "text": "Expand Project and select the src directory from the module." }, { "code": null, "e": 24492, "s": 24438, "text": "Right click on it; select the New->Java Class option." }, { "code": null, "e": 24546, "s": 24492, "text": "Right click on it; select the New->Java Class option." }, { "code": null, "e": 24613, "s": 24546, "text": "Enter the class name in the dialog-box and click on the OK button." }, { "code": null, "e": 24680, "s": 24613, "text": "Enter the class name in the dialog-box and click on the OK button." }, { "code": null, "e": 24739, "s": 24680, "text": "It will open the Editor window with the class declaration." }, { "code": null, "e": 24798, "s": 24739, "text": "It will open the Editor window with the class declaration." }, { "code": null, "e": 24886, "s": 24798, "text": "We will now see how to run a Java application. Follow these steps and see how it runs −" }, { "code": null, "e": 25005, "s": 24886, "text": "Let us write a simple code, which will print a message on the console. Enter the following code in the Editor window −" }, { "code": null, "e": 25124, "s": 25005, "text": "Let us write a simple code, which will print a message on the console. Enter the following code in the Editor window −" }, { "code": null, "e": 25251, "s": 25124, "text": "public class HelloWorld { \n public static void main(String[] args) { \n System.out.println(\"Hello, World !!!\"); \n } \n}" }, { "code": null, "e": 25297, "s": 25251, "text": "Go to the Run menu and select the Run option." }, { "code": null, "e": 25343, "s": 25297, "text": "Go to the Run menu and select the Run option." }, { "code": null, "e": 25383, "s": 25343, "text": "Select the Class name and click on Run." }, { "code": null, "e": 25423, "s": 25383, "text": "Select the Class name and click on Run." }, { "code": null, "e": 25513, "s": 25423, "text": "If there are no compilation errors, then it will show output at the bottom of the window." }, { "code": null, "e": 25603, "s": 25513, "text": "If there are no compilation errors, then it will show output at the bottom of the window." }, { "code": null, "e": 25821, "s": 25603, "text": "The first four chapters of this tutorial were designed to give beginners a basic-level overview of IntelliJ. This section dives deep into IntelliJ and discusses more about projects, its format along with other things." }, { "code": null, "e": 26010, "s": 25821, "text": "A project is an application or software on which you are working. It can contain multiple modules, classes, libraries, configuration, and so on. It is the topmost element in the hierarchy." }, { "code": null, "e": 26255, "s": 26010, "text": "Modules feature one rung below ‘Project’. A module is a separate entity that can be compiled, debugged and run independently of other modules. A single project can contain multiple modules. You may add or remove modules from a project any time." }, { "code": null, "e": 26369, "s": 26255, "text": "In addition to this, we can also import the existing modules. Follow these steps to import the existing modules −" }, { "code": null, "e": 26401, "s": 26369, "text": "Go to File → Project structure." }, { "code": null, "e": 26440, "s": 26401, "text": "Select modules and click on plus icon." }, { "code": null, "e": 26482, "s": 26440, "text": "It will show the option to import module." }, { "code": null, "e": 26660, "s": 26482, "text": "Content root is a folder that contains all the files that make up your module. A module can have more than one content folder. Folders are categorized into the following types −" }, { "code": null, "e": 26844, "s": 26660, "text": "Sources − By assigning this category to folder, we instruct IntelliJ that this and its subfolder contain java source code and it should be compiled as part of the compilation process." }, { "code": null, "e": 27028, "s": 26844, "text": "Sources − By assigning this category to folder, we instruct IntelliJ that this and its subfolder contain java source code and it should be compiled as part of the compilation process." }, { "code": null, "e": 27191, "s": 27028, "text": "Tests − By assigning this category to folder, we instruct IntelliJ that it is the location for unit tests. This folder can access classes from the Sources folder." }, { "code": null, "e": 27354, "s": 27191, "text": "Tests − By assigning this category to folder, we instruct IntelliJ that it is the location for unit tests. This folder can access classes from the Sources folder." }, { "code": null, "e": 27562, "s": 27354, "text": "Resources − It represents various resource files used in project, for instance, images, XML and properties files. During the compilation process, contents of this folder is copied as is to the output folder." }, { "code": null, "e": 27770, "s": 27562, "text": "Resources − It represents various resource files used in project, for instance, images, XML and properties files. During the compilation process, contents of this folder is copied as is to the output folder." }, { "code": null, "e": 28022, "s": 27770, "text": "Excluded − Contents from the excluded folder will not be indexed by IntelliJ. This means that IntelliJ will not provide the code completion suggestion and other hints. For example, the output directory and the target directory are excluded by default." }, { "code": null, "e": 28274, "s": 28022, "text": "Excluded − Contents from the excluded folder will not be indexed by IntelliJ. This means that IntelliJ will not provide the code completion suggestion and other hints. For example, the output directory and the target directory are excluded by default." }, { "code": null, "e": 28349, "s": 28274, "text": "Test resources − This is similar to the resources and used for unit tests." }, { "code": null, "e": 28424, "s": 28349, "text": "Test resources − This is similar to the resources and used for unit tests." }, { "code": null, "e": 28670, "s": 28424, "text": "Library is a compilation of different classes. Library enables code reusability. In Java, library can be enclosed in ZIP, Jar or simply folder. We can define libraries at three different levels. The levels are - global, project and module level." }, { "code": null, "e": 28709, "s": 28670, "text": "Global level − Shared by all projects." }, { "code": null, "e": 28748, "s": 28709, "text": "Global level − Shared by all projects." }, { "code": null, "e": 28802, "s": 28748, "text": "Project level − Shared by all the modules of project." }, { "code": null, "e": 28856, "s": 28802, "text": "Project level − Shared by all the modules of project." }, { "code": null, "e": 28911, "s": 28856, "text": "Module level − Shared by the classes of those modules." }, { "code": null, "e": 28966, "s": 28911, "text": "Module level − Shared by the classes of those modules." }, { "code": null, "e": 29309, "s": 28966, "text": "Facets are the extensions to the modules. They add support to the frameworks and technologies. When a facet is added to a module, IntelliJ identifies it adds support. For instance, hints and help in editor, new tools in window bar, dependency downloading and so on. You can add facets from the File → Project Structure window as shown below −" }, { "code": null, "e": 29626, "s": 29309, "text": "Artifacts are the output of a project. It can be a simple JAR file, Java EE application, or Java EJB application. If we are using external build tools like Gradle or Maven, then IntelliJ will add artifact for them automatically. Artifacts can be created by navigating to the File → Project Structure as shown below −" }, { "code": null, "e": 29735, "s": 29626, "text": "In this section, we will understand how to import an existing project. We can import a project in two ways −" }, { "code": null, "e": 29766, "s": 29735, "text": "Import it from existing source" }, { "code": null, "e": 29798, "s": 29766, "text": "Import it from the build model." }, { "code": null, "e": 29872, "s": 29798, "text": "At present, it supports Gradle and Maven build tools. To import project −" }, { "code": null, "e": 29933, "s": 29872, "text": "Navigating to File → New → Project from the existing source." }, { "code": null, "e": 30017, "s": 29933, "text": "Select directory of the existing project, Maven’s pom.xml or Gradle’s build script." }, { "code": null, "e": 30041, "s": 30017, "text": "Click on the OK button." }, { "code": null, "e": 30384, "s": 30041, "text": "IntelliJ supports two types of project format one is directory-based and other is file-based. Directory based format is newer one it is recommended. By default, IntelliJ creates directory based project format. You can select project format while creating new project. On new project window just click on more settings as show in below image −" }, { "code": null, "e": 30678, "s": 30384, "text": "This format helps create an idea folder in your project and keep all configuration files inside that folder. Settings are grouped into the xml files. For instance, it will create misc.xml, modules.xml, workspace.xml and so on. The following screenshot will help you understand how this works −" }, { "code": null, "e": 30853, "s": 30678, "text": "It will create two project files with ..ipr and wpr extensions. The ipr file will contain project-specific settings and the wpr file will contain workspace-specific settings." }, { "code": null, "e": 30966, "s": 30853, "text": "To convert a file-based project to a directory-based project, go to the File → Save as a Directory-Based format." }, { "code": null, "e": 31128, "s": 30966, "text": "Compared to the file-based project format, the directory-based project format stores settings in a separate folder with meaningful names. Other differences are −" }, { "code": null, "e": 31238, "s": 31128, "text": "Related settings getting stored in a single file makes it easier to manage in directory-based project format." }, { "code": null, "e": 31348, "s": 31238, "text": "Related settings getting stored in a single file makes it easier to manage in directory-based project format." }, { "code": null, "e": 31492, "s": 31348, "text": "If folder contains the idea subfolder then IntelliJ recognizes that project. Because of this, you don’t have select the ipr project explicitly." }, { "code": null, "e": 31636, "s": 31492, "text": "If folder contains the idea subfolder then IntelliJ recognizes that project. Because of this, you don’t have select the ipr project explicitly." }, { "code": null, "e": 31795, "s": 31636, "text": "Directory-based project format breaks settings into multiple files hence it is easier to select particular type of setting to store in version control system." }, { "code": null, "e": 31954, "s": 31795, "text": "Directory-based project format breaks settings into multiple files hence it is easier to select particular type of setting to store in version control system." }, { "code": null, "e": 32241, "s": 31954, "text": "Editor is that area where a developer spends most of his/her time. Mastering the editor is the first step at improving the productivity of any resource. This chapter discusses visual elements of editor, the most common editor actions and SonarLint plug-in, which provides lint checking." }, { "code": null, "e": 32402, "s": 32241, "text": "IntelliJ has many provisions that include visual elements designed to assist developers in navigating through and understanding the real status of their coding." }, { "code": null, "e": 32450, "s": 32402, "text": "Let us now go through the different provision −" }, { "code": null, "e": 32540, "s": 32450, "text": "Editor’s gutter area is located on the left side of IDE as shown in the following image −" }, { "code": null, "e": 32675, "s": 32540, "text": "We will now understand how the labels work. The above screenshot is marked in numbers. We will now see what the numbers have to show −" }, { "code": null, "e": 32963, "s": 32675, "text": "Here we can see line numbers along with other useful options. If you observe carefully just before class name and main method there is a small green triangle. It provides option to run, debug and run application with coverage. Just click on the triangle icon and it will provide options." }, { "code": null, "e": 33251, "s": 32963, "text": "Here we can see line numbers along with other useful options. If you observe carefully just before class name and main method there is a small green triangle. It provides option to run, debug and run application with coverage. Just click on the triangle icon and it will provide options." }, { "code": null, "e": 33466, "s": 33251, "text": "You can see the small plus symbol at line number 6. This is the code folding functionality. If you click on that icon, then it will unfold it. Code folding can be done at class, method, loop and other block levels." }, { "code": null, "e": 33681, "s": 33466, "text": "You can see the small plus symbol at line number 6. This is the code folding functionality. If you click on that icon, then it will unfold it. Code folding can be done at class, method, loop and other block levels." }, { "code": null, "e": 34046, "s": 33681, "text": "At line numbers 11 and 14, there are 2 arrows which point towards each other. The marker represents the method’s start and end position. If you click on any arrow, then it will perform the fold action on that code block. The Gutter area will show various symbols when certain actions are taken; for instance, it will show symbols for breakpoints, Java annotations." }, { "code": null, "e": 34411, "s": 34046, "text": "At line numbers 11 and 14, there are 2 arrows which point towards each other. The marker represents the method’s start and end position. If you click on any arrow, then it will perform the fold action on that code block. The Gutter area will show various symbols when certain actions are taken; for instance, it will show symbols for breakpoints, Java annotations." }, { "code": null, "e": 34541, "s": 34411, "text": "At the bottom of the Editor window, there is a status bar, which shows information about the current file and the project status." }, { "code": null, "e": 34637, "s": 34541, "text": "In the first image, 16:1 represents the current line number and the column number respectively." }, { "code": null, "e": 34733, "s": 34637, "text": "In the first image, 16:1 represents the current line number and the column number respectively." }, { "code": null, "e": 34814, "s": 34733, "text": "Next is the line separator, for UNIX and mac OS it’s \\n and for windows it’s \\r." }, { "code": null, "e": 34895, "s": 34814, "text": "Next is the line separator, for UNIX and mac OS it’s \\n and for windows it’s \\r." }, { "code": null, "e": 34931, "s": 34895, "text": "UTF-8 represents the file encoding." }, { "code": null, "e": 34967, "s": 34931, "text": "UTF-8 represents the file encoding." }, { "code": null, "e": 35050, "s": 34967, "text": "Next is the lock icon. We can toggle file’s read-only attribute by clicking on it." }, { "code": null, "e": 35133, "s": 35050, "text": "Next is the lock icon. We can toggle file’s read-only attribute by clicking on it." }, { "code": null, "e": 35578, "s": 35133, "text": "At the end, there is a symbol with a man’s face. It allows managing the code inspection level.\n\nWhen we type code in Editor, IntelliJ inspects code on the fly and shows hints/suggestion. We can decide the inspection level from here. For instance, we can completely disable it or allow inspection only for syntax and so on.\nWe can also enable the Power Save mode from here, which will disable background code analysis and other background jobs.\n" }, { "code": null, "e": 35673, "s": 35578, "text": "At the end, there is a symbol with a man’s face. It allows managing the code inspection level." }, { "code": null, "e": 35900, "s": 35673, "text": "When we type code in Editor, IntelliJ inspects code on the fly and shows hints/suggestion. We can decide the inspection level from here. For instance, we can completely disable it or allow inspection only for syntax and so on." }, { "code": null, "e": 36127, "s": 35900, "text": "When we type code in Editor, IntelliJ inspects code on the fly and shows hints/suggestion. We can decide the inspection level from here. For instance, we can completely disable it or allow inspection only for syntax and so on." }, { "code": null, "e": 36248, "s": 36127, "text": "We can also enable the Power Save mode from here, which will disable background code analysis and other background jobs." }, { "code": null, "e": 36369, "s": 36248, "text": "We can also enable the Power Save mode from here, which will disable background code analysis and other background jobs." }, { "code": null, "e": 36501, "s": 36369, "text": "The Status bar also shows information about project actions. For instance, second image show information about project compilation." }, { "code": null, "e": 36633, "s": 36501, "text": "The Status bar also shows information about project actions. For instance, second image show information about project compilation." }, { "code": null, "e": 36800, "s": 36633, "text": "IntelliJ provides a temporary Editor. You can create text or piece of code without modifying the current project structure. It provides two types of temporary files −" }, { "code": null, "e": 36873, "s": 36800, "text": "They are functional, run-able and debug-able. To create a scratch file −" }, { "code": null, "e": 36906, "s": 36873, "text": "Go to File → New → Scratch file." }, { "code": null, "e": 36939, "s": 36906, "text": "Go to File → New → Scratch file." }, { "code": null, "e": 36975, "s": 36939, "text": "Select the language of your choice." }, { "code": null, "e": 37011, "s": 36975, "text": "Select the language of your choice." }, { "code": null, "e": 37099, "s": 37011, "text": "It will create a file in the IntelliJ-Installation-Directory\\ config \\scratches folder." }, { "code": null, "e": 37187, "s": 37099, "text": "It will create a file in the IntelliJ-Installation-Directory\\ config \\scratches folder." }, { "code": null, "e": 37257, "s": 37187, "text": "This is used only for creating any text. To create a scratch buffer −" }, { "code": null, "e": 37315, "s": 37257, "text": "Press Ctrl + Shift + A or click on Search Everywhere icon" }, { "code": null, "e": 37373, "s": 37315, "text": "Press Ctrl + Shift + A or click on Search Everywhere icon" }, { "code": null, "e": 37400, "s": 37373, "text": "It will pop up dialog box." }, { "code": null, "e": 37427, "s": 37400, "text": "It will pop up dialog box." }, { "code": null, "e": 37486, "s": 37427, "text": "Enter new scratch buffer text in that box and press enter." }, { "code": null, "e": 37545, "s": 37486, "text": "Enter new scratch buffer text in that box and press enter." }, { "code": null, "e": 37589, "s": 37545, "text": "It’ll open scratch buffer in editor window." }, { "code": null, "e": 37633, "s": 37589, "text": "It’ll open scratch buffer in editor window." }, { "code": null, "e": 37753, "s": 37633, "text": "Like the scratch files, scratch buffers are also stored in the IntelliJ-Installation-Directory\\config\\scratches folder." }, { "code": null, "e": 37945, "s": 37753, "text": "Scrollbar highlights warnings/error messages/TODO markers from the code. For instance, the sayHello() and sayGoodBye() method is never used; hence, the scrollbar shows yellow marker for them." }, { "code": null, "e": 38078, "s": 37945, "text": "At line number 8, there is the TODO comment, scrollbar highlights it using the blue marker. Errors are highlighted using red marker." }, { "code": null, "e": 38143, "s": 38078, "text": "In this section, we will discuss the Editor actions in IntelliJ." }, { "code": null, "e": 38180, "s": 38143, "text": "To search text in the current file −" }, { "code": null, "e": 38240, "s": 38180, "text": "Navigate to the file in the Editor window and press Ctrl+F." }, { "code": null, "e": 38300, "s": 38240, "text": "Navigate to the file in the Editor window and press Ctrl+F." }, { "code": null, "e": 38355, "s": 38300, "text": "It will show text box, type text to be searched there." }, { "code": null, "e": 38410, "s": 38355, "text": "It will show text box, type text to be searched there." }, { "code": null, "e": 38514, "s": 38410, "text": "You can provide various options here - case sensitive match, exact match, regular expression and so on." }, { "code": null, "e": 38618, "s": 38514, "text": "You can provide various options here - case sensitive match, exact match, regular expression and so on." }, { "code": null, "e": 38754, "s": 38618, "text": "You can perform the search operation at a very granular level. For instance, search can be done at project, module or directory level −" }, { "code": null, "e": 38794, "s": 38754, "text": "Press the Ctrl+Shift+F key combination." }, { "code": null, "e": 38834, "s": 38794, "text": "Press the Ctrl+Shift+F key combination." }, { "code": null, "e": 38909, "s": 38834, "text": "A new window will appear; from here, you can select the appropriate level." }, { "code": null, "e": 38984, "s": 38909, "text": "A new window will appear; from here, you can select the appropriate level." }, { "code": null, "e": 39034, "s": 38984, "text": "To perform a replace action in the current file −" }, { "code": null, "e": 39068, "s": 39034, "text": "Press the Ctrl+R key combination." }, { "code": null, "e": 39102, "s": 39068, "text": "Press the Ctrl+R key combination." }, { "code": null, "e": 39164, "s": 39102, "text": "A dialog box will appear, enter the text to be replaced here." }, { "code": null, "e": 39226, "s": 39164, "text": "A dialog box will appear, enter the text to be replaced here." }, { "code": null, "e": 39312, "s": 39226, "text": "This operation allows you to replace single match, all matches or skip current match." }, { "code": null, "e": 39398, "s": 39312, "text": "This operation allows you to replace single match, all matches or skip current match." }, { "code": null, "e": 39450, "s": 39398, "text": "To perform the replace action at a granular level −" }, { "code": null, "e": 39490, "s": 39450, "text": "Press the Shift+Ctrl+R key combination." }, { "code": null, "e": 39530, "s": 39490, "text": "Press the Shift+Ctrl+R key combination." }, { "code": null, "e": 39609, "s": 39530, "text": "It will allow you replace text at project, module, directory and other scopes." }, { "code": null, "e": 39688, "s": 39609, "text": "It will allow you replace text at project, module, directory and other scopes." }, { "code": null, "e": 39863, "s": 39688, "text": "To enable the column mode selection, hold the Alt key while selecting the text. To enable the column selection mode on a permanent basis, select Edit → Column selection mode." }, { "code": null, "e": 40077, "s": 39863, "text": "When we copy any text, it goes to the clipboard history. IntelliJ maintains the clipboard history. To view this history, pressthe Ctrl+Shift+V key combination. You can select the content to paste from this window." }, { "code": null, "e": 40244, "s": 40077, "text": "IntelliJ inspects the code on the fly and provides accurate code completion. For instance, when I type the word say - it suggests sayHello() and sayGoodBye() methods." }, { "code": null, "e": 40342, "s": 40244, "text": "Code completion suggests class attributes and class methods while working with the class objects." }, { "code": null, "e": 40536, "s": 40342, "text": "IntelliJ provides a way to generate useful code like constructor, getter, setter, toString() method, override methods and so on. Follow these steps to generate right-click in the Editor window." }, { "code": null, "e": 40564, "s": 40536, "text": "Select the Generate option." }, { "code": null, "e": 40592, "s": 40564, "text": "Select the Generate option." }, { "code": null, "e": 40654, "s": 40592, "text": "It will list the methods for which code can be can generated." }, { "code": null, "e": 40716, "s": 40654, "text": "It will list the methods for which code can be can generated." }, { "code": null, "e": 41022, "s": 40716, "text": "We have already seen that IntelliJ identifies syntax errors, warning messages and TODO markers. In addition to this, it suggests code improvement, identifies dead code, code optimization. For instance, in the code given below, the value of flag is always true. Hence, the else part will never be executed." }, { "code": null, "e": 41176, "s": 41022, "text": "boolean flag = true; \nif (flag == true) { \n System.out.println(\"Value of flag is true\"); \n} else { \n System.out.println(\"Value of flag is false\"); \n}" }, { "code": null, "e": 41240, "s": 41176, "text": "IntelliJ identifies this and suggests removing this code block." }, { "code": null, "e": 41290, "s": 41240, "text": "Follow these steps to compare files and folders −" }, { "code": null, "e": 41370, "s": 41290, "text": "Hold the Ctrl key and select files to be compared from the project perspective." }, { "code": null, "e": 41450, "s": 41370, "text": "Hold the Ctrl key and select files to be compared from the project perspective." }, { "code": null, "e": 41505, "s": 41450, "text": "Right-click on it and select the Compare Files option." }, { "code": null, "e": 41560, "s": 41505, "text": "Right-click on it and select the Compare Files option." }, { "code": null, "e": 41627, "s": 41560, "text": "It will open the Compare window where the changes are highlighted." }, { "code": null, "e": 41694, "s": 41627, "text": "It will open the Compare window where the changes are highlighted." }, { "code": null, "e": 41903, "s": 41694, "text": "You can also apply the changes from one file to another. If you observe, there are two arrow markers highlighted in red color. Click on them to apply changes from other file. Press Ctrl+Z to undo the changes." }, { "code": null, "e": 41996, "s": 41903, "text": "Similarly, to compare the folders, select folders from project perspective instead of files." }, { "code": null, "e": 42198, "s": 41996, "text": "It is useful if you get details about code easily. Like the method description, its return type, arguments type and number of arguments - IntelliJ can provide these details in the Editor window itself." }, { "code": null, "e": 42461, "s": 42198, "text": "As the name suggests, IntelliJ can access documentation by extracting it from the code. If you provide Java Docs for your code, then IntelliJ can show help about it. To access inline documentation, hover click on method name and press the Ctrl+Q key combination." }, { "code": null, "e": 42558, "s": 42461, "text": "To view definition, hover the mouse over method name and press the Ctrl+Shift+I key combination." }, { "code": null, "e": 42662, "s": 42558, "text": "To view method usage, click on method declaration/definition and press the Alt+Ctrl+F7 key combination." }, { "code": null, "e": 42748, "s": 42662, "text": "To view the method parameters, type method name and press the Ctrl+P key combination." }, { "code": null, "e": 42977, "s": 42748, "text": "Linting is a process in which the lint tool analyzes the source codes and reports potential issues related to the coding standard. It helps in improving the code quality. IntelliJ supports SonarLint plug-in which lints the code." }, { "code": null, "e": 43211, "s": 42977, "text": "Once you install and enable the SonarLint plug-in, it will start analyzing the code automatically when you open a file in the Editor window. It will report issues in the SonarLint panel. We will discuss more about it in this section." }, { "code": null, "e": 43299, "s": 43211, "text": "SonarLint supports popular programming languages like Java, JavaScript, PHP and Python." }, { "code": null, "e": 43341, "s": 43299, "text": "Follow these steps to install SonarLint −" }, { "code": null, "e": 43371, "s": 43341, "text": "Download SonarLint from here." }, { "code": null, "e": 43401, "s": 43371, "text": "Download SonarLint from here." }, { "code": null, "e": 43441, "s": 43401, "text": "Go to File → Settings → Select plugins." }, { "code": null, "e": 43481, "s": 43441, "text": "Go to File → Settings → Select plugins." }, { "code": null, "e": 43527, "s": 43481, "text": "Click on the Install plugin from disk button." }, { "code": null, "e": 43573, "s": 43527, "text": "Click on the Install plugin from disk button." }, { "code": null, "e": 43643, "s": 43573, "text": "Follow on-screen installation to complete the installation procedure." }, { "code": null, "e": 43713, "s": 43643, "text": "Follow on-screen installation to complete the installation procedure." }, { "code": null, "e": 43899, "s": 43713, "text": "Once the plug-in is installed and enabled, it will start analyzing code on the fly. It will report issues in the SonarLint panel. Follow these steps to view issues of the current file −" }, { "code": null, "e": 43930, "s": 43899, "text": "Click on the Current file tab." }, { "code": null, "e": 43961, "s": 43930, "text": "Click on the Current file tab." }, { "code": null, "e": 44064, "s": 43961, "text": "It will report issues like unused local variables, unused class attributes, message logging and so on." }, { "code": null, "e": 44167, "s": 44064, "text": "It will report issues like unused local variables, unused class attributes, message logging and so on." }, { "code": null, "e": 44230, "s": 44167, "text": "To know more about issue, click on issue from SolarLint panel." }, { "code": null, "e": 44293, "s": 44230, "text": "To know more about issue, click on issue from SolarLint panel." }, { "code": null, "e": 44379, "s": 44293, "text": "In the right side of the window, it will show its severity as Major, Minor and so on." }, { "code": null, "e": 44465, "s": 44379, "text": "In the right side of the window, it will show its severity as Major, Minor and so on." }, { "code": null, "e": 44669, "s": 44465, "text": "If you are not comfortable with on-the-fly code analysis, then you can disable it and perform one time code analysis once you are ready with code. Follow these steps to disable on-the-fly code analysis −" }, { "code": null, "e": 44736, "s": 44669, "text": "Go to File → Settings → Other Setting → SonarLint General Settings" }, { "code": null, "e": 44803, "s": 44736, "text": "Go to File → Settings → Other Setting → SonarLint General Settings" }, { "code": null, "e": 44874, "s": 44803, "text": "Uncheck Automatically Trigger Analysis checkbox from the settings tab." }, { "code": null, "e": 44945, "s": 44874, "text": "Uncheck Automatically Trigger Analysis checkbox from the settings tab." }, { "code": null, "e": 44983, "s": 44945, "text": "Click on Apply followed by Ok button." }, { "code": null, "e": 45021, "s": 44983, "text": "Click on Apply followed by Ok button." }, { "code": null, "e": 45423, "s": 45021, "text": "In this chapter, we will learn about Code Refactoring and how it works in IntelliJ. Code refactoring is restructuring of code without changing its functionality and usability. Code refactoring can be done to improve code readability, performance or to remove unused/duplicate functionality. IntelliJ provides great support for code refactoring. This chapter discusses various code refactoring actions." }, { "code": null, "e": 45577, "s": 45423, "text": "Rename actions can be used to rename methods, its parameters, class attributes, local variables and so on. Let us create the following class in IntelliJ." }, { "code": null, "e": 46543, "s": 45577, "text": "public class Employee {\n private String name;\n private String address;\n private int age;\n public Employee() {\n this(\"Jarvis\", \"Palo Alto\", 35);\n }\n public Employee(String name, String address, int age) {\n this.name = name;\n this.address = address;\n this.age = age;\n }\n public String getName() {\n return name;\n }\n public void setName(String name) {\n this.name = name;\n }\n public String getAddress() {\n return address;\n }\n public void setAddress(String address) {\n this.address = address;\n }\n public int getAge() {\n return age;\n }\n public void setAge(int age) {\n this.age = age;\n }\n \n @Override\n public String toString() {\n return \"Employee{\" +\n \"name='\" + name + '\\'' +\n \", address='\" + address + '\\'' +\n \", age=\" + age +\n '}';\n }\n public static void main(String args[]) {\n Employee e = new Employee();\n System.out.println(e);\n }\n}" }, { "code": null, "e": 46662, "s": 46543, "text": "Now, let us rename Employee class to Person. This action will do modifications in constructors and the main() method −" }, { "code": null, "e": 46683, "s": 46662, "text": "Select Employee word" }, { "code": null, "e": 46704, "s": 46683, "text": "Select Employee word" }, { "code": null, "e": 46755, "s": 46704, "text": "Go to Refactor → Rename and rename it with Person." }, { "code": null, "e": 46806, "s": 46755, "text": "Go to Refactor → Rename and rename it with Person." }, { "code": null, "e": 47021, "s": 46806, "text": "This is one of the powerful refactoring actions. IntelliJ identifies code duplicates and\nreplaces it with appropriate code. Let us introduce code duplication and refactor it. Type\nthe following code in the Editor −" }, { "code": null, "e": 47718, "s": 47021, "text": "public class Employee {\n private String name;\n private String address;\n private int age;\n public Employee() {\n this(\"Jarvis\", \"Palo Alto\", 35);\n }\n public Employee(String name, String address, int age) {\n this.name = name;\n this.address = address;\n this.age = age;\n }\n public void setData(String name, String address, int age) {\n this.name = name;\n this.address = address;\n this.age = age;\n }\n public void showEmployeeDetail() {\n System.out.println(\"Name = \" + name + \", Address = \" + address + \", Age = \" + age);\n }\n public static void main(String args[]) {\n Employee e = new Employee();\n e.showEmployeeDetail();\n }\n} " }, { "code": null, "e": 47995, "s": 47718, "text": "In this example, Employee(String name, String address, int age) constructor and public void setData(String name, String address, int age) method are exactly identical. After refactoring, the Employee(String name, String address, int age) constructor gets modified as follows −" }, { "code": null, "e": 48083, "s": 47995, "text": "public Employee(String name, String address, int age) {\n setData(name, address, age);\n}" }, { "code": null, "e": 48111, "s": 48083, "text": "To replace the duplicates −" }, { "code": null, "e": 48162, "s": 48111, "text": "Go to Refactor → Find and Replace Code Duplicates." }, { "code": null, "e": 48213, "s": 48162, "text": "Go to Refactor → Find and Replace Code Duplicates." }, { "code": null, "e": 48282, "s": 48213, "text": "Select refactor scope and follow on-screen steps to complete action." }, { "code": null, "e": 48351, "s": 48282, "text": "Select refactor scope and follow on-screen steps to complete action." }, { "code": null, "e": 48621, "s": 48351, "text": "In this section, we will understand how to copy one class to another. Let us copy Employee\nclass to Person class. We can copy it to the existing module or a new one. IntelliJ will do\nthe required changes depending on it. Follow these steps to perform copy refactoring −" }, { "code": null, "e": 48673, "s": 48621, "text": "Go to Refactor → Copy, it will open the dialog box." }, { "code": null, "e": 48725, "s": 48673, "text": "Go to Refactor → Copy, it will open the dialog box." }, { "code": null, "e": 48765, "s": 48725, "text": "Enter new name and destination package." }, { "code": null, "e": 48805, "s": 48765, "text": "Enter new name and destination package." }, { "code": null, "e": 48856, "s": 48805, "text": "Click on the OK button and it will do the needful." }, { "code": null, "e": 48907, "s": 48856, "text": "Click on the OK button and it will do the needful." }, { "code": null, "e": 49063, "s": 48907, "text": "Move refactoring is similar to copy but instead of making another copy it moves the code to a different package or make it as inner class of another class." }, { "code": null, "e": 49112, "s": 49063, "text": "Follow these steps to perform move refactoring −" }, { "code": null, "e": 49136, "s": 49112, "text": "Go to, Refactor → Move." }, { "code": null, "e": 49160, "s": 49136, "text": "Go to, Refactor → Move." }, { "code": null, "e": 49186, "s": 49160, "text": "A new window will appear." }, { "code": null, "e": 49212, "s": 49186, "text": "A new window will appear." }, { "code": null, "e": 49286, "s": 49212, "text": "Select one of the options according to your choice and click on Refactor." }, { "code": null, "e": 49360, "s": 49286, "text": "Select one of the options according to your choice and click on Refactor." }, { "code": null, "e": 49538, "s": 49360, "text": "The Safe Delete action will delete object only when it is not referenced anywhere in the\nproject. The target for this option can be class, interface, method, field or parameter." }, { "code": null, "e": 49601, "s": 49538, "text": "Let us see this in action. Type the following code in Editor −" }, { "code": null, "e": 49775, "s": 49601, "text": "public class HelloWorld {\n static void sayHello() {\n System.out.println(\"Hello, World !!!\");\n }\n public static void main(String[] args) {\n sayHello();\n }\n}" }, { "code": null, "e": 49830, "s": 49775, "text": "Follow these steps to perform the safe delete action −" }, { "code": null, "e": 49860, "s": 49830, "text": "Select the sayHello() method." }, { "code": null, "e": 49890, "s": 49860, "text": "Select the sayHello() method." }, { "code": null, "e": 49954, "s": 49890, "text": "Right-click on it and select the Refactor → Safe Delete option." }, { "code": null, "e": 50018, "s": 49954, "text": "Right-click on it and select the Refactor → Safe Delete option." }, { "code": null, "e": 50112, "s": 50018, "text": "As the sayHello() method is being used it will show an error as in the following\nscreenshot −" }, { "code": null, "e": 50206, "s": 50112, "text": "As the sayHello() method is being used it will show an error as in the following\nscreenshot −" }, { "code": null, "e": 50393, "s": 50206, "text": "The action modifies method signature. It can change the method name, its parameters,\ntypes, return values and so on. Let us take a method from the above example and change\nits signature." }, { "code": null, "e": 50453, "s": 50393, "text": "Follow these steps to perform the Change Signature action −" }, { "code": null, "e": 50468, "s": 50453, "text": "Select method." }, { "code": null, "e": 50483, "s": 50468, "text": "Select method." }, { "code": null, "e": 50551, "s": 50483, "text": "Right-click on it and select the Refactor → Change signature action" }, { "code": null, "e": 50619, "s": 50551, "text": "Right-click on it and select the Refactor → Change signature action" }, { "code": null, "e": 50687, "s": 50619, "text": "A new window will appear wherein you can perform the above actions." }, { "code": null, "e": 50755, "s": 50687, "text": "A new window will appear wherein you can perform the above actions." }, { "code": null, "e": 50823, "s": 50755, "text": "At the bottom of the window, it shows the preview of new signature." }, { "code": null, "e": 50891, "s": 50823, "text": "At the bottom of the window, it shows the preview of new signature." }, { "code": null, "e": 51077, "s": 50891, "text": "The Type Migration changes the type of the symbol. This symbol can be a method parameter or class attribute. Let us consider the following method before performing the required action −" }, { "code": null, "e": 51144, "s": 51077, "text": "static void sayHello(String name) {\n System.out.println(name);\n}" }, { "code": null, "e": 51191, "s": 51144, "text": "Follow these steps to perform type migration −" }, { "code": null, "e": 51222, "s": 51191, "text": "Select the “String” data type." }, { "code": null, "e": 51253, "s": 51222, "text": "Select the “String” data type." }, { "code": null, "e": 51309, "s": 51253, "text": "Right-click on it and select Refactor → Type migration." }, { "code": null, "e": 51365, "s": 51309, "text": "Right-click on it and select Refactor → Type migration." }, { "code": null, "e": 51417, "s": 51365, "text": "Enter the required data type in the given text box." }, { "code": null, "e": 51469, "s": 51417, "text": "Enter the required data type in the given text box." }, { "code": null, "e": 51516, "s": 51469, "text": "Choose scope and click on the Refactor button." }, { "code": null, "e": 51563, "s": 51516, "text": "Choose scope and click on the Refactor button." }, { "code": null, "e": 51768, "s": 51563, "text": "IntelliJ provides multiple ways to create configuration. This chapter discusses the options\nto create temporary, permanent configuration. It also discusses method to share configuration among other users." }, { "code": null, "e": 51910, "s": 51768, "text": "Temporary configuration is created when you run or debug Java class or test case. Consider the following steps to understand how this works −" }, { "code": null, "e": 51931, "s": 51910, "text": "Create a Java class." }, { "code": null, "e": 51976, "s": 51931, "text": "Right-click on it and select the Run option." }, { "code": null, "e": 52047, "s": 51976, "text": "After the first Run, temporary configuration is added to the run menu." }, { "code": null, "e": 52225, "s": 52047, "text": "Temporary configuration can be converted to permanent configuration by saving it with\nIntelliJ. To save configuration, click on the Save Configuration option from the Run menu −" }, { "code": null, "e": 52287, "s": 52225, "text": "You can also modify the existing configuration by editing it." }, { "code": null, "e": 52405, "s": 52287, "text": "In this section, we will understand how to create new configuration. Follow these steps to\ncreate new configuration −" }, { "code": null, "e": 52447, "s": 52405, "text": "Navigate to the Run → Edit Configuration." }, { "code": null, "e": 52489, "s": 52447, "text": "Navigate to the Run → Edit Configuration." }, { "code": null, "e": 52540, "s": 52489, "text": "Click on the Plus button to add new configuration." }, { "code": null, "e": 52591, "s": 52540, "text": "Click on the Plus button to add new configuration." }, { "code": null, "e": 52634, "s": 52591, "text": "Select Application from the dropdown list." }, { "code": null, "e": 52677, "s": 52634, "text": "Select Application from the dropdown list." }, { "code": null, "e": 52716, "s": 52677, "text": "It will create un-named configuration." }, { "code": null, "e": 52755, "s": 52716, "text": "It will create un-named configuration." }, { "code": null, "e": 52827, "s": 52755, "text": "Configure it according to your requirements and click on the OK button." }, { "code": null, "e": 52899, "s": 52827, "text": "Configure it according to your requirements and click on the OK button." }, { "code": null, "e": 52994, "s": 52899, "text": "This saved configuration will be accessible from the Run menu along with other\nconfigurations." }, { "code": null, "e": 53089, "s": 52994, "text": "This saved configuration will be accessible from the Run menu along with other\nconfigurations." }, { "code": null, "e": 53145, "s": 53089, "text": "Follow these steps to share configuration with others −" }, { "code": null, "e": 53187, "s": 53145, "text": "Navigate to the Run → Edit Configuration." }, { "code": null, "e": 53229, "s": 53187, "text": "Navigate to the Run → Edit Configuration." }, { "code": null, "e": 53302, "s": 53229, "text": "Select configuration from the left pane and click on the Share checkbox." }, { "code": null, "e": 53375, "s": 53302, "text": "Select configuration from the left pane and click on the Share checkbox." }, { "code": null, "e": 53412, "s": 53375, "text": "It will store configuration on disk." }, { "code": null, "e": 53449, "s": 53412, "text": "It will store configuration on disk." }, { "code": null, "e": 53616, "s": 53449, "text": "If directory based format is used, it will save configuration in separate file under\nrunConfiguration folder. Otherwise, it will store configuration in the .ipr file." }, { "code": null, "e": 53661, "s": 53616, "text": "To run project with specific configuration −" }, { "code": null, "e": 53701, "s": 53661, "text": "Select configuration from the Run menu." }, { "code": null, "e": 53741, "s": 53701, "text": "Select configuration from the Run menu." }, { "code": null, "e": 53796, "s": 53741, "text": "Run the project as shown in the following screenshot −" }, { "code": null, "e": 53851, "s": 53796, "text": "Run the project as shown in the following screenshot −" }, { "code": null, "e": 54014, "s": 53851, "text": "IntelliJ provides a way to build and package Java package. It supports external build tools\nlike Maven and Gradle. This chapter discusses about these build tools." }, { "code": null, "e": 54061, "s": 54014, "text": "Follow these steps to create a Maven project −" }, { "code": null, "e": 54089, "s": 54061, "text": "Navigate to File → Project." }, { "code": null, "e": 54117, "s": 54089, "text": "Navigate to File → Project." }, { "code": null, "e": 54163, "s": 54117, "text": "Select Maven option and click on Next button." }, { "code": null, "e": 54209, "s": 54163, "text": "Select Maven option and click on Next button." }, { "code": null, "e": 54301, "s": 54209, "text": "In the new project window enter tutorialspoint.com as GroupId and HelloWorld as ArtifactId." }, { "code": null, "e": 54393, "s": 54301, "text": "In the new project window enter tutorialspoint.com as GroupId and HelloWorld as ArtifactId." }, { "code": null, "e": 54444, "s": 54393, "text": "In the New window, it will open the pom.xml file. " }, { "code": null, "e": 54495, "s": 54444, "text": "In the New window, it will open the pom.xml file. " }, { "code": null, "e": 54582, "s": 54495, "text": "We need to add properties to this file; the final pom.xml file should look like this −" }, { "code": null, "e": 54669, "s": 54582, "text": "We need to add properties to this file; the final pom.xml file should look like this −" }, { "code": null, "e": 55248, "s": 54669, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<project xmlns = \"http://maven.apache.org/POM/4.0.0\"\n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation = \"http://maven.apache.org/POM/4.0.0 \n http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n <modelVersion>4.0.0</modelVersion>\n <groupId>com.tutorialspoing</groupId>\n <artifactId>HelloWorld</artifactId>\n <version>1.0-SNAPSHOT</version>\n <properties>\n <maven.compiler.source>1.7</maven.compiler.source>\n <maven.compiler.target>1.7</maven.compiler.target>\n </properties>\n</project>" }, { "code": null, "e": 55378, "s": 55248, "text": "Now, let us create a Java class inside the src/main/java directory of the Maven project. Follow these steps to create the class −" }, { "code": null, "e": 55419, "s": 55378, "text": "Navigate to the src/main/java directory." }, { "code": null, "e": 55460, "s": 55419, "text": "Navigate to the src/main/java directory." }, { "code": null, "e": 55507, "s": 55460, "text": "Right click on it and select New → Java Class." }, { "code": null, "e": 55554, "s": 55507, "text": "Right click on it and select New → Java Class." }, { "code": null, "e": 55609, "s": 55554, "text": "Follow these steps to compile this class using Maven −" }, { "code": null, "e": 55647, "s": 55609, "text": "Navigate to Run → Edit Configuration." }, { "code": null, "e": 55685, "s": 55647, "text": "Navigate to Run → Edit Configuration." }, { "code": null, "e": 55766, "s": 55685, "text": "Click on the green plus icon and select the Maven option from the dropdown menu." }, { "code": null, "e": 55847, "s": 55766, "text": "Click on the green plus icon and select the Maven option from the dropdown menu." }, { "code": null, "e": 55888, "s": 55847, "text": "Enter the project name as Maven-Package." }, { "code": null, "e": 55929, "s": 55888, "text": "Enter the project name as Maven-Package." }, { "code": null, "e": 55966, "s": 55929, "text": "Provide package as the command line." }, { "code": null, "e": 56003, "s": 55966, "text": "Provide package as the command line." }, { "code": null, "e": 56027, "s": 56003, "text": "Click on the OK button." }, { "code": null, "e": 56051, "s": 56027, "text": "Click on the OK button." }, { "code": null, "e": 56104, "s": 56051, "text": "Navigate to Run and select the Maven-Package option." }, { "code": null, "e": 56157, "s": 56104, "text": "Navigate to Run and select the Maven-Package option." }, { "code": null, "e": 56266, "s": 56157, "text": "It will start building package. Upon successful building of the package, you will see\nthe following result −" }, { "code": null, "e": 56375, "s": 56266, "text": "It will start building package. Upon successful building of the package, you will see\nthe following result −" }, { "code": null, "e": 56439, "s": 56375, "text": "In this section, we will learn how to create a Gradle project −" }, { "code": null, "e": 56485, "s": 56439, "text": "Navigate to File → Project and select Gradle." }, { "code": null, "e": 56531, "s": 56485, "text": "Navigate to File → Project and select Gradle." }, { "code": null, "e": 56557, "s": 56531, "text": "Click on the Next button." }, { "code": null, "e": 56583, "s": 56557, "text": "Click on the Next button." }, { "code": null, "e": 56673, "s": 56583, "text": "In the new project window, enter tutorialspoint as GroupId and HelloWorld\nas ArtifactId. " }, { "code": null, "e": 56763, "s": 56673, "text": "In the new project window, enter tutorialspoint as GroupId and HelloWorld\nas ArtifactId. " }, { "code": null, "e": 56848, "s": 56763, "text": "Click on the Next button, verify the project details and click on the Finish button." }, { "code": null, "e": 56933, "s": 56848, "text": "Click on the Next button, verify the project details and click on the Finish button." }, { "code": null, "e": 56992, "s": 56933, "text": "Follow the on-screen instructions to complete the process." }, { "code": null, "e": 57051, "s": 56992, "text": "Follow the on-screen instructions to complete the process." }, { "code": null, "e": 57134, "s": 57051, "text": "Open the buildl.gradle file and write Hello task as shown in the above screenshot." }, { "code": null, "e": 57217, "s": 57134, "text": "Open the buildl.gradle file and write Hello task as shown in the above screenshot." }, { "code": null, "e": 57282, "s": 57217, "text": "To compile this task, navigate to the Run → Build-Gradle option." }, { "code": null, "e": 57347, "s": 57282, "text": "To compile this task, navigate to the Run → Build-Gradle option." }, { "code": null, "e": 57545, "s": 57347, "text": "Unit testing plays an important role in software development. IntelliJ supports various unit\ntesting frameworks like JUnit, TestNG, Spock and many more. In this chapter, we are going to use JUnit3." }, { "code": null, "e": 57643, "s": 57545, "text": "In this section, we will learn how to create a Unit Test. Follow these steps to create the\ntest −" }, { "code": null, "e": 57678, "s": 57643, "text": "Select the Navigate → Test option." }, { "code": null, "e": 57713, "s": 57678, "text": "Select the Navigate → Test option." }, { "code": null, "e": 57783, "s": 57713, "text": "A dialog box will appear wherein, you have to select Create New Test." }, { "code": null, "e": 57853, "s": 57783, "text": "A dialog box will appear wherein, you have to select Create New Test." }, { "code": null, "e": 57901, "s": 57853, "text": "Follow the on-screen instructions to continue −" }, { "code": null, "e": 57949, "s": 57901, "text": "Follow the on-screen instructions to continue −" }, { "code": null, "e": 58056, "s": 57949, "text": "Provide the details about the test like testing library, class details, setUp, tearDown\nmethods and so on." }, { "code": null, "e": 58163, "s": 58056, "text": "Provide the details about the test like testing library, class details, setUp, tearDown\nmethods and so on." }, { "code": null, "e": 58199, "s": 58163, "text": "Click on the OK button to continue." }, { "code": null, "e": 58235, "s": 58199, "text": "Click on the OK button to continue." }, { "code": null, "e": 58381, "s": 58235, "text": "A test class will be created. Initially it may fail to resolve some symbols. Navigate\nthe cursor to the error line, it will show the hint symbol." }, { "code": null, "e": 58527, "s": 58381, "text": "A test class will be created. Initially it may fail to resolve some symbols. Navigate\nthe cursor to the error line, it will show the hint symbol." }, { "code": null, "e": 58649, "s": 58527, "text": "Select the appropriate option from the dropdown menu. We have selected the Add library ‘junit.jar!’ to classpath option −" }, { "code": null, "e": 58771, "s": 58649, "text": "Select the appropriate option from the dropdown menu. We have selected the Add library ‘junit.jar!’ to classpath option −" }, { "code": null, "e": 58883, "s": 58771, "text": "You can add logic inside each test according to your business requirement. I have kept it\nempty for simplicity." }, { "code": null, "e": 58921, "s": 58883, "text": "Follow these steps to run unit test −" }, { "code": null, "e": 58968, "s": 58921, "text": "Select unit test class from the Editor window." }, { "code": null, "e": 59015, "s": 58968, "text": "Select unit test class from the Editor window." }, { "code": null, "e": 59067, "s": 59015, "text": "Navigate to the Run menu and select the Run option." }, { "code": null, "e": 59119, "s": 59067, "text": "Navigate to the Run menu and select the Run option." }, { "code": null, "e": 59158, "s": 59119, "text": "The following result will be generated" }, { "code": null, "e": 59197, "s": 59158, "text": "The following result will be generated" }, { "code": null, "e": 59419, "s": 59197, "text": "Debugger makes application debugging much easier. Using debugger, we can stop the execution of program at a certain point, inspect variables, step into function and do many things. IntelliJ provides inbuilt Java debugger." }, { "code": null, "e": 59577, "s": 59419, "text": "Breakpoint allows stopping program execution at certain point. Breakpoints can be set by hovering the mouse over the Editor’s gutter area and clicking on it." }, { "code": null, "e": 59666, "s": 59577, "text": "Breakpoints are denoted using red circle symbols. Consider the breakpoint set at line 3." }, { "code": null, "e": 59744, "s": 59666, "text": "Consider the following steps to understand more on how the breakpoints work −" }, { "code": null, "e": 59782, "s": 59744, "text": "Right-click on the red circle symbol." }, { "code": null, "e": 59820, "s": 59782, "text": "Right-click on the red circle symbol." }, { "code": null, "e": 59845, "s": 59820, "text": "Select the More options." }, { "code": null, "e": 59870, "s": 59845, "text": "Select the More options." }, { "code": null, "e": 59918, "s": 59870, "text": "To remove breakpoint just click on same symbol." }, { "code": null, "e": 59966, "s": 59918, "text": "To remove breakpoint just click on same symbol." }, { "code": null, "e": 60009, "s": 59966, "text": "Follow these steps to start the debugger −" }, { "code": null, "e": 60035, "s": 60009, "text": "Navigate to the Run menu." }, { "code": null, "e": 60060, "s": 60035, "text": "Select the Debug option." }, { "code": null, "e": 60261, "s": 60060, "text": "While debugging, if a function is encountered and a step into action is selected, then debugger will stop program execution at each point of that function as if debugging is enabled for that function." }, { "code": null, "e": 60425, "s": 60261, "text": "For instance, when program execution reaches at line 9 and if we select the step into action then it stops the execution at each line in the sayGoodBye() function." }, { "code": null, "e": 60647, "s": 60425, "text": "The Step out action is exactly the reverse of Step in action. For instance, if you perform the step out action with the above scenario then debugger will return from the sayGoodBye() method and start execution at line 10." }, { "code": null, "e": 60853, "s": 60647, "text": "The Step over action does not enter into function instead, it will jump to the next line of code. For instance, if you are at line 9 and execute the step over action then it will move execution to line 10." }, { "code": null, "e": 60943, "s": 60853, "text": "The Resume Program action will continue execution of program by ignoring all breakpoints." }, { "code": null, "e": 60984, "s": 60943, "text": "The Stop action helps stop the debugger." }, { "code": null, "e": 61369, "s": 60984, "text": "While debugging, we may sometimes reach a line of code that calls several methods. When debugging these lines of code, the debugger typically allows us to use step into and leads us through all child functions and then back to the parent function. However, what if we only wanted to step into one child function? With Smart step-into, it allows us to choose the function to step into." }, { "code": null, "e": 61435, "s": 61369, "text": "Now, let us create a Java class with the following line of code −" }, { "code": null, "e": 61836, "s": 61435, "text": "public class HelloWorld {\n public static void main(String[] args) {\n allFunctions();\n }\n static void allFunctions() {\n System.out.println(function1() + \" \" + function2() + \" \" + function3());\n }\n static String function1() {\n return \"function1\";\n }\n static String function2() {\n return \"function2\";\n }\n static String function3() {\n return \"function3\";\n }\n}" }, { "code": null, "e": 61986, "s": 61836, "text": "In the above code, allFunctions() calls 3 more functions. Let us set the breakpoint at\nthis function. Follow these steps to perform smart step into −" }, { "code": null, "e": 61996, "s": 61986, "text": "Go to run" }, { "code": null, "e": 62020, "s": 61996, "text": "Select smart step into." }, { "code": null, "e": 62053, "s": 62020, "text": "Select the child function to go." }, { "code": null, "e": 62192, "s": 62053, "text": "During debugging, IntelliJ shows value of variable in the Editor window itself. We can also\nview the same information in the Debug window." }, { "code": null, "e": 62298, "s": 62192, "text": "Evaluate expression allows to evaluate expression on the fly. Follow these steps to perform\nthis action −" }, { "code": null, "e": 62328, "s": 62298, "text": "Start application in debugger" }, { "code": null, "e": 62358, "s": 62328, "text": "Start application in debugger" }, { "code": null, "e": 62396, "s": 62358, "text": "Navigate to Run->Evaluate expression." }, { "code": null, "e": 62434, "s": 62396, "text": "Navigate to Run->Evaluate expression." }, { "code": null, "e": 62571, "s": 62434, "text": "Enter expression. In the example given below, the current value of variable ‘i’ is 0;\nhence, expression ‘i > 100’ will evaluate to false" }, { "code": null, "e": 62708, "s": 62571, "text": "Enter expression. In the example given below, the current value of variable ‘i’ is 0;\nhence, expression ‘i > 100’ will evaluate to false" }, { "code": null, "e": 62973, "s": 62708, "text": "Profiler gives insights about your application like its CPU, memory and heap usage. It also\ngives details about the application threads. This chapter discusses the usage of VisualVM\ntool for Java application profiling. It can profile entities such as CPU and heap." }, { "code": null, "e": 63078, "s": 62973, "text": "It is recommended that the readers of this tutorial are familiar with the application profiler\nconcepts." }, { "code": null, "e": 63318, "s": 63078, "text": "VisualVM is a visual tool that integrates JDK tools and gives you powerful profiling\ncapabilities. It allows you to generate and analyze heap data, track down memory leaks,monitor the garbage collector and perform memory and CPU profiling." }, { "code": null, "e": 63390, "s": 63318, "text": "Visual interface for local and remote Java applications running on JVM." }, { "code": null, "e": 63462, "s": 63390, "text": "Visual interface for local and remote Java applications running on JVM." }, { "code": null, "e": 63539, "s": 63462, "text": "Monitoring of application’s memory usage and application’s runtime behavior." }, { "code": null, "e": 63616, "s": 63539, "text": "Monitoring of application’s memory usage and application’s runtime behavior." }, { "code": null, "e": 63650, "s": 63616, "text": "Monitoring of application threads" }, { "code": null, "e": 63684, "s": 63650, "text": "Monitoring of application threads" }, { "code": null, "e": 63744, "s": 63684, "text": "Analyzing the memory allocations to different applications." }, { "code": null, "e": 63804, "s": 63744, "text": "Analyzing the memory allocations to different applications." }, { "code": null, "e": 63872, "s": 63804, "text": "Thread dumps − very handy in case of deadlocks and race conditions." }, { "code": null, "e": 63940, "s": 63872, "text": "Thread dumps − very handy in case of deadlocks and race conditions." }, { "code": null, "e": 64005, "s": 63940, "text": "Heap dumps − very handy in analyzing the heap memory allocation." }, { "code": null, "e": 64070, "s": 64005, "text": "Heap dumps − very handy in analyzing the heap memory allocation." }, { "code": null, "e": 64170, "s": 64070, "text": "In this section, we will learn the steps performed to configure VisualVM. The steps are as\nfollow −" }, { "code": null, "e": 64193, "s": 64170, "text": "Download it from here." }, { "code": null, "e": 64216, "s": 64193, "text": "Download it from here." }, { "code": null, "e": 64238, "s": 64216, "text": "Extract the zip file." }, { "code": null, "e": 64260, "s": 64238, "text": "Extract the zip file." }, { "code": null, "e": 64337, "s": 64260, "text": "Navigate to etc/visualvm.conf file and add the following line in this file −" }, { "code": null, "e": 64414, "s": 64337, "text": "Navigate to etc/visualvm.conf file and add the following line in this file −" }, { "code": null, "e": 64446, "s": 64414, "text": "visualvm_jdkhome=<path of JDK>\n" }, { "code": null, "e": 64552, "s": 64446, "text": "If your JDK is installed in the C:\\Program Files\\Java\\jdk-9.0.1 directory then\nit should look like this −" }, { "code": null, "e": 64658, "s": 64552, "text": "If your JDK is installed in the C:\\Program Files\\Java\\jdk-9.0.1 directory then\nit should look like this −" }, { "code": null, "e": 64710, "s": 64658, "text": "visualvm_jdkhome=\"C:\\Program Files\\Java\\jdk-9.0.1\"\n" }, { "code": null, "e": 64811, "s": 64710, "text": "Let us now see how to monitor the application. Consider the following steps to understand\nthe same −" }, { "code": null, "e": 64850, "s": 64811, "text": "Double-click on the visualvm.exe file." }, { "code": null, "e": 64889, "s": 64850, "text": "Select the application from left pane." }, { "code": null, "e": 64913, "s": 64889, "text": "Select the monitor tab." }, { "code": null, "e": 65132, "s": 64913, "text": "You will be directed to a window where you will get the details about CPU, Heap, Classes\nand threads. To be specific with the usage, hover the mouse over any graph. We can see\nthe usage of Heap in the above screenshot." }, { "code": null, "e": 65444, "s": 65132, "text": "Java application can contain multiple threads of execution. To know more about threads,\nselect the Threads tab of a particular application. It will give various statistics about\nthreads like number of live threads and daemon threads. The different thread states are\nRunning, Sleeping, Waiting, Park and Monitor." }, { "code": null, "e": 65580, "s": 65444, "text": "VisualVM supports CPU, memory sampling and memory leak detection. To sample application, select application and choose the sample tab −" }, { "code": null, "e": 65660, "s": 65580, "text": "For CPU sampling, click on the CPU button as show in the following screenshot −" }, { "code": null, "e": 65748, "s": 65660, "text": "For memory profiling, click on the Memory button as shown in the following screenshot −" }, { "code": null, "e": 65894, "s": 65748, "text": "A memory leak occurs when an application, while running, slowly fills up the heap with\nobjects that are not automatically deleted by the program." }, { "code": null, "e": 66231, "s": 65894, "text": "If an object that is not used by the program is not deleted, then it remains in memory and\nthe GC cannot reclaim its space. If the number of bytes and number of instances in your\napplication were to increase constantly and significantly in your program to the point of\nusing up all the space, this can be an indication of a memory leak." }, { "code": null, "e": 66382, "s": 66231, "text": "In this section, we will learn how to profile an application. To profile an application, select application from left pane and click the profile tab −" }, { "code": null, "e": 66467, "s": 66382, "text": "To perform CPU profiling, click on the CPU button as shown in the screenshot below −" }, { "code": null, "e": 66552, "s": 66467, "text": "To perform CPU profiling, click on the CPU button as shown in the screenshot below −" }, { "code": null, "e": 66724, "s": 66552, "text": "IntelliJ supports various version control systems like Git, Subversion, Mercurial, CVS,\nGitHub and TFS. You can perform version control related action from the IDE itself." }, { "code": null, "e": 66889, "s": 66724, "text": "In this chapter, we will discuss Git and Subversion (hereafter referred to as SVN). We\nassume that the reader is familiar with Git and SVN tool and its terminology." }, { "code": null, "e": 66942, "s": 66889, "text": "In this section, we will learn how to work with Git." }, { "code": null, "e": 66980, "s": 66942, "text": "To clone an existing Git repository −" }, { "code": null, "e": 67038, "s": 66980, "text": "Navigate to File->New->Project from Version Control->Git." }, { "code": null, "e": 67096, "s": 67038, "text": "Navigate to File->New->Project from Version Control->Git." }, { "code": null, "e": 67159, "s": 67096, "text": "Enter the repository URL, Parent directory and Directory name." }, { "code": null, "e": 67222, "s": 67159, "text": "Enter the repository URL, Parent directory and Directory name." }, { "code": null, "e": 67261, "s": 67222, "text": "Click on the clone button to continue." }, { "code": null, "e": 67300, "s": 67261, "text": "Click on the clone button to continue." }, { "code": null, "e": 67376, "s": 67300, "text": "Upon successful running of the above steps, the repository will get cloned." }, { "code": null, "e": 67452, "s": 67376, "text": "Upon successful running of the above steps, the repository will get cloned." }, { "code": null, "e": 67587, "s": 67452, "text": "Git will track the changes that you make in repository. Let us modify any file from the\nrepository and compare it with the repository." }, { "code": null, "e": 67651, "s": 67587, "text": "Navigate to VCS → Git → Compare with Latest Repository Version." }, { "code": null, "e": 67715, "s": 67651, "text": "Navigate to VCS → Git → Compare with Latest Repository Version." }, { "code": null, "e": 67757, "s": 67715, "text": "The above step will open the diff window." }, { "code": null, "e": 67799, "s": 67757, "text": "The above step will open the diff window." }, { "code": null, "e": 67879, "s": 67799, "text": "You can see there is a new line on the right side with green background colour." }, { "code": null, "e": 67959, "s": 67879, "text": "You can see there is a new line on the right side with green background colour." }, { "code": null, "e": 68072, "s": 67959, "text": "Git shows it in green as we have added new contents. If we remove any contents then it’ll be shown in red colour" }, { "code": null, "e": 68185, "s": 68072, "text": "Git shows it in green as we have added new contents. If we remove any contents then it’ll be shown in red colour" }, { "code": null, "e": 68235, "s": 68185, "text": "Follow these steps to discard the local changes −" }, { "code": null, "e": 68278, "s": 68235, "text": "Navigate to the VCS → Git → Revert option." }, { "code": null, "e": 68321, "s": 68278, "text": "Navigate to the VCS → Git → Revert option." }, { "code": null, "e": 68375, "s": 68321, "text": "It will ask for confirmation and remove your changes." }, { "code": null, "e": 68429, "s": 68375, "text": "It will ask for confirmation and remove your changes." }, { "code": null, "e": 68537, "s": 68429, "text": "To add file to repository navigate to VCS → Git → Add option. This action is similar to the git add action." }, { "code": null, "e": 68644, "s": 68537, "text": "The Commit operation will create local commit. It is similar to the git commit action. To perform commit −" }, { "code": null, "e": 68692, "s": 68644, "text": "Navigate to the VCS → Git → Commit File option." }, { "code": null, "e": 68740, "s": 68692, "text": "Navigate to the VCS → Git → Commit File option." }, { "code": null, "e": 68770, "s": 68740, "text": "Select files to be committed." }, { "code": null, "e": 68800, "s": 68770, "text": "Select files to be committed." }, { "code": null, "e": 68849, "s": 68800, "text": "Enter commit message and click on Commit button." }, { "code": null, "e": 68898, "s": 68849, "text": "Enter commit message and click on Commit button." }, { "code": null, "e": 68982, "s": 68898, "text": "The Push action will send local changes to the remote repository. To push changes −" }, { "code": null, "e": 69023, "s": 68982, "text": "Navigate to the VCS → Git → Push option." }, { "code": null, "e": 69064, "s": 69023, "text": "Navigate to the VCS → Git → Push option." }, { "code": null, "e": 69130, "s": 69064, "text": "A window will appear. Here, you can see the comitts to be pushed." }, { "code": null, "e": 69196, "s": 69130, "text": "A window will appear. Here, you can see the comitts to be pushed." }, { "code": null, "e": 69264, "s": 69196, "text": "Verify commit and click on the Push button to publish your changes." }, { "code": null, "e": 69332, "s": 69264, "text": "Verify commit and click on the Push button to publish your changes." }, { "code": null, "e": 69479, "s": 69332, "text": "To show history, navigate to the VCS → Git → Show history option. This action is similar\nto the git log command. It will show history as follows −" }, { "code": null, "e": 69537, "s": 69479, "text": "Follow these steps to fetch updates from the repository −" }, { "code": null, "e": 69578, "s": 69537, "text": "Navigate to the VCS → Git → Pull option." }, { "code": null, "e": 69619, "s": 69578, "text": "Navigate to the VCS → Git → Pull option." }, { "code": null, "e": 69669, "s": 69619, "text": "Select the option according to your requirements." }, { "code": null, "e": 69719, "s": 69669, "text": "Select the option according to your requirements." }, { "code": null, "e": 69745, "s": 69719, "text": "Click on the Pull button." }, { "code": null, "e": 69771, "s": 69745, "text": "Click on the Pull button." }, { "code": null, "e": 69807, "s": 69771, "text": "To add existing project under Git −" }, { "code": null, "e": 69878, "s": 69807, "text": "Navigate to VCS → Import into Version Control → Create Git repository." }, { "code": null, "e": 69949, "s": 69878, "text": "Navigate to VCS → Import into Version Control → Create Git repository." }, { "code": null, "e": 69987, "s": 69949, "text": "Select project by browsing directory." }, { "code": null, "e": 70025, "s": 69987, "text": "Select project by browsing directory." }, { "code": null, "e": 70049, "s": 70025, "text": "Click on the OK button." }, { "code": null, "e": 70073, "s": 70049, "text": "Click on the OK button." }, { "code": null, "e": 70203, "s": 70073, "text": "In this section, we will understand how Subversion works in IntelliJ. Let us consider a few\nimportant actions to understand this." }, { "code": null, "e": 70232, "s": 70203, "text": "To checkout SVN repository −" }, { "code": null, "e": 70300, "s": 70232, "text": "Navigate to File → New → Project from Version Control → Subversion." }, { "code": null, "e": 70368, "s": 70300, "text": "Navigate to File → New → Project from Version Control → Subversion." }, { "code": null, "e": 70390, "s": 70368, "text": "Enter repository URL." }, { "code": null, "e": 70412, "s": 70390, "text": "Enter repository URL." }, { "code": null, "e": 70436, "s": 70412, "text": "Click on the OK button." }, { "code": null, "e": 70460, "s": 70436, "text": "Click on the OK button." }, { "code": null, "e": 70583, "s": 70460, "text": "SVN will track changes you made in the repository. Let us modify any file from repository\nand compare it with repository −" }, { "code": null, "e": 70651, "s": 70583, "text": "Navigate to VCS->Subversion->Compare with Latest Repository Version" }, { "code": null, "e": 70719, "s": 70651, "text": "Navigate to VCS->Subversion->Compare with Latest Repository Version" }, { "code": null, "e": 70793, "s": 70719, "text": "You can see there is new line on right side with green background colour." }, { "code": null, "e": 70867, "s": 70793, "text": "You can see there is new line on right side with green background colour." }, { "code": null, "e": 71009, "s": 70867, "text": "SVN shows it in with green background to indicated the addition of new content. If\nwe remove any content then it will be shown in red colour." }, { "code": null, "e": 71151, "s": 71009, "text": "SVN shows it in with green background to indicated the addition of new content. If\nwe remove any content then it will be shown in red colour." }, { "code": null, "e": 71214, "s": 71151, "text": "Follow these steps to revert the local changes you have made −" }, { "code": null, "e": 71264, "s": 71214, "text": "Navigate to the VCS → Subversion → Revert option." }, { "code": null, "e": 71314, "s": 71264, "text": "Navigate to the VCS → Subversion → Revert option." }, { "code": null, "e": 71368, "s": 71314, "text": "It will ask for confirmation and remove your changes." }, { "code": null, "e": 71422, "s": 71368, "text": "It will ask for confirmation and remove your changes." }, { "code": null, "e": 71486, "s": 71422, "text": "Follow these steps to commit changes in the remote repository −" }, { "code": null, "e": 71538, "s": 71486, "text": "Navigate to VCS → Subversion → Commit Files option." }, { "code": null, "e": 71590, "s": 71538, "text": "Navigate to VCS → Subversion → Commit Files option." }, { "code": null, "e": 71683, "s": 71590, "text": "A new window will appear. Here, you can see the files to be committed to remote\nrespository." }, { "code": null, "e": 71776, "s": 71683, "text": "A new window will appear. Here, you can see the files to be committed to remote\nrespository." }, { "code": null, "e": 71849, "s": 71776, "text": "Verify the files and click on the Commit button to publish your changes." }, { "code": null, "e": 71922, "s": 71849, "text": "Verify the files and click on the Commit button to publish your changes." }, { "code": null, "e": 72075, "s": 71922, "text": "To show history, navigate to the VCS → Subverion → Show history option. This option is\nsimilar to the svn log command. It will show history as follows −" }, { "code": null, "e": 72164, "s": 72075, "text": "To fetch latest changes navigate to VCS → Subversion → Update File/Update Folder option." }, { "code": null, "e": 72219, "s": 72164, "text": "Follow these steps to add existing project under SVN −" }, { "code": null, "e": 72290, "s": 72219, "text": "Navigate to VCS → Import into Version Control → Import into Subverion." }, { "code": null, "e": 72361, "s": 72290, "text": "Navigate to VCS → Import into Version Control → Import into Subverion." }, { "code": null, "e": 72419, "s": 72361, "text": "Enter the repository URL and click on the Import button −" }, { "code": null, "e": 72477, "s": 72419, "text": "Enter the repository URL and click on the Import button −" }, { "code": null, "e": 72745, "s": 72477, "text": "IntelliJ provides database tool which allows you to perform database related operation from the IDE itself. It supports all major databases like MySQL, Oracle, Postgress, SQL server and many more. In this chapter, we will discuss how IntelliJ supports MySQL database." }, { "code": null, "e": 72889, "s": 72745, "text": "We assume that the reader is familiar with the database concepts and the required databases’ tools are installed and configured on your system." }, { "code": null, "e": 72995, "s": 72889, "text": "To begin with, we will create a database - test_db. Execute the following command in the command prompt −" }, { "code": null, "e": 73041, "s": 72995, "text": "Follow these steps to connect to a Database −" }, { "code": null, "e": 73085, "s": 73041, "text": "Navigate to View → Tool Windows → Database." }, { "code": null, "e": 73129, "s": 73085, "text": "Navigate to View → Tool Windows → Database." }, { "code": null, "e": 73190, "s": 73129, "text": "Click on the green plus icon and select Data Source → MySQL." }, { "code": null, "e": 73251, "s": 73190, "text": "Click on the green plus icon and select Data Source → MySQL." }, { "code": null, "e": 73315, "s": 73251, "text": "Enter the host address and click on the Test Connection button." }, { "code": null, "e": 73379, "s": 73315, "text": "Enter the host address and click on the Test Connection button." }, { "code": null, "e": 73455, "s": 73379, "text": "If everything goes well then it’ll show Successful as shown in above image." }, { "code": null, "e": 73531, "s": 73455, "text": "If everything goes well then it’ll show Successful as shown in above image." }, { "code": null, "e": 73570, "s": 73531, "text": "Click on OK button to save connection." }, { "code": null, "e": 73609, "s": 73570, "text": "Click on OK button to save connection." }, { "code": null, "e": 73652, "s": 73609, "text": "Follow these steps to create a new table −" }, { "code": null, "e": 73704, "s": 73652, "text": "Right-click on the database pane and select schema." }, { "code": null, "e": 73756, "s": 73704, "text": "Right-click on the database pane and select schema." }, { "code": null, "e": 73786, "s": 73756, "text": "Select the New → Table option" }, { "code": null, "e": 73816, "s": 73786, "text": "Select the New → Table option" }, { "code": null, "e": 73890, "s": 73816, "text": "A new window will appear. Define the table with columns, types and so on." }, { "code": null, "e": 73964, "s": 73890, "text": "A new window will appear. Define the table with columns, types and so on." }, { "code": null, "e": 73992, "s": 73964, "text": "Click on the Execute button" }, { "code": null, "e": 74020, "s": 73992, "text": "Click on the Execute button" }, { "code": null, "e": 74048, "s": 74020, "text": "Click on the Execute button" }, { "code": null, "e": 74076, "s": 74048, "text": "Click on the Execute button" }, { "code": null, "e": 74112, "s": 74076, "text": "Follow these steps to insert data −" }, { "code": null, "e": 74149, "s": 74112, "text": "Select table from the database pane." }, { "code": null, "e": 74187, "s": 74149, "text": "It will open table in the new window." }, { "code": null, "e": 74229, "s": 74187, "text": "Click on the plus icon to insert new row." }, { "code": null, "e": 74287, "s": 74229, "text": "Click on the Submit button to make the changes permanent." }, { "code": null, "e": 74398, "s": 74287, "text": "To retrieve data, double-click on student_table from the database pane. It will show table\ndata in new window." }, { "code": null, "e": 74511, "s": 74398, "text": "To ensure that the data is inserted into the table, open the command prompt and execute\nthe following commands −" }, { "code": null, "e": 74674, "s": 74511, "text": "NetBeans is another popular Java IDE. If you are a current user of NetBeans and want to\nmigrate from it to IntelliJ then this will serve as a good starting point." }, { "code": null, "e": 74837, "s": 74674, "text": "This chapter discusses the importing of NetBeans projects in IntelliJ, its terminologies\nequivalent to NetBeans, popular shortcuts and frequently asked questions." }, { "code": null, "e": 74943, "s": 74837, "text": "In this section, we will learn how to import NetBeans project. Follow these steps to import\nthe project −" }, { "code": null, "e": 74998, "s": 74943, "text": "Navigate to File → New → Project from Existing Sources" }, { "code": null, "e": 75053, "s": 74998, "text": "Navigate to File → New → Project from Existing Sources" }, { "code": null, "e": 75093, "s": 75053, "text": "Select your NetBeans project directory." }, { "code": null, "e": 75133, "s": 75093, "text": "Select your NetBeans project directory." }, { "code": null, "e": 75227, "s": 75133, "text": "When the Import Project wizard opens, select the Create project from existing sources option." }, { "code": null, "e": 75321, "s": 75227, "text": "When the Import Project wizard opens, select the Create project from existing sources option." }, { "code": null, "e": 75368, "s": 75321, "text": "Follow the on-screen instructions to continue." }, { "code": null, "e": 75415, "s": 75368, "text": "Follow the on-screen instructions to continue." }, { "code": null, "e": 75480, "s": 75415, "text": "The following table compares IntelliJ and NetBeans terminology −" }, { "code": null, "e": 75617, "s": 75480, "text": "IntelliJ is a keyboard-centric IDE. It provides shortcuts for most of the actions. The\nfollowing table lists a few important shortcuts −" }, { "code": null, "e": 75685, "s": 75617, "text": "The following table lists down a few important debugger shortcuts −" }, { "code": null, "e": 75802, "s": 75685, "text": "In this section, we will go through a few Frequently Answered Questions and Tips. The\nFAQs and tips are as follows −" }, { "code": null, "e": 75850, "s": 75802, "text": "Navigate to Files → Settings and select Keymap." }, { "code": null, "e": 75898, "s": 75850, "text": "Navigate to Files → Settings and select Keymap." }, { "code": null, "e": 75937, "s": 75898, "text": "Select NetBeans from the drop down box" }, { "code": null, "e": 75976, "s": 75937, "text": "Select NetBeans from the drop down box" }, { "code": null, "e": 76201, "s": 75976, "text": "Local history in IntelliJ IDEA, generally, is more detailed. Whatever you do with a directory,\nfile, class, method or field, or a code block is reflected in your local history. The local\nhistory also includes VCS operations." }, { "code": null, "e": 76271, "s": 76201, "text": "Navigate to File → Settings → Build, Execution, Deployment → Compiler" }, { "code": null, "e": 76314, "s": 76271, "text": "Select Build Project Automatically option." }, { "code": null, "e": 76338, "s": 76314, "text": "Click on the OK button." }, { "code": null, "e": 76354, "s": 76338, "text": "No, you cannot." }, { "code": null, "e": 76510, "s": 76354, "text": "It is possible; however, you will not get the same kind of support that you get with\nNetBeans (wizards, menu actions, etc.). For more details, visit this." }, { "code": null, "e": 76665, "s": 76510, "text": "Eclipse is yet another popular Java IDE. If you are a current user of Eclipse and want to\nmigrate from it to IntelliJ, then this is a good starting point." }, { "code": null, "e": 76823, "s": 76665, "text": "This chapter discusses how to import Eclipse projects in IntelliJ, its terminologies\nequivalent to Eclipse, popular shortcuts and frequently asked questions." }, { "code": null, "e": 76934, "s": 76823, "text": "In this section, we will discuss how to import an existing project. Follow these steps to\nimport the project −" }, { "code": null, "e": 76990, "s": 76934, "text": "Navigate to File → New → Project from Existing Sources." }, { "code": null, "e": 77046, "s": 76990, "text": "Navigate to File → New → Project from Existing Sources." }, { "code": null, "e": 77086, "s": 77046, "text": "Select your NetBeans project directory." }, { "code": null, "e": 77126, "s": 77086, "text": "Select your NetBeans project directory." }, { "code": null, "e": 77220, "s": 77126, "text": "When the Import Project wizard opens, select the Create project from existing\nsources option." }, { "code": null, "e": 77314, "s": 77220, "text": "When the Import Project wizard opens, select the Create project from existing\nsources option." }, { "code": null, "e": 77361, "s": 77314, "text": "Follow the on-screen instructions to continue." }, { "code": null, "e": 77408, "s": 77361, "text": "Follow the on-screen instructions to continue." }, { "code": null, "e": 77475, "s": 77408, "text": "The following table compares IntelliJ and NetBeans terminologies −" }, { "code": null, "e": 77610, "s": 77475, "text": "IntelliJ is a keyboard-centric IDE. It provides shortcuts for most of the actions. The\nfollowing table lists a few popular shortcuts −" }, { "code": null, "e": 77676, "s": 77610, "text": "The following table lists down commonly used debugger shortcuts −" }, { "code": null, "e": 77786, "s": 77676, "text": "In this section, we will see a few Frequently Answered Questions and tips. The FAQs and\ntips are as follows −" }, { "code": null, "e": 77933, "s": 77786, "text": "While Eclipse uses its own compiler, IntelliJ IDEA uses the javac compiler bundled with the\nproject JDK. If you want to use the Eclipse compiler −" }, { "code": null, "e": 78020, "s": 77933, "text": "Navigate to File → Settings → Build, Execution, Deployment → Compiler → Java Compiler." }, { "code": null, "e": 78107, "s": 78020, "text": "Navigate to File → Settings → Build, Execution, Deployment → Compiler → Java Compiler." }, { "code": null, "e": 78165, "s": 78107, "text": "Select the required compiler from User compiler dropdown." }, { "code": null, "e": 78223, "s": 78165, "text": "Select the required compiler from User compiler dropdown." }, { "code": null, "e": 78358, "s": 78223, "text": "For Eclipse users who prefer not to learn new shortcuts, IntelliJ IDEA provides the Eclipse\nkeymap that closely mimics its shortcuts −" }, { "code": null, "e": 78403, "s": 78358, "text": "Navigate to File → Settings → Keymap option." }, { "code": null, "e": 78440, "s": 78403, "text": "Select Eclipse from Keymap dropdown." }, { "code": null, "e": 78484, "s": 78440, "text": "To import your Eclipse formatter settings −" }, { "code": null, "e": 78542, "s": 78484, "text": "Navigate to File → Settings → Editor → Code Style → Java." }, { "code": null, "e": 78600, "s": 78542, "text": "Navigate to File → Settings → Editor → Code Style → Java." }, { "code": null, "e": 78632, "s": 78600, "text": "Select the Eclipse XML profile." }, { "code": null, "e": 78664, "s": 78632, "text": "Select the Eclipse XML profile." }, { "code": null, "e": 78763, "s": 78664, "text": "Like Eclipse, IntelliJ does not provide visual forms for editing Maven/Gradle configuration\nfiles." }, { "code": null, "e": 78902, "s": 78763, "text": "Once you have imported/created your Maven/Gradle project, you are free to edit its\npom.xml/build.gradle files directly in the text editor." }, { "code": null, "e": 78909, "s": 78902, "text": " Print" }, { "code": null, "e": 78920, "s": 78909, "text": " Add Notes" } ]
EmberJS - Template Condition If
The #if statement uses a boolean expression wherein, if the Boolean expression is true, then the block of code inside the if statement will be executed; if the Boolean expression is false, then the else block will be executed. {{#if property-name}} //statement {{else}} //statement {{/if}} The example given below shows the use of the if conditional helper in Ember.js. Create a template called application.hbs under app/templates/ with the following code − {{#if check}} //true block of statement <h3> boolean value is {{check}}</h3> {{else}} //false block of statement <h3>boolean value is {{check}}</h3> {{/if}} Next, create the controller called application.js file which will be defined under app/controller/ with the following code − import Ember from 'ember'; export default Ember.Controller.extend ({ bool: true, check: function () { //returning the boolean value to the called function return this.bool; }.property('content.check'), }); Run the ember server and you will receive the following output − Print Add Notes Bookmark this page
[ { "code": null, "e": 2125, "s": 1898, "text": "The #if statement uses a boolean expression wherein, if the Boolean expression is true, then the block of code inside the if statement will be executed; if the Boolean expression is false, then the else block will be executed." }, { "code": null, "e": 2195, "s": 2125, "text": "{{#if property-name}}\n //statement\n{{else}}\n //statement\n{{/if}}\n" }, { "code": null, "e": 2363, "s": 2195, "text": "The example given below shows the use of the if conditional helper in Ember.js. Create a template called application.hbs under app/templates/ with the following code −" }, { "code": null, "e": 2535, "s": 2363, "text": "{{#if check}}\n //true block of statement\n <h3> boolean value is {{check}}</h3>\n {{else}}\n //false block of statement\n <h3>boolean value is {{check}}</h3>\n{{/if}}" }, { "code": null, "e": 2660, "s": 2535, "text": "Next, create the controller called application.js file which will be defined under app/controller/ with the following code −" }, { "code": null, "e": 2888, "s": 2660, "text": "import Ember from 'ember';\n\nexport default Ember.Controller.extend ({\n bool: true,\n check: function () {\n //returning the boolean value to the called function\n return this.bool;\n }.property('content.check'),\n});" }, { "code": null, "e": 2953, "s": 2888, "text": "Run the ember server and you will receive the following output −" }, { "code": null, "e": 2960, "s": 2953, "text": " Print" }, { "code": null, "e": 2971, "s": 2960, "text": " Add Notes" } ]
SVG <animateMotion> Element - GeeksforGeeks
31 Mar, 2022 SVG stands for Scalable Vector Graphic. It can be used to make graphics and animations like in HTML canvas. The SVG <animateMotion> element let define how an element moves along a motion path. Syntax: <animateMotion values="" dur="" repeatCount="" path="" /> Attributes: keyPoints: This attribute indicates in the range [0, 1], how far is the object along the path for each keyTimes associated values. path: This attribute defines the path of the motion. rotate: This attribute defines a rotation applied to the element animated along a path, usually to make it point in the direction of the animation. Animation Attributes: Attributes used to give animation effects, exp timing attributes, event attributes, and value attributes, etc. Global Attributes: some global attributes used like core attributes and styling attributes, etc. Example: <!DOCTYPE html><html> <body> <svg width="1200" height="1200"> <circle cx="60" cy="60" r="5" fill="green"> <animateMotion dur="10s" repeatCount="indefinite" path="M20, 60 C20, -50 180, 150 180, 60 C180-60 20, 150 20, 60 z" /> </circle> </svg></body> </html> Output: Browsers Supported: The following browsers are supported by this SVG element: Chrome Edge Firefox Safari Opera Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. HTML-SVG SVG-Element HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to update Node.js and NPM to next version ? How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ? Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 28654, "s": 28626, "text": "\n31 Mar, 2022" }, { "code": null, "e": 28762, "s": 28654, "text": "SVG stands for Scalable Vector Graphic. It can be used to make graphics and animations like in HTML canvas." }, { "code": null, "e": 28847, "s": 28762, "text": "The SVG <animateMotion> element let define how an element moves along a motion path." }, { "code": null, "e": 28855, "s": 28847, "text": "Syntax:" }, { "code": null, "e": 28913, "s": 28855, "text": "<animateMotion values=\"\" dur=\"\" repeatCount=\"\" path=\"\" />" }, { "code": null, "e": 28925, "s": 28913, "text": "Attributes:" }, { "code": null, "e": 29056, "s": 28925, "text": "keyPoints: This attribute indicates in the range [0, 1], how far is the object along the path for each keyTimes associated values." }, { "code": null, "e": 29109, "s": 29056, "text": "path: This attribute defines the path of the motion." }, { "code": null, "e": 29257, "s": 29109, "text": "rotate: This attribute defines a rotation applied to the element animated along a path, usually to make it point in the direction of the animation." }, { "code": null, "e": 29390, "s": 29257, "text": "Animation Attributes: Attributes used to give animation effects, exp timing attributes, event attributes, and value attributes, etc." }, { "code": null, "e": 29487, "s": 29390, "text": "Global Attributes: some global attributes used like core attributes and styling attributes, etc." }, { "code": null, "e": 29496, "s": 29487, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <body> <svg width=\"1200\" height=\"1200\"> <circle cx=\"60\" cy=\"60\" r=\"5\" fill=\"green\"> <animateMotion dur=\"10s\" repeatCount=\"indefinite\" path=\"M20, 60 C20, -50 180, 150 180, 60 C180-60 20, 150 20, 60 z\" /> </circle> </svg></body> </html>", "e": 29842, "s": 29496, "text": null }, { "code": null, "e": 29850, "s": 29842, "text": "Output:" }, { "code": null, "e": 29928, "s": 29850, "text": "Browsers Supported: The following browsers are supported by this SVG element:" }, { "code": null, "e": 29935, "s": 29928, "text": "Chrome" }, { "code": null, "e": 29940, "s": 29935, "text": "Edge" }, { "code": null, "e": 29948, "s": 29940, "text": "Firefox" }, { "code": null, "e": 29955, "s": 29948, "text": "Safari" }, { "code": null, "e": 29961, "s": 29955, "text": "Opera" }, { "code": null, "e": 30098, "s": 29961, "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": 30107, "s": 30098, "text": "HTML-SVG" }, { "code": null, "e": 30119, "s": 30107, "text": "SVG-Element" }, { "code": null, "e": 30124, "s": 30119, "text": "HTML" }, { "code": null, "e": 30141, "s": 30124, "text": "Web Technologies" }, { "code": null, "e": 30146, "s": 30141, "text": "HTML" }, { "code": null, "e": 30244, "s": 30146, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30253, "s": 30244, "text": "Comments" }, { "code": null, "e": 30266, "s": 30253, "text": "Old Comments" }, { "code": null, "e": 30328, "s": 30266, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 30378, "s": 30328, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 30426, "s": 30378, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 30486, "s": 30426, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 30547, "s": 30486, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 30589, "s": 30547, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 30622, "s": 30589, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 30665, "s": 30622, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 30727, "s": 30665, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
Tryit Editor v3.7
CSS Style Images Tryit: Place text in top-left corner of an image
[ { "code": null, "e": 26, "s": 9, "text": "CSS Style Images" } ]
Arduino - LED Bar Graph
This example shows you how to read an analog input at analog pin 0, convert the values from analogRead() into voltage, and print it out to the serial monitor of the Arduino Software (IDE). You will need the following components − 1 × Breadboard 1 × Arduino Uno R3 1 × 5k ohm variable resistor (potentiometer) 2 × Jumper 8 × LED or you can use (LED bar graph display as shown in the image below) Follow the circuit diagram and hook up the components on the breadboard as shown in the image given below. Open the Arduino IDE software on your computer. Coding in the Arduino language will control your circuit. Open a new sketch File by clicking New. These 10-segment bar graph LEDs have many uses. With a compact footprint, simple hookup, they are easy for prototype or finished products. Essentially, they are 10 individual blue LEDs housed together, each with an individual anode and cathode connection. They are also available in yellow, red, and green colors. Note − The pin out on these bar graphs may vary from what is listed on the datasheet. Rotating the device 180 degrees will correct the change, making pin 11 the first pin in line. /* LED bar graph Turns on a series of LEDs based on the value of an analog sensor. This is a simple way to make a bar graph display. Though this graph uses 8LEDs, you can use any number by changing the LED count and the pins in the array. This method can be used to control any series of digital outputs that depends on an analog input. */ // these constants won't change: const int analogPin = A0; // the pin that the potentiometer is attached to const int ledCount = 8; // the number of LEDs in the bar graph int ledPins[] = {2, 3, 4, 5, 6, 7, 8, 9}; // an array of pin numbers to which LEDs are attached void setup() { // loop over the pin array and set them all to output: for (int thisLed = 0; thisLed < ledCount; thisLed++) { pinMode(ledPins[thisLed], OUTPUT); } } void loop() { // read the potentiometer: int sensorReading = analogRead(analogPin); // map the result to a range from 0 to the number of LEDs: int ledLevel = map(sensorReading, 0, 1023, 0, ledCount); // loop over the LED array: for (int thisLed = 0; thisLed < ledCount; thisLed++) { // if the array element's index is less than ledLevel, // turn the pin for this element on: if (thisLed < ledLevel) { digitalWrite(ledPins[thisLed], HIGH); }else { // turn off all pins higher than the ledLevel: digitalWrite(ledPins[thisLed], LOW); } } } The sketch works like this: first, you read the input. You map the input value to the output range, in this case ten LEDs. Then you set up a for-loop to iterate over the outputs. If the output's number in the series is lower than the mapped input range, you turn it on. If not, you turn it off. You will see the LED turn ON one by one when the value of analog reading increases and turn OFF one by one while the reading is decreasing. 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": 3059, "s": 2870, "text": "This example shows you how to read an analog input at analog pin 0, convert the values from analogRead() into voltage, and print it out to the serial monitor of the Arduino Software (IDE)." }, { "code": null, "e": 3100, "s": 3059, "text": "You will need the following components −" }, { "code": null, "e": 3115, "s": 3100, "text": "1 × Breadboard" }, { "code": null, "e": 3134, "s": 3115, "text": "1 × Arduino Uno R3" }, { "code": null, "e": 3179, "s": 3134, "text": "1 × 5k ohm variable resistor (potentiometer)" }, { "code": null, "e": 3190, "s": 3179, "text": "2 × Jumper" }, { "code": null, "e": 3265, "s": 3190, "text": "8 × LED or you can use (LED bar graph display as shown in the image below)" }, { "code": null, "e": 3372, "s": 3265, "text": "Follow the circuit diagram and hook up the components on the breadboard as shown in the image given below." }, { "code": null, "e": 3518, "s": 3372, "text": "Open the Arduino IDE software on your computer. Coding in the Arduino language will control your circuit. Open a new sketch File by clicking New." }, { "code": null, "e": 3774, "s": 3518, "text": "These 10-segment bar graph LEDs have many uses. With a compact footprint, simple hookup, they are easy for prototype or finished products. Essentially, they are 10 individual blue LEDs housed together, each with an individual anode and cathode connection." }, { "code": null, "e": 3832, "s": 3774, "text": "They are also available in yellow, red, and green colors." }, { "code": null, "e": 4012, "s": 3832, "text": "Note − The pin out on these bar graphs may vary from what is listed on the datasheet. Rotating the device 180 degrees will correct the change, making pin 11 the first pin in line." }, { "code": null, "e": 5437, "s": 4012, "text": "/*\n LED bar graph\n Turns on a series of LEDs based on the value of an analog sensor. \n This is a simple way to make a bar graph display. \n Though this graph uses 8LEDs, you can use any number by\n changing the LED count and the pins in the array.\n This method can be used to control any series of digital\n outputs that depends on an analog input.\n*/\n\n// these constants won't change:\nconst int analogPin = A0; // the pin that the potentiometer is attached to\nconst int ledCount = 8; // the number of LEDs in the bar graph\nint ledPins[] = {2, 3, 4, 5, 6, 7, 8, 9}; // an array of pin numbers to which LEDs are attached\n\nvoid setup() {\n // loop over the pin array and set them all to output:\n for (int thisLed = 0; thisLed < ledCount; thisLed++) {\n pinMode(ledPins[thisLed], OUTPUT);\n }\n}\n\nvoid loop() {\n // read the potentiometer:\n int sensorReading = analogRead(analogPin);\n // map the result to a range from 0 to the number of LEDs:\n int ledLevel = map(sensorReading, 0, 1023, 0, ledCount);\n // loop over the LED array:\n for (int thisLed = 0; thisLed < ledCount; thisLed++) {\n // if the array element's index is less than ledLevel,\n // turn the pin for this element on:\n if (thisLed < ledLevel) {\n digitalWrite(ledPins[thisLed], HIGH);\n }else { // turn off all pins higher than the ledLevel:\n digitalWrite(ledPins[thisLed], LOW);\n }\n }\n} " }, { "code": null, "e": 5732, "s": 5437, "text": "The sketch works like this: first, you read the input. You map the input value to the output range, in this case ten LEDs. Then you set up a for-loop to iterate over the outputs. If the output's number in the series is lower than the mapped input range, you turn it on. If not, you turn it off." }, { "code": null, "e": 5872, "s": 5732, "text": "You will see the LED turn ON one by one when the value of analog reading increases and turn OFF one by one while the reading is decreasing." }, { "code": null, "e": 5907, "s": 5872, "text": "\n 65 Lectures \n 6.5 hours \n" }, { "code": null, "e": 5918, "s": 5907, "text": " Amit Rana" }, { "code": null, "e": 5951, "s": 5918, "text": "\n 43 Lectures \n 3 hours \n" }, { "code": null, "e": 5962, "s": 5951, "text": " Amit Rana" }, { "code": null, "e": 5995, "s": 5962, "text": "\n 20 Lectures \n 2 hours \n" }, { "code": null, "e": 6008, "s": 5995, "text": " Ashraf Said" }, { "code": null, "e": 6043, "s": 6008, "text": "\n 19 Lectures \n 1.5 hours \n" }, { "code": null, "e": 6056, "s": 6043, "text": " Ashraf Said" }, { "code": null, "e": 6088, "s": 6056, "text": "\n 11 Lectures \n 47 mins\n" }, { "code": null, "e": 6101, "s": 6088, "text": " Ashraf Said" }, { "code": null, "e": 6132, "s": 6101, "text": "\n 9 Lectures \n 41 mins\n" }, { "code": null, "e": 6145, "s": 6132, "text": " Ashraf Said" }, { "code": null, "e": 6152, "s": 6145, "text": " Print" }, { "code": null, "e": 6163, "s": 6152, "text": " Add Notes" } ]
JSTL - Core <c:import> Tag
The <c:import> tag provides all functionalities of the <include> action but also allows for the inclusion of absolute URLs. For example, using the import tag allows for the inclusion of content from a different Website or an FTP server. The <c:import> tag has the following attributes − <%@ taglib uri = "http://java.sun.com/jsp/jstl/core" prefix = "c" %> <html> <head> <title><c:import> Tag Example</title> </head> <body> <c:import var = "data" url = "http://www.tutorialspoint.com"/> <c:out value = "${data}"/> </body> </html> The above example will fetch complete content from tutorialspoint.com/index.htm and will store in variable data which will be printed eventually. Try it yourself. 108 Lectures 11 hours Chaand Sheikh 517 Lectures 57 hours Chaand Sheikh 41 Lectures 4.5 hours Karthikeya T 42 Lectures 5.5 hours TELCOMA Global 15 Lectures 3 hours TELCOMA Global 44 Lectures 15 hours Uplatz Print Add Notes Bookmark this page
[ { "code": null, "e": 2363, "s": 2239, "text": "The <c:import> tag provides all functionalities of the <include> action but also allows for the inclusion of absolute URLs." }, { "code": null, "e": 2476, "s": 2363, "text": "For example, using the import tag allows for the inclusion of content from a different Website or an FTP server." }, { "code": null, "e": 2526, "s": 2476, "text": "The <c:import> tag has the following attributes −" }, { "code": null, "e": 2800, "s": 2526, "text": "<%@ taglib uri = \"http://java.sun.com/jsp/jstl/core\" prefix = \"c\" %>\n\n<html>\n <head>\n <title><c:import> Tag Example</title>\n </head>\n\n <body>\n <c:import var = \"data\" url = \"http://www.tutorialspoint.com\"/>\n <c:out value = \"${data}\"/>\n </body>\n</html>" }, { "code": null, "e": 2963, "s": 2800, "text": "The above example will fetch complete content from tutorialspoint.com/index.htm and will store in variable data which will be printed eventually. Try it yourself." }, { "code": null, "e": 2998, "s": 2963, "text": "\n 108 Lectures \n 11 hours \n" }, { "code": null, "e": 3013, "s": 2998, "text": " Chaand Sheikh" }, { "code": null, "e": 3048, "s": 3013, "text": "\n 517 Lectures \n 57 hours \n" }, { "code": null, "e": 3063, "s": 3048, "text": " Chaand Sheikh" }, { "code": null, "e": 3098, "s": 3063, "text": "\n 41 Lectures \n 4.5 hours \n" }, { "code": null, "e": 3112, "s": 3098, "text": " Karthikeya T" }, { "code": null, "e": 3147, "s": 3112, "text": "\n 42 Lectures \n 5.5 hours \n" }, { "code": null, "e": 3163, "s": 3147, "text": " TELCOMA Global" }, { "code": null, "e": 3196, "s": 3163, "text": "\n 15 Lectures \n 3 hours \n" }, { "code": null, "e": 3212, "s": 3196, "text": " TELCOMA Global" }, { "code": null, "e": 3246, "s": 3212, "text": "\n 44 Lectures \n 15 hours \n" }, { "code": null, "e": 3254, "s": 3246, "text": " Uplatz" }, { "code": null, "e": 3261, "s": 3254, "text": " Print" }, { "code": null, "e": 3272, "s": 3261, "text": " Add Notes" } ]
OpenPose Research Paper Summary: Multi-Person 2D Pose Estimation with Deep Learning | by Chonyy | Towards Data Science
This paper summary will give you a good understanding of the high-level concept of OpenPose. Since we will be focusing on their creative pipeline and structure, there will be no difficult math or theory included in this summary. I would like to start by talking about why I want to share what I learn from this wonderful paper. I have implemented the OpenPose library in my AI Basketball Analysis project. At the time I was building the project, I only knew the basic concept of OpenPose. I spent most of the time working on the code implementation and trying to figure out the best way to combine OpenPose with my original basketball shot detection. Now, as you can see in the GIF, the project is almost completed. I have a full grasp of the implementation of OpenPose after building this project. In order to have a better understanding of what I have been dealing with, I think now it’s time for me to take a deeper look at the research paper. In this work, we present a realtime approach to detect the 2D pose of multiple people in an image. The proposed method uses a nonparametric representation, which we refer to as Part Affinity Fields (PAFs), to learn to associate body parts with individuals in the image. This bottom-up system achieves high accuracy and realtime performance, regardless of the number of people in the image. Let’s start by talking about what makes estimating the poses of multi-person in an image so difficult. Here are some difficulties listed. Unknown number of people People can appear at any pose or scale People contact and overlapping Runtime complexity grows with the number of people OpenPose is definitely not the first team facing this challenge. Then how the other teams try to tackle these problems? A common approach is to employ a person detector and perform single-person pose estimation for each detection. This kind of top-down method sounds really intuitive and simple. However, there are some hidden pitfalls in this approach. Early commitment: no resource to recovery when person detector fails Runtime proportional to the number of people Pose estimation is executed even if the person detector fails If the top-down method doesn’t sound like the best approach. Then why don’t we try bottom-up? Not surprisingly, OpenPose is not the first team that came up with a bottom-up method. Some other teams have also tried the bottom-up approach. However, they are still facing some problems with it. Required costly global inference at the final parse Didn’t retain the gains in efficiency Taking several minutes per image (a) Take the entire image as the input for a CNN(b) Predict confidence maps for body parts detection(c) Predict PAFs for part association(d) Perform a set of bipartite matching(e) Assemble into a full body pose Confidence map is the 2D representation of the belief that a particular body part can be located​. A single body part will be represented on a single map. So, the number of maps is the same as the total number of the body parts. Part Affinity Fields (PAFs), a set of 2D vector fields that encode the location and orientation of limbs over the image domain. When it comes to finding the full body pose of multiple people, determining Z is a K-dimensional matching problem. This problem is NP-Hard and many relaxations exist. In this work, we add two relaxations to the optimization, specialized to our domain. Relaxation 1: Choose a minimal number of edges to obtain a spanning tree skeleton. Relaxation 2: Further decompose the matching problem into a set of bipartite matching subproblems. Determine the matching in adjacent tree nodes independently. The original structure is split into two branches. Beige branch: predicts the confidence map Blue branch: predicts the PAF Both branches are organized as an iterative prediction architecture. The predictions from the previous stage are concatenated with the original feature F to produce more refined predictions. The first set of stages predicts PAFs L t , while the last set predicts confidence maps S t . The predictions of each stage and their corresponding image features are concatenated for each subsequent stage. Comparing to their previous publication, they have made a big breakthrough and came up with a new structure. As you can see from the structure above, the confidence map prediction is runned on top of the most refined PAF predictions. Why? The reason is actually really simple. Intuitively, if we look at the PAF channel output, the body part locations can be guessed. A growing number of computer vision and machine learning applications require 2D human pose estimation as an input for their systems. The OpenPose’s team is definitely not the only one doing this research. Then why we always think of OpenPose when it comes to pose estimation and not Alpha-Pose? Here are some of the problems with other libraries. Require users to implement most of the pipeline Users have to construct their won frame reader Facial and body keypoint detector are not combined I have implemented OpenPose in this AI Basketball Analysis project. In the beginning, I only have an idea that I want to analyze the shooting pose of the shooter, but I have no clue how to do it! Luckily, I came across OpenPose, which gives me everything I want. Although the installation process is a little troublesome, the actual code implementation is fairly simple. Their function takes a frame as an input, and output the human coordinate. What’s even better, it could also show the detection overlay on the frame! The simplicity of the code implementation is the main reason why their repo could obatin18.6k+ stars on GitHub. My project is below, feel free to check it out! github.com [1] Zhe Cao, Student Member, IEEE, Gines Hidalgo, Student Member, IEEE, Tomas Simon, Shih-En Wei, and Yaser Sheikh, “OpenPose: Realtime Multi-Person 2D Pose Estimation using Part Affinity Fields,” in CVPR, 2019.
[ { "code": null, "e": 401, "s": 172, "text": "This paper summary will give you a good understanding of the high-level concept of OpenPose. Since we will be focusing on their creative pipeline and structure, there will be no difficult math or theory included in this summary." }, { "code": null, "e": 823, "s": 401, "text": "I would like to start by talking about why I want to share what I learn from this wonderful paper. I have implemented the OpenPose library in my AI Basketball Analysis project. At the time I was building the project, I only knew the basic concept of OpenPose. I spent most of the time working on the code implementation and trying to figure out the best way to combine OpenPose with my original basketball shot detection." }, { "code": null, "e": 1119, "s": 823, "text": "Now, as you can see in the GIF, the project is almost completed. I have a full grasp of the implementation of OpenPose after building this project. In order to have a better understanding of what I have been dealing with, I think now it’s time for me to take a deeper look at the research paper." }, { "code": null, "e": 1218, "s": 1119, "text": "In this work, we present a realtime approach to detect the 2D pose of multiple people in an image." }, { "code": null, "e": 1509, "s": 1218, "text": "The proposed method uses a nonparametric representation, which we refer to as Part Affinity Fields (PAFs), to learn to associate body parts with individuals in the image. This bottom-up system achieves high accuracy and realtime performance, regardless of the number of people in the image." }, { "code": null, "e": 1647, "s": 1509, "text": "Let’s start by talking about what makes estimating the poses of multi-person in an image so difficult. Here are some difficulties listed." }, { "code": null, "e": 1672, "s": 1647, "text": "Unknown number of people" }, { "code": null, "e": 1711, "s": 1672, "text": "People can appear at any pose or scale" }, { "code": null, "e": 1742, "s": 1711, "text": "People contact and overlapping" }, { "code": null, "e": 1793, "s": 1742, "text": "Runtime complexity grows with the number of people" }, { "code": null, "e": 1913, "s": 1793, "text": "OpenPose is definitely not the first team facing this challenge. Then how the other teams try to tackle these problems?" }, { "code": null, "e": 2024, "s": 1913, "text": "A common approach is to employ a person detector and perform single-person pose estimation for each detection." }, { "code": null, "e": 2147, "s": 2024, "text": "This kind of top-down method sounds really intuitive and simple. However, there are some hidden pitfalls in this approach." }, { "code": null, "e": 2216, "s": 2147, "text": "Early commitment: no resource to recovery when person detector fails" }, { "code": null, "e": 2261, "s": 2216, "text": "Runtime proportional to the number of people" }, { "code": null, "e": 2323, "s": 2261, "text": "Pose estimation is executed even if the person detector fails" }, { "code": null, "e": 2417, "s": 2323, "text": "If the top-down method doesn’t sound like the best approach. Then why don’t we try bottom-up?" }, { "code": null, "e": 2615, "s": 2417, "text": "Not surprisingly, OpenPose is not the first team that came up with a bottom-up method. Some other teams have also tried the bottom-up approach. However, they are still facing some problems with it." }, { "code": null, "e": 2667, "s": 2615, "text": "Required costly global inference at the final parse" }, { "code": null, "e": 2705, "s": 2667, "text": "Didn’t retain the gains in efficiency" }, { "code": null, "e": 2738, "s": 2705, "text": "Taking several minutes per image" }, { "code": null, "e": 2950, "s": 2738, "text": "(a) Take the entire image as the input for a CNN(b) Predict confidence maps for body parts detection(c) Predict PAFs for part association(d) Perform a set of bipartite matching(e) Assemble into a full body pose " }, { "code": null, "e": 3179, "s": 2950, "text": "Confidence map is the 2D representation of the belief that a particular body part can be located​. A single body part will be represented on a single map. So, the number of maps is the same as the total number of the body parts." }, { "code": null, "e": 3307, "s": 3179, "text": "Part Affinity Fields (PAFs), a set of 2D vector fields that encode the location and orientation of limbs over the image domain." }, { "code": null, "e": 3559, "s": 3307, "text": "When it comes to finding the full body pose of multiple people, determining Z is a K-dimensional matching problem. This problem is NP-Hard and many relaxations exist. In this work, we add two relaxations to the optimization, specialized to our domain." }, { "code": null, "e": 3642, "s": 3559, "text": "Relaxation 1: Choose a minimal number of edges to obtain a spanning tree skeleton." }, { "code": null, "e": 3802, "s": 3642, "text": "Relaxation 2: Further decompose the matching problem into a set of bipartite matching subproblems. Determine the matching in adjacent tree nodes independently." }, { "code": null, "e": 3853, "s": 3802, "text": "The original structure is split into two branches." }, { "code": null, "e": 3895, "s": 3853, "text": "Beige branch: predicts the confidence map" }, { "code": null, "e": 3925, "s": 3895, "text": "Blue branch: predicts the PAF" }, { "code": null, "e": 4116, "s": 3925, "text": "Both branches are organized as an iterative prediction architecture. The predictions from the previous stage are concatenated with the original feature F to produce more refined predictions." }, { "code": null, "e": 4323, "s": 4116, "text": "The first set of stages predicts PAFs L t , while the last set predicts confidence maps S t . The predictions of each stage and their corresponding image features are concatenated for each subsequent stage." }, { "code": null, "e": 4557, "s": 4323, "text": "Comparing to their previous publication, they have made a big breakthrough and came up with a new structure. As you can see from the structure above, the confidence map prediction is runned on top of the most refined PAF predictions." }, { "code": null, "e": 4600, "s": 4557, "text": "Why? The reason is actually really simple." }, { "code": null, "e": 4691, "s": 4600, "text": "Intuitively, if we look at the PAF channel output, the body part locations can be guessed." }, { "code": null, "e": 5039, "s": 4691, "text": "A growing number of computer vision and machine learning applications require 2D human pose estimation as an input for their systems. The OpenPose’s team is definitely not the only one doing this research. Then why we always think of OpenPose when it comes to pose estimation and not Alpha-Pose? Here are some of the problems with other libraries." }, { "code": null, "e": 5087, "s": 5039, "text": "Require users to implement most of the pipeline" }, { "code": null, "e": 5134, "s": 5087, "text": "Users have to construct their won frame reader" }, { "code": null, "e": 5185, "s": 5134, "text": "Facial and body keypoint detector are not combined" }, { "code": null, "e": 5448, "s": 5185, "text": "I have implemented OpenPose in this AI Basketball Analysis project. In the beginning, I only have an idea that I want to analyze the shooting pose of the shooter, but I have no clue how to do it! Luckily, I came across OpenPose, which gives me everything I want." }, { "code": null, "e": 5818, "s": 5448, "text": "Although the installation process is a little troublesome, the actual code implementation is fairly simple. Their function takes a frame as an input, and output the human coordinate. What’s even better, it could also show the detection overlay on the frame! The simplicity of the code implementation is the main reason why their repo could obatin18.6k+ stars on GitHub." }, { "code": null, "e": 5866, "s": 5818, "text": "My project is below, feel free to check it out!" }, { "code": null, "e": 5877, "s": 5866, "text": "github.com" } ]
Jupyter Notebook Without Code — The Mito Way | by Yong Cui | Towards Data Science
The first comprehensive statistical analysis software that I used was SAS, and it wasn’t easy to get it started with SAS, because it has its own syntax that I had to learn before I was able to do anything with it. Certainly, after I learned it, it became pretty handy, because you can re-use the code in your projects. Later, I came across SPSS, another kind of commonly used statistical software. This software is basically point-and-click, and you do your data processing and analysis in a GUI. One particularly useful feature is the automatic creation of the script based on the operations that you’ve done. With the generated script, you can simply apply it to other similarly structured datasets. For beginners, it seems easier to pick up SPSS, because point-and-click is more intuitive compared to writing code in SAS, particularly if you don’t have any programming experience. The last several paragraphs are the thoughts that came to my mind when I first encountered mito, which is a Jupyter-based tool that prepares and presents your data using a point-and-click approach. Just like SPSS, it can generate the code based on the operations that you’ve done. Thus, maybe for data science beginners with less code experience, mito is a good place to start with. Wait a second. What does mito do exactly? Let’s explore it in this article. Before you jump into this tutorial, let’s assume the following things such that we’re on the same page. Have already installed Python on your computer. Please also make sure your Python’s version is 3.6+. In your terminal, you can check it using: python — version. Have experience using Jupyter Notebook. For a better notebook experience, please also make sure you install jupyter lab. Know how to set up a virtual environment. A good tool is conda, and see my article for its instruction. In the terminal, enter the following command to install the installer. python -m pip install mitoinstaller Then, you can use the installer to install the mito library by running: python -m mitoinstaller install In the terminal, after activating the desired virtual environment, you can launch jupyter lab by running jupyter lab. You’ll see that the jupyter server is running in your default web browser. Create a notebook and in the cell, enter the following lines of code, which will create a mito sheet for you. import mitosheetmitosheet.sheet() Please note that you’ll have to sign up using your email before you can proceed. You’ll then be prompted to choose a file to import. For this tutorial, let’s use the mpg dataset that is available as part of the seaborn’s datasets. After the import, you’ll see the sheet-like below. One thing that is useful is that the shape of the dataset is shown in the right corner at the bottom. So you’ll have a reasonable idea whether the import of the file is correct. As you can tell, the overall appearance of this sheet is very clean. Personally, I like the font and its size, and they’re just pleasing to the eyes. As mentioned at the beginning, mito has the capability of automatically generating code for the step you’ve just done. So after importing the dataset, you’ll see a cell with the code appear below the current cell. Everything should be straightforward because mito not only generates the code, it also annotates the code such that it’s clear to those who’re not familiar with Python or pandas. The first thing that you can do is to explore your data. Particularly, you can take a quick look at your data column-wise. As shown in the animated image above, after you select a column, the data explorer is shown. There are three tabs. Filter/Sort: you can filter your data by specifying a series of criteria, and you can sort the data as needed. Value: it shows the frequency table, so you can have an idea about what values are available and their frequency. Summary Stats: the histogram is pretty handy, as it provides an intuitive overview in terms of data distribution. Following that, you’ll see the summary In the animation, you may notice that we sort the data using the mpg column. This operation resulted in additional lines of code, which accounted for these operations and were added to the cell. So far, we’ve done several steps in manipulating the dataset. One useful way to know where you’re is to view the steps by clicking the “STEPS” button on the right side. The following diagram will be shown to illustrate the steps. A useful feature of mito is that you can clear these steps and undo/redo your steps very easily. As you can notice, there are different buttons at the top: UNDO, REDO, and CLEAR. For instance, if you click “CLEAR”, you’ll see that the steps that we’ve done will be removed from the history. You can also delete previous steps separately if you want to just undo several steps. For many beginners, creating the pivot table isn’t the most straightforward in Pandas, because the parameters aren’t too clear. Fortunately, it appears to be easier with mito — the following screenshot shows you such operation. As you can see, mito uses different terminologies than pandas. In essence, it uses rows and columns to represent the created pivot table such that you can visualize your pivot table first and then specify the needed data. The following code snippet shows you the corresponding Python code. You can tell that it’s more intuitive with the mito approach. pivot_table = tmp_df.pivot_table( index=['model_year'], columns=['origin'], values=['mpg'], aggfunc={'mpg': ['mean']}) You can also intuitively merge DataFrames with mito by clicking the “MERGE” button. In the menu, you can specify what tables you want to merge. The common merge types are supported, as shown in the screenshot below. After you specify the two tables, you can specify the key upon which they merge. However, I do notice a limitation here, because you can only specify one key for each table. If I’m not mistaken and if you want to use multiple keys, it doesn’t appear to support this feature now. You can also create graphs using mito, although the supported graphs look limited now. As you can see, you can only create bar, box, histogram, and scatter with mito for now. One thing that is different from the previous steps is that the code creating the graph isn’t automatically included in the cell. For your convenience, I’ve copied the code for you. # Import plotly and create a figureimport plotly.graph_objects as gofig = go.Figure()# Add box plots to the graphfor column_header in ['mpg', 'horsepower']: fig.add_trace(go.Box(y=mpg_csv[column_header], name=column_header))# Update the title and stacking mode of the graph# See Plotly documentation for customizations: https://plotly.com/python/reference/box/fig.update_layout( title='mpg, horsepower box plot', barmode='stack')fig.show(renderer="iframe") As you can see, mito uses the plotly as its drawing backend. In many situations, we need to repeat our processing steps. Mito made it possible too. You’ll simply save your analysis by clicking “SAVE” button at the top. When you need to re-run the analysis with a different dataset, just click “REPLAY”, where you can start to re-do the analysis. Besides the above operations, you can also add and remove columns, which should be very straightforward to you without my showing you these operations. That’s pretty much a review of this mito tool. In my opinion, the mito library seems a growing tool that is still under development. The developers seem diligent and are working on it to make a better tool for those who’re less coding-savvy. With that said, it may be useful for those who are new to Python or Pandas. However, I doubt the long-term use of this tool, because so far, all these operations don’t really require sophisticated coding skills. In other words, mito is trying to address something that isn’t too hard to code so most people can learn to code to solve these issues without the significant time investment. Relatedly, another thing that the developers of the mito team may consider is that if the users already know to install Python and Jupyter Notebook, they are probably relatively savvy with Python and Pandas programming. With that level of coding skills, they should already be familiar with the operations that mito has to offer at this stage. In other words, the target audience of mito seems unclear. Nevertheless, I appreciate that the developers have made great efforts to put together this GUI tool to advance the data science field. Thanks for reading this article. Stay connected by signing up my newsletter. Not a Medium member yet? Support my writing by using my membership link.
[ { "code": null, "e": 491, "s": 172, "text": "The first comprehensive statistical analysis software that I used was SAS, and it wasn’t easy to get it started with SAS, because it has its own syntax that I had to learn before I was able to do anything with it. Certainly, after I learned it, it became pretty handy, because you can re-use the code in your projects." }, { "code": null, "e": 874, "s": 491, "text": "Later, I came across SPSS, another kind of commonly used statistical software. This software is basically point-and-click, and you do your data processing and analysis in a GUI. One particularly useful feature is the automatic creation of the script based on the operations that you’ve done. With the generated script, you can simply apply it to other similarly structured datasets." }, { "code": null, "e": 1056, "s": 874, "text": "For beginners, it seems easier to pick up SPSS, because point-and-click is more intuitive compared to writing code in SAS, particularly if you don’t have any programming experience." }, { "code": null, "e": 1439, "s": 1056, "text": "The last several paragraphs are the thoughts that came to my mind when I first encountered mito, which is a Jupyter-based tool that prepares and presents your data using a point-and-click approach. Just like SPSS, it can generate the code based on the operations that you’ve done. Thus, maybe for data science beginners with less code experience, mito is a good place to start with." }, { "code": null, "e": 1515, "s": 1439, "text": "Wait a second. What does mito do exactly? Let’s explore it in this article." }, { "code": null, "e": 1619, "s": 1515, "text": "Before you jump into this tutorial, let’s assume the following things such that we’re on the same page." }, { "code": null, "e": 1780, "s": 1619, "text": "Have already installed Python on your computer. Please also make sure your Python’s version is 3.6+. In your terminal, you can check it using: python — version." }, { "code": null, "e": 1901, "s": 1780, "text": "Have experience using Jupyter Notebook. For a better notebook experience, please also make sure you install jupyter lab." }, { "code": null, "e": 2005, "s": 1901, "text": "Know how to set up a virtual environment. A good tool is conda, and see my article for its instruction." }, { "code": null, "e": 2076, "s": 2005, "text": "In the terminal, enter the following command to install the installer." }, { "code": null, "e": 2112, "s": 2076, "text": "python -m pip install mitoinstaller" }, { "code": null, "e": 2184, "s": 2112, "text": "Then, you can use the installer to install the mito library by running:" }, { "code": null, "e": 2216, "s": 2184, "text": "python -m mitoinstaller install" }, { "code": null, "e": 2409, "s": 2216, "text": "In the terminal, after activating the desired virtual environment, you can launch jupyter lab by running jupyter lab. You’ll see that the jupyter server is running in your default web browser." }, { "code": null, "e": 2519, "s": 2409, "text": "Create a notebook and in the cell, enter the following lines of code, which will create a mito sheet for you." }, { "code": null, "e": 2553, "s": 2519, "text": "import mitosheetmitosheet.sheet()" }, { "code": null, "e": 3013, "s": 2553, "text": "Please note that you’ll have to sign up using your email before you can proceed. You’ll then be prompted to choose a file to import. For this tutorial, let’s use the mpg dataset that is available as part of the seaborn’s datasets. After the import, you’ll see the sheet-like below. One thing that is useful is that the shape of the dataset is shown in the right corner at the bottom. So you’ll have a reasonable idea whether the import of the file is correct." }, { "code": null, "e": 3163, "s": 3013, "text": "As you can tell, the overall appearance of this sheet is very clean. Personally, I like the font and its size, and they’re just pleasing to the eyes." }, { "code": null, "e": 3377, "s": 3163, "text": "As mentioned at the beginning, mito has the capability of automatically generating code for the step you’ve just done. So after importing the dataset, you’ll see a cell with the code appear below the current cell." }, { "code": null, "e": 3556, "s": 3377, "text": "Everything should be straightforward because mito not only generates the code, it also annotates the code such that it’s clear to those who’re not familiar with Python or pandas." }, { "code": null, "e": 3679, "s": 3556, "text": "The first thing that you can do is to explore your data. Particularly, you can take a quick look at your data column-wise." }, { "code": null, "e": 3794, "s": 3679, "text": "As shown in the animated image above, after you select a column, the data explorer is shown. There are three tabs." }, { "code": null, "e": 3905, "s": 3794, "text": "Filter/Sort: you can filter your data by specifying a series of criteria, and you can sort the data as needed." }, { "code": null, "e": 4019, "s": 3905, "text": "Value: it shows the frequency table, so you can have an idea about what values are available and their frequency." }, { "code": null, "e": 4172, "s": 4019, "text": "Summary Stats: the histogram is pretty handy, as it provides an intuitive overview in terms of data distribution. Following that, you’ll see the summary" }, { "code": null, "e": 4367, "s": 4172, "text": "In the animation, you may notice that we sort the data using the mpg column. This operation resulted in additional lines of code, which accounted for these operations and were added to the cell." }, { "code": null, "e": 4597, "s": 4367, "text": "So far, we’ve done several steps in manipulating the dataset. One useful way to know where you’re is to view the steps by clicking the “STEPS” button on the right side. The following diagram will be shown to illustrate the steps." }, { "code": null, "e": 4974, "s": 4597, "text": "A useful feature of mito is that you can clear these steps and undo/redo your steps very easily. As you can notice, there are different buttons at the top: UNDO, REDO, and CLEAR. For instance, if you click “CLEAR”, you’ll see that the steps that we’ve done will be removed from the history. You can also delete previous steps separately if you want to just undo several steps." }, { "code": null, "e": 5202, "s": 4974, "text": "For many beginners, creating the pivot table isn’t the most straightforward in Pandas, because the parameters aren’t too clear. Fortunately, it appears to be easier with mito — the following screenshot shows you such operation." }, { "code": null, "e": 5554, "s": 5202, "text": "As you can see, mito uses different terminologies than pandas. In essence, it uses rows and columns to represent the created pivot table such that you can visualize your pivot table first and then specify the needed data. The following code snippet shows you the corresponding Python code. You can tell that it’s more intuitive with the mito approach." }, { "code": null, "e": 5685, "s": 5554, "text": "pivot_table = tmp_df.pivot_table( index=['model_year'], columns=['origin'], values=['mpg'], aggfunc={'mpg': ['mean']})" }, { "code": null, "e": 5901, "s": 5685, "text": "You can also intuitively merge DataFrames with mito by clicking the “MERGE” button. In the menu, you can specify what tables you want to merge. The common merge types are supported, as shown in the screenshot below." }, { "code": null, "e": 6180, "s": 5901, "text": "After you specify the two tables, you can specify the key upon which they merge. However, I do notice a limitation here, because you can only specify one key for each table. If I’m not mistaken and if you want to use multiple keys, it doesn’t appear to support this feature now." }, { "code": null, "e": 6267, "s": 6180, "text": "You can also create graphs using mito, although the supported graphs look limited now." }, { "code": null, "e": 6537, "s": 6267, "text": "As you can see, you can only create bar, box, histogram, and scatter with mito for now. One thing that is different from the previous steps is that the code creating the graph isn’t automatically included in the cell. For your convenience, I’ve copied the code for you." }, { "code": null, "e": 7003, "s": 6537, "text": "# Import plotly and create a figureimport plotly.graph_objects as gofig = go.Figure()# Add box plots to the graphfor column_header in ['mpg', 'horsepower']: fig.add_trace(go.Box(y=mpg_csv[column_header], name=column_header))# Update the title and stacking mode of the graph# See Plotly documentation for customizations: https://plotly.com/python/reference/box/fig.update_layout( title='mpg, horsepower box plot', barmode='stack')fig.show(renderer=\"iframe\")" }, { "code": null, "e": 7064, "s": 7003, "text": "As you can see, mito uses the plotly as its drawing backend." }, { "code": null, "e": 7349, "s": 7064, "text": "In many situations, we need to repeat our processing steps. Mito made it possible too. You’ll simply save your analysis by clicking “SAVE” button at the top. When you need to re-run the analysis with a different dataset, just click “REPLAY”, where you can start to re-do the analysis." }, { "code": null, "e": 7548, "s": 7349, "text": "Besides the above operations, you can also add and remove columns, which should be very straightforward to you without my showing you these operations. That’s pretty much a review of this mito tool." }, { "code": null, "e": 8131, "s": 7548, "text": "In my opinion, the mito library seems a growing tool that is still under development. The developers seem diligent and are working on it to make a better tool for those who’re less coding-savvy. With that said, it may be useful for those who are new to Python or Pandas. However, I doubt the long-term use of this tool, because so far, all these operations don’t really require sophisticated coding skills. In other words, mito is trying to address something that isn’t too hard to code so most people can learn to code to solve these issues without the significant time investment." }, { "code": null, "e": 8534, "s": 8131, "text": "Relatedly, another thing that the developers of the mito team may consider is that if the users already know to install Python and Jupyter Notebook, they are probably relatively savvy with Python and Pandas programming. With that level of coding skills, they should already be familiar with the operations that mito has to offer at this stage. In other words, the target audience of mito seems unclear." }, { "code": null, "e": 8670, "s": 8534, "text": "Nevertheless, I appreciate that the developers have made great efforts to put together this GUI tool to advance the data science field." } ]
Mann Whitney U Test in R Programming - GeeksforGeeks
28 Dec, 2021 A popular nonparametric(distribution-free) test to compare outcomes between two independent groups is the Mann Whitney U test. When comparing two independent samples, when the outcome is not normally distributed and the samples are small, a nonparametric test is appropriate. It is used to see the distribution difference between two independent variables on the basis of an ordinal(categorical variable having intrinsic an order or rank) dependent variable. It’s very much easy to perform this test in R programming. Let’s say we have two kinds of bulbs say orange and red in our data and these are divided on the day to day base prices. So here the base prices are dependent variable on the two categories which are red and orange. So we will try and analyze that if we want to buy a red or orange color bulb which should we prefer on the basis of prices. If both the distributions are the same then this means that the null hypothesis (means no significant difference between the two) is true and we can buy any one of them and prices won’t matter. To understand the concept of the Mann Whitney U Test one needs to know what is the p-value. This value actually tells if we can reject our null hypothesis(0.5) or not. Now below is the implementation of the above example. Make a dataframe with two categorical variables in which one would be an ordinal type.After this, check the summary of the non-ordinal categorical variable by loading a package dplyr and summarise() to get median values using median() and passing bulb_prices column, IQR-inter-quartile range, and count of both the groups i.e red and orange bulb.Then look at the Boxplot and see the distribution of the data with the help of installing a package ggpubr and using the ggboxplot() and passing the columns as arguments in x and y and giving them color with help of palette and passing the color codes.Then finally apply the function wilcox.test() to get the p-value.If the p-value is found to be less than 0.5 then the null hypothesis will be rejected.If we found the value to be greater than 0.5 then the null hypothesis will be accepted.wilcox.test() function takes both categorical variables,dataframe as an argument, and gives us the hypothesis p-value. Make a dataframe with two categorical variables in which one would be an ordinal type. After this, check the summary of the non-ordinal categorical variable by loading a package dplyr and summarise() to get median values using median() and passing bulb_prices column, IQR-inter-quartile range, and count of both the groups i.e red and orange bulb. Then look at the Boxplot and see the distribution of the data with the help of installing a package ggpubr and using the ggboxplot() and passing the columns as arguments in x and y and giving them color with help of palette and passing the color codes. Then finally apply the function wilcox.test() to get the p-value. If the p-value is found to be less than 0.5 then the null hypothesis will be rejected. If we found the value to be greater than 0.5 then the null hypothesis will be accepted. wilcox.test() function takes both categorical variables,dataframe as an argument, and gives us the hypothesis p-value. R # R program to illustrate# Mann Whitney U Test # Creating a small dataset# Creating a vector of red bulb and orange pricesred_bulb <- c(38.9, 61.2, 73.3, 21.8, 63.4, 64.6, 48.4, 48.8)orange_bulb <- c(47.8, 60, 63.4, 76, 89.4, 67.3, 61.3, 62.4) # Passing them in the columnsBULB_PRICE = c(red_bulb, orange_bulb)BULB_TYPE = rep(c("red", "orange"), each = 8) # Now creating a dataframeDATASET <- data.frame(BULB_TYPE, BULB_PRICE, stringsAsFactors = TRUE) # printing the dataframeDATASET # installing libraries to view summaries and# boxplot of both orange and red color bulbsinstall.packages("dplyr")install.packages("ggpubr") # Summary of the data # loading the packagelibrary(dplyr)group_by(DATASET,BULB_TYPE) %>% summarise( count = n(), median = median(BULB_PRICE, na.rm = TRUE), IQR = IQR(BULB_PRICE, na.rm = TRUE)) # loading package for boxplotlibrary("ggpubr")ggboxplot(DATASET, x = "BULB_TYPE", y = "BULB_PRICE", color = "BULB_TYPE", palette = c("#FFA500", "#FF0000"), ylab = "BULB_PRICES", xlab = "BULB_TYPES") res <- wilcox.test(BULB_PRICE~ BULB_TYPE, data = DATASET, exact = FALSE)res Output: > DATASET BULB_TYPE BULB_PRICE 1 red 38.9 2 red 61.2 3 red 73.3 4 red 21.8 5 red 63.4 6 red 64.6 7 red 48.4 8 red 48.8 9 orange 47.8 10 orange 60.0 11 orange 63.4 12 orange 76.0 13 orange 89.4 14 orange 67.3 15 orange 61.3 16 orange 62.4 # summary of the data summarise()` ungrouping output (override with `.groups` argument) # A tibble: 2 x 4 BULB_TYPE count median IQR <fct> <int> <dbl> <dbl> 1 orange 8 62.9 8.5 2 red 8 55 17.7 # boxplot > res Wilcoxon rank sum test with continuity correction data: BULB_PRICE by BULB_TYPE W = 44.5, p-value = 0.2072 alternative hypothesis: true location shift is not equal to 0 Explanation: Here as we can see that the value of p is coming out to be 0.2072 which is far less than the null hypothesis(0.5). Due to which it will be rejected. And it can conclude that the distribution of prices over red and orange bulbs is not the same. Due to which it cannot say that if it is profitable to buy any one of the above bulbs is profitable. kumar_satyam R Data-science R Machine-Learning R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Replace specific values in column in R DataFrame ? Filter data by multiple conditions in R using Dplyr Loops in R (for, while, repeat) How to change Row Names of DataFrame in R ? Change Color of Bars in Barchart using ggplot2 in R Printing Output of an R Program How to Change Axis Scales in R Plots? Remove rows with NA in one column of R DataFrame Group by function in R using Dplyr How to Split Column Into Multiple Columns in R DataFrame?
[ { "code": null, "e": 24450, "s": 24422, "text": "\n28 Dec, 2021" }, { "code": null, "e": 24968, "s": 24450, "text": "A popular nonparametric(distribution-free) test to compare outcomes between two independent groups is the Mann Whitney U test. When comparing two independent samples, when the outcome is not normally distributed and the samples are small, a nonparametric test is appropriate. It is used to see the distribution difference between two independent variables on the basis of an ordinal(categorical variable having intrinsic an order or rank) dependent variable. It’s very much easy to perform this test in R programming." }, { "code": null, "e": 25725, "s": 24968, "text": "Let’s say we have two kinds of bulbs say orange and red in our data and these are divided on the day to day base prices. So here the base prices are dependent variable on the two categories which are red and orange. So we will try and analyze that if we want to buy a red or orange color bulb which should we prefer on the basis of prices. If both the distributions are the same then this means that the null hypothesis (means no significant difference between the two) is true and we can buy any one of them and prices won’t matter. To understand the concept of the Mann Whitney U Test one needs to know what is the p-value. This value actually tells if we can reject our null hypothesis(0.5) or not. Now below is the implementation of the above example. " }, { "code": null, "e": 26681, "s": 25725, "text": " Make a dataframe with two categorical variables in which one would be an ordinal type.After this, check the summary of the non-ordinal categorical variable by loading a package dplyr and summarise() to get median values using median() and passing bulb_prices column, IQR-inter-quartile range, and count of both the groups i.e red and orange bulb.Then look at the Boxplot and see the distribution of the data with the help of installing a package ggpubr and using the ggboxplot() and passing the columns as arguments in x and y and giving them color with help of palette and passing the color codes.Then finally apply the function wilcox.test() to get the p-value.If the p-value is found to be less than 0.5 then the null hypothesis will be rejected.If we found the value to be greater than 0.5 then the null hypothesis will be accepted.wilcox.test() function takes both categorical variables,dataframe as an argument, and gives us the hypothesis p-value." }, { "code": null, "e": 26769, "s": 26681, "text": " Make a dataframe with two categorical variables in which one would be an ordinal type." }, { "code": null, "e": 27030, "s": 26769, "text": "After this, check the summary of the non-ordinal categorical variable by loading a package dplyr and summarise() to get median values using median() and passing bulb_prices column, IQR-inter-quartile range, and count of both the groups i.e red and orange bulb." }, { "code": null, "e": 27283, "s": 27030, "text": "Then look at the Boxplot and see the distribution of the data with the help of installing a package ggpubr and using the ggboxplot() and passing the columns as arguments in x and y and giving them color with help of palette and passing the color codes." }, { "code": null, "e": 27349, "s": 27283, "text": "Then finally apply the function wilcox.test() to get the p-value." }, { "code": null, "e": 27436, "s": 27349, "text": "If the p-value is found to be less than 0.5 then the null hypothesis will be rejected." }, { "code": null, "e": 27524, "s": 27436, "text": "If we found the value to be greater than 0.5 then the null hypothesis will be accepted." }, { "code": null, "e": 27643, "s": 27524, "text": "wilcox.test() function takes both categorical variables,dataframe as an argument, and gives us the hypothesis p-value." }, { "code": null, "e": 27645, "s": 27643, "text": "R" }, { "code": "# R program to illustrate# Mann Whitney U Test # Creating a small dataset# Creating a vector of red bulb and orange pricesred_bulb <- c(38.9, 61.2, 73.3, 21.8, 63.4, 64.6, 48.4, 48.8)orange_bulb <- c(47.8, 60, 63.4, 76, 89.4, 67.3, 61.3, 62.4) # Passing them in the columnsBULB_PRICE = c(red_bulb, orange_bulb)BULB_TYPE = rep(c(\"red\", \"orange\"), each = 8) # Now creating a dataframeDATASET <- data.frame(BULB_TYPE, BULB_PRICE, stringsAsFactors = TRUE) # printing the dataframeDATASET # installing libraries to view summaries and# boxplot of both orange and red color bulbsinstall.packages(\"dplyr\")install.packages(\"ggpubr\") # Summary of the data # loading the packagelibrary(dplyr)group_by(DATASET,BULB_TYPE) %>% summarise( count = n(), median = median(BULB_PRICE, na.rm = TRUE), IQR = IQR(BULB_PRICE, na.rm = TRUE)) # loading package for boxplotlibrary(\"ggpubr\")ggboxplot(DATASET, x = \"BULB_TYPE\", y = \"BULB_PRICE\", color = \"BULB_TYPE\", palette = c(\"#FFA500\", \"#FF0000\"), ylab = \"BULB_PRICES\", xlab = \"BULB_TYPES\") res <- wilcox.test(BULB_PRICE~ BULB_TYPE, data = DATASET, exact = FALSE)res", "e": 28801, "s": 27645, "text": null }, { "code": null, "e": 28810, "s": 28801, "text": " Output:" }, { "code": null, "e": 28820, "s": 28810, "text": "> DATASET" }, { "code": null, "e": 29230, "s": 28820, "text": " BULB_TYPE BULB_PRICE\n1 red 38.9\n2 red 61.2\n3 red 73.3\n4 red 21.8\n5 red 63.4\n6 red 64.6\n7 red 48.4\n8 red 48.8\n9 orange 47.8\n10 orange 60.0\n11 orange 63.4\n12 orange 76.0\n13 orange 89.4\n14 orange 67.3\n15 orange 61.3\n16 orange 62.4" }, { "code": null, "e": 29252, "s": 29230, "text": "# summary of the data" }, { "code": null, "e": 29460, "s": 29252, "text": "summarise()` ungrouping output (override with `.groups` argument)\n# A tibble: 2 x 4\n BULB_TYPE count median IQR\n <fct> <int> <dbl> <dbl>\n1 orange 8 62.9 8.5\n2 red 8 55 17.7" }, { "code": null, "e": 29470, "s": 29460, "text": "# boxplot" }, { "code": null, "e": 29476, "s": 29470, "text": "> res" }, { "code": null, "e": 29655, "s": 29476, "text": " Wilcoxon rank sum test with continuity correction\n\ndata: BULB_PRICE by BULB_TYPE\nW = 44.5, p-value = 0.2072\nalternative hypothesis: true location shift is not equal to 0" }, { "code": null, "e": 29668, "s": 29655, "text": "Explanation:" }, { "code": null, "e": 30014, "s": 29668, "text": "Here as we can see that the value of p is coming out to be 0.2072 which is far less than the null hypothesis(0.5). Due to which it will be rejected. And it can conclude that the distribution of prices over red and orange bulbs is not the same. Due to which it cannot say that if it is profitable to buy any one of the above bulbs is profitable." }, { "code": null, "e": 30027, "s": 30014, "text": "kumar_satyam" }, { "code": null, "e": 30042, "s": 30027, "text": "R Data-science" }, { "code": null, "e": 30061, "s": 30042, "text": "R Machine-Learning" }, { "code": null, "e": 30072, "s": 30061, "text": "R Language" }, { "code": null, "e": 30170, "s": 30072, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30179, "s": 30170, "text": "Comments" }, { "code": null, "e": 30192, "s": 30179, "text": "Old Comments" }, { "code": null, "e": 30250, "s": 30192, "text": "How to Replace specific values in column in R DataFrame ?" }, { "code": null, "e": 30302, "s": 30250, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 30334, "s": 30302, "text": "Loops in R (for, while, repeat)" }, { "code": null, "e": 30378, "s": 30334, "text": "How to change Row Names of DataFrame in R ?" }, { "code": null, "e": 30430, "s": 30378, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 30462, "s": 30430, "text": "Printing Output of an R Program" }, { "code": null, "e": 30500, "s": 30462, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 30549, "s": 30500, "text": "Remove rows with NA in one column of R DataFrame" }, { "code": null, "e": 30584, "s": 30549, "text": "Group by function in R using Dplyr" } ]
Analysing Posterior Predictive Distributions with PyMC3 | by Michael Grogan | Towards Data Science
The primary purpose of Bayesian analysis is to model data given uncertainty. Since one cannot access all the data about a population to determine its precise distribution, assumptions regarding the same are often made. For instance, I might make an assumption regarding the mean height of a population in a particular country. This is a prior distribution, or a distribution that is founded on prior beliefs before looking at data that could prove or disprove that belief. Upon analysing a new set of data (a likelihood function), prior beliefs and the likelihood function can then be combined to form the posterior distribution. Let’s see how PyMC3 can be used to model such a distribution. For this example, the Pima Indians Diabetes dataset is used to model body mass index data across a number of patients (some of whom are diabetic, some of whom are not). Before looking at the data, one needs to establish a prior belief regarding the mean and standard deviation of that data. Given that a sizeable number of patients in the dataset are diabetic, then one could formulate a prior belief that the mean BMI is higher than average. In this regard, let’s make a prior assumption that the mean BMI is 30, with a relatively smaller standard deviation of 2, indicating that we do not expect much deviation from the mean across individual cases. mu_prior=30sigma_prior=2with pm.Model() as model: mu = pm.Normal("mu", mu=mu_prior, sigma=sigma_prior) sd = pm.HalfNormal("sd", sigma=sigma_prior) obs = pm.Normal("obs", mu=mu, sigma=sd, observed=data) idata = pm.sample(1000, tune=1500, return_inferencedata=True) Using the 3.1. Sampling template from the PyMC3 General API Quickstart manual, the NUTS (No-U-Turn) sampler is used to draw 1,000 samples from the posterior in each chain, and then allow for readjustment across an additional 1,500 iterations. Note that as well as the prior mean and standard deviation, the model is also taking the observed data (observed=data) into account when generating the posterior distribution. NUTS is a form of Monte Carlo Markov Chain (MCMC) algorithm that bypasses random walk behaviour and allows for convergence to a target distribution more quickly. This not only has the advantage of speed, but allows for complex models to be fitted without having to employ specialised knowledge regarding the theory underlying those fitting methods. Using arviz, here are the generated posterior plots: A statistical summary of the distribution is also provided: Note that the mean of 31.949 was slightly higher than the prior estimation, while the standard deviation was significantly higher at 7.823. Having taken the data into account, it would make sense in hindsight that the standard deviation is higher than originally expected. After all, numerous patients in the dataset are not diabetic. Moreover, while one might expect a positive correlation between BMI and diabetes, this is based on a prior belief — we do not have hard evidence that this is the case without looking at the data. Taking the updated mean and standard deviation into account, here is the updated posterior distribution: We can see that the dispersion is higher than originally anticipated. That said, what if the data itself is not always quite accurate? For instance, nobody can have a BMI of 0, yet a number of 0 BMI values are present in the data for some unknown reason. However, specification of the prior values — along with the majority of other values in the data — indicate that such an observation is highly improbable. In this regard, the posterior predictive distribution drops dramatically below a level of 20 (the lowest observed BMI value in the data was 18.2). When first formulating our prior belief about BMI, the estimated mean value was not very far off from the actual value. However, what if our prior beliefs completely missed the mark? Suppose we had estimated a mean BMI of 50 and a standard deviation of 2? The generated posterior distribution is as follows: Even in spite of the inaccurate prior beliefs, the sampler can recognise that this completely misses the mark with respect to the actual data observed, and the distribution is updated accordingly. This can also be very useful in a situation whereby new data assumes a different distribution from prior patterns. For instance, a manager of a company might assume from experience that product sales in a given year tend to show a certain mean and standard deviation, but subsequent data is different from that of previous years. In this regard, the posterior distribution allows for updating of the manager’s prior beliefs to reflect the new data being observed. Posterior distributions allow for updating of prior beliefs through taking new evidence (or data) into account when generating such distributions. In this example, you have learned: The difference between a prior and posterior distribution How to model posterior distributions with PyMC3 How to interpret posterior plots with arviz Role of prior beliefs and the likelihood function in generating posterior distributions Many thanks for your time, and any questions or feedback are greatly welcomed. You can also find more of my data science content at michael-grogan.com. Disclaimer: This article is written on an “as is” basis and without warranty. It was written with the intention of providing an overview of data science concepts, and should not be interpreted as professional advice. The findings and interpretations in this article are those of the author and are not endorsed by or affiliated with any third-party mentioned in this article. Gelman and Hoffman (2011). The No-U-Turn Sampler: Adaptively Setting Path Lengths in Hamiltonian Monte Carlo Kaggle: Pima Indians Diabetes Database PyMC3: General API Quickstart
[ { "code": null, "e": 249, "s": 172, "text": "The primary purpose of Bayesian analysis is to model data given uncertainty." }, { "code": null, "e": 391, "s": 249, "text": "Since one cannot access all the data about a population to determine its precise distribution, assumptions regarding the same are often made." }, { "code": null, "e": 645, "s": 391, "text": "For instance, I might make an assumption regarding the mean height of a population in a particular country. This is a prior distribution, or a distribution that is founded on prior beliefs before looking at data that could prove or disprove that belief." }, { "code": null, "e": 802, "s": 645, "text": "Upon analysing a new set of data (a likelihood function), prior beliefs and the likelihood function can then be combined to form the posterior distribution." }, { "code": null, "e": 864, "s": 802, "text": "Let’s see how PyMC3 can be used to model such a distribution." }, { "code": null, "e": 1033, "s": 864, "text": "For this example, the Pima Indians Diabetes dataset is used to model body mass index data across a number of patients (some of whom are diabetic, some of whom are not)." }, { "code": null, "e": 1307, "s": 1033, "text": "Before looking at the data, one needs to establish a prior belief regarding the mean and standard deviation of that data. Given that a sizeable number of patients in the dataset are diabetic, then one could formulate a prior belief that the mean BMI is higher than average." }, { "code": null, "e": 1516, "s": 1307, "text": "In this regard, let’s make a prior assumption that the mean BMI is 30, with a relatively smaller standard deviation of 2, indicating that we do not expect much deviation from the mean across individual cases." }, { "code": null, "e": 1792, "s": 1516, "text": "mu_prior=30sigma_prior=2with pm.Model() as model: mu = pm.Normal(\"mu\", mu=mu_prior, sigma=sigma_prior) sd = pm.HalfNormal(\"sd\", sigma=sigma_prior) obs = pm.Normal(\"obs\", mu=mu, sigma=sd, observed=data) idata = pm.sample(1000, tune=1500, return_inferencedata=True)" }, { "code": null, "e": 2211, "s": 1792, "text": "Using the 3.1. Sampling template from the PyMC3 General API Quickstart manual, the NUTS (No-U-Turn) sampler is used to draw 1,000 samples from the posterior in each chain, and then allow for readjustment across an additional 1,500 iterations. Note that as well as the prior mean and standard deviation, the model is also taking the observed data (observed=data) into account when generating the posterior distribution." }, { "code": null, "e": 2560, "s": 2211, "text": "NUTS is a form of Monte Carlo Markov Chain (MCMC) algorithm that bypasses random walk behaviour and allows for convergence to a target distribution more quickly. This not only has the advantage of speed, but allows for complex models to be fitted without having to employ specialised knowledge regarding the theory underlying those fitting methods." }, { "code": null, "e": 2613, "s": 2560, "text": "Using arviz, here are the generated posterior plots:" }, { "code": null, "e": 2673, "s": 2613, "text": "A statistical summary of the distribution is also provided:" }, { "code": null, "e": 2813, "s": 2673, "text": "Note that the mean of 31.949 was slightly higher than the prior estimation, while the standard deviation was significantly higher at 7.823." }, { "code": null, "e": 2946, "s": 2813, "text": "Having taken the data into account, it would make sense in hindsight that the standard deviation is higher than originally expected." }, { "code": null, "e": 3204, "s": 2946, "text": "After all, numerous patients in the dataset are not diabetic. Moreover, while one might expect a positive correlation between BMI and diabetes, this is based on a prior belief — we do not have hard evidence that this is the case without looking at the data." }, { "code": null, "e": 3309, "s": 3204, "text": "Taking the updated mean and standard deviation into account, here is the updated posterior distribution:" }, { "code": null, "e": 3564, "s": 3309, "text": "We can see that the dispersion is higher than originally anticipated. That said, what if the data itself is not always quite accurate? For instance, nobody can have a BMI of 0, yet a number of 0 BMI values are present in the data for some unknown reason." }, { "code": null, "e": 3866, "s": 3564, "text": "However, specification of the prior values — along with the majority of other values in the data — indicate that such an observation is highly improbable. In this regard, the posterior predictive distribution drops dramatically below a level of 20 (the lowest observed BMI value in the data was 18.2)." }, { "code": null, "e": 3986, "s": 3866, "text": "When first formulating our prior belief about BMI, the estimated mean value was not very far off from the actual value." }, { "code": null, "e": 4122, "s": 3986, "text": "However, what if our prior beliefs completely missed the mark? Suppose we had estimated a mean BMI of 50 and a standard deviation of 2?" }, { "code": null, "e": 4174, "s": 4122, "text": "The generated posterior distribution is as follows:" }, { "code": null, "e": 4371, "s": 4174, "text": "Even in spite of the inaccurate prior beliefs, the sampler can recognise that this completely misses the mark with respect to the actual data observed, and the distribution is updated accordingly." }, { "code": null, "e": 4835, "s": 4371, "text": "This can also be very useful in a situation whereby new data assumes a different distribution from prior patterns. For instance, a manager of a company might assume from experience that product sales in a given year tend to show a certain mean and standard deviation, but subsequent data is different from that of previous years. In this regard, the posterior distribution allows for updating of the manager’s prior beliefs to reflect the new data being observed." }, { "code": null, "e": 4982, "s": 4835, "text": "Posterior distributions allow for updating of prior beliefs through taking new evidence (or data) into account when generating such distributions." }, { "code": null, "e": 5017, "s": 4982, "text": "In this example, you have learned:" }, { "code": null, "e": 5075, "s": 5017, "text": "The difference between a prior and posterior distribution" }, { "code": null, "e": 5123, "s": 5075, "text": "How to model posterior distributions with PyMC3" }, { "code": null, "e": 5167, "s": 5123, "text": "How to interpret posterior plots with arviz" }, { "code": null, "e": 5255, "s": 5167, "text": "Role of prior beliefs and the likelihood function in generating posterior distributions" }, { "code": null, "e": 5407, "s": 5255, "text": "Many thanks for your time, and any questions or feedback are greatly welcomed. You can also find more of my data science content at michael-grogan.com." }, { "code": null, "e": 5783, "s": 5407, "text": "Disclaimer: This article is written on an “as is” basis and without warranty. It was written with the intention of providing an overview of data science concepts, and should not be interpreted as professional advice. The findings and interpretations in this article are those of the author and are not endorsed by or affiliated with any third-party mentioned in this article." }, { "code": null, "e": 5892, "s": 5783, "text": "Gelman and Hoffman (2011). The No-U-Turn Sampler: Adaptively Setting Path Lengths in Hamiltonian Monte Carlo" }, { "code": null, "e": 5931, "s": 5892, "text": "Kaggle: Pima Indians Diabetes Database" } ]
Longest Consecutive Subsequence - GeeksforGeeks
20 Jan, 2022 Given an array of integers, find the length of the longest sub-sequence such that elements in the subsequence are consecutive integers, the consecutive numbers can be in any order. Examples: Input: arr[] = {1, 9, 3, 10, 4, 20, 2} Output: 4 Explanation: The subsequence 1, 3, 4, 2 is the longest subsequence of consecutive elements Input: arr[] = {36, 41, 56, 35, 44, 33, 34, 92, 43, 32, 42} Output: 5 Explanation: The subsequence 36, 35, 33, 34, 32 is the longest subsequence of consecutive elements. Naive Approach: The idea is to first sort the array and find the longest subarray with consecutive elements. After sorting the array and removing the multiple occurrences of elements, run a loop and keep a count and max (both initially zero). Run a loop from start to end and if the current element is not equal to the previous (element+1) then set the count to 1 else increase the count. Update max with a maximum of count and max. C++ Java Python3 C# Javascript // C++ program to find longest// contiguous subsequence#include <bits/stdc++.h>using namespace std; // Returns length of the longest// contiguous subsequenceint findLongestConseqSubseq(int arr[], int n){ int ans = 0, count = 0; // sort the array sort(arr, arr + n); vector<int> v; v.push_back(arr[0]); //insert repeated elements only once in the vector for (int i = 1; i < n; i++) { if (arr[i] != arr[i - 1]) v.push_back(arr[i]); } // find the maximum length // by traversing the array for (int i = 0; i < v.size(); i++) { // Check if the current element is equal // to previous element +1 if (i > 0 && v[i] == v[i - 1] + 1) count++; // reset the count else count = 1; // update the maximum ans = max(ans, count); } return ans;} // Driver codeint main(){ int arr[] = { 1, 2, 2, 3 }; int n = sizeof arr / sizeof arr[0]; cout << "Length of the Longest contiguous subsequence " "is " << findLongestConseqSubseq(arr, n); return 0;} // Java program to find longest// contiguous subsequenceimport java.io.*;import java.util.*; class GFG{ static int findLongestConseqSubseq(int arr[], int n) { // Sort the array Arrays.sort(arr); int ans = 0, count = 0; ArrayList<Integer> v = new ArrayList<Integer>(); v.add(10); // Insert repeated elements // only once in the vector for (int i = 1; i < n; i++) { if (arr[i] != arr[i - 1]) v.add(arr[i]); } // Find the maximum length // by traversing the array for (int i = 0; i < v.size(); i++) { // Check if the current element is // equal to previous element +1 if (i > 0 &&v.get(i) == v.get(i - 1) + 1) count++; else count = 1; // Update the maximum ans = Math.max(ans, count); } return ans; } // Driver code public static void main(String[] args) { int arr[] = { 1, 9, 3, 10, 4, 20, 2 }; int n = arr.length; System.out.println( "Length of the Longest " + "contiguous subsequence is " + findLongestConseqSubseq(arr, n)); }} // This code is contributed by parascoding # Python3 program to find longest# contiguous subsequence # Returns length of the longest# contiguous subsequencedef findLongestConseqSubseq(arr, n): ans = 0 count = 0 # Sort the array arr.sort() v = [] v.append(arr[0]) # Insert repeated elements only # once in the vector for i in range(1, n): if (arr[i] != arr[i - 1]): v.append(arr[i]) # Find the maximum length # by traversing the array for i in range(len(v)): # Check if the current element is # equal to previous element +1 if (i > 0 and v[i] == v[i - 1] + 1): count += 1 # Reset the count else: count = 1 # Update the maximum ans = max(ans, count) return ans # Driver codearr = [ 1, 2, 2, 3 ]n = len(arr) print("Length of the Longest contiguous subsequence is", findLongestConseqSubseq(arr, n)) # This code is contributed by avanitrachhadiya2155 // C# program to find longest// contiguous subsequenceusing System;using System.Collections.Generic; class GFG{ static int findLongestConseqSubseq(int[] arr, int n){ // Sort the array Array.Sort(arr); int ans = 0, count = 0; List<int> v = new List<int>(); v.Add(10); // Insert repeated elements // only once in the vector for(int i = 1; i < n; i++) { if (arr[i] != arr[i - 1]) v.Add(arr[i]); } // Find the maximum length // by traversing the array for(int i = 0; i < v.Count; i++) { // Check if the current element is // equal to previous element +1 if (i > 0 && v[i] == v[i - 1] + 1) count++; else count = 1; // Update the maximum ans = Math.Max(ans, count); } return ans;} // Driver codestatic void Main(){ int[] arr = { 1, 9, 3, 10, 4, 20, 2 }; int n = arr.Length; Console.WriteLine("Length of the Longest " + "contiguous subsequence is " + findLongestConseqSubseq(arr, n));}} // This code is contributed by divyeshrabadiya07 <script> // JavaScript program to find longest // contiguous subsequence // Returns length of the longest // contiguous subsequence function findLongestConseqSubseq(arr, n) { let ans = 0, count = 0; // sort the array arr.sort(function (a, b) { return a - b; }) var v = []; v.push(arr[0]); //insert repeated elements only once in the vector for (let i = 1; i < n; i++) { if (arr[i] != arr[i - 1]) v.push(arr[i]); } // find the maximum length // by traversing the array for (let i = 0; i < v.length; i++) { // Check if the current element is equal // to previous element +1 if (i > 0 && v[i] == v[i - 1] + 1) count++; // reset the count else count = 1; // update the maximum ans = Math.max(ans, count); } return ans; } // Driver code let arr = [1, 2, 2, 3]; let n = arr.length; document.write( "Length of the Longest contiguous subsequence is " +findLongestConseqSubseq(arr, n) ); // This code is contributed by Potta Lokesh </script> Length of the Longest contiguous subsequence is 3 Complexity Analysis: Time complexity: O(nLogn). Time to sort the array is O(nlogn). Auxiliary space : O(1). As no extra space is needed. Thanks to Hao.W for suggesting the above solution. Efficient solution: This problem can be solved in O(n) time using an Efficient Solution. The idea is to use Hashing. We first insert all elements in a Set. Then check all the possible starts of consecutive subsequences. Algorithm: Create an empty hash.Insert all array elements to hash.Do following for every element arr[i]Check if this element is the starting point of a subsequence. To check this, simply look for arr[i] – 1 in the hash, if not found, then this is the first element a subsequence.If this element is the first element, then count the number of elements in the consecutive starting with this element. Iterate from arr[i] + 1 till the last element that can be found.If the count is more than the previous longest subsequence found, then update this. Create an empty hash. Insert all array elements to hash. Do following for every element arr[i] Check if this element is the starting point of a subsequence. To check this, simply look for arr[i] – 1 in the hash, if not found, then this is the first element a subsequence. If this element is the first element, then count the number of elements in the consecutive starting with this element. Iterate from arr[i] + 1 till the last element that can be found. If the count is more than the previous longest subsequence found, then update this. Below image is a dry run of the above approach: Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to find longest// contiguous subsequence#include <bits/stdc++.h>using namespace std; // Returns length of the longest// contiguous subsequenceint findLongestConseqSubseq(int arr[], int n){ unordered_set<int> S; int ans = 0; // Hash all the array elements for (int i = 0; i < n; i++) S.insert(arr[i]); // check each possible sequence from // the start then update optimal length for (int i = 0; i < n; i++) { // if current element is the starting // element of a sequence if (S.find(arr[i] - 1) == S.end()) { // Then check for next elements // in the sequence int j = arr[i]; while (S.find(j) != S.end()) j++; // update optimal length if // this length is more ans = max(ans, j - arr[i]); } } return ans;} // Driver codeint main(){ int arr[] = { 1, 9, 3, 10, 4, 20, 2 }; int n = sizeof arr / sizeof arr[0]; cout << "Length of the Longest contiguous subsequence " "is " << findLongestConseqSubseq(arr, n); return 0;} // Java program to find longest// consecutive subsequenceimport java.io.*;import java.util.*; class ArrayElements { // Returns length of the longest // consecutive subsequence static int findLongestConseqSubseq(int arr[], int n) { HashSet<Integer> S = new HashSet<Integer>(); int ans = 0; // Hash all the array elements for (int i = 0; i < n; ++i) S.add(arr[i]); // check each possible sequence from the start // then update optimal length for (int i = 0; i < n; ++i) { // if current element is the starting // element of a sequence if (!S.contains(arr[i] - 1)) { // Then check for next elements // in the sequence int j = arr[i]; while (S.contains(j)) j++; // update optimal length if this // length is more if (ans < j - arr[i]) ans = j - arr[i]; } } return ans; } // Driver Code public static void main(String args[]) { int arr[] = { 1, 9, 3, 10, 4, 20, 2 }; int n = arr.length; System.out.println( "Length of the Longest consecutive subsequence is " + findLongestConseqSubseq(arr, n)); }}// This code is contributed by Aakash Hasija # Python program to find longest contiguous subsequence def findLongestConseqSubseq(arr, n): s = set() ans = 0 # Hash all the array elements for ele in arr: s.add(ele) # check each possible sequence from the start # then update optimal length for i in range(n): # if current element is the starting # element of a sequence if (arr[i]-1) not in s: # Then check for next elements in the # sequence j = arr[i] while(j in s): j += 1 # update optimal length if this length # is more ans = max(ans, j-arr[i]) return ans # Driver codeif __name__ == '__main__': n = 7 arr = [1, 9, 3, 10, 4, 20, 2] print ("Length of the Longest contiguous subsequence is ",findLongestConseqSubseq(arr, n)) # Contributed by: Harshit Sidhwa using System;using System.Collections.Generic; // C# program to find longest consecutive subsequence public class ArrayElements { // Returns length of the // longest consecutive subsequence public static int findLongestConseqSubseq(int[] arr, int n) { HashSet<int> S = new HashSet<int>(); int ans = 0; // Hash all the array elements for (int i = 0; i < n; ++i) { S.Add(arr[i]); } // check each possible sequence from the start // then update optimal length for (int i = 0; i < n; ++i) { // if current element is the starting // element of a sequence if (!S.Contains(arr[i] - 1)) { // Then check for next elements in the // sequence int j = arr[i]; while (S.Contains(j)) { j++; } // update optimal length if this length // is more if (ans < j - arr[i]) { ans = j - arr[i]; } } } return ans; } // Driver code public static void Main(string[] args) { int[] arr = new int[] { 1, 9, 3, 10, 4, 20, 2 }; int n = arr.Length; Console.WriteLine( "Length of the Longest consecutive subsequence is " + findLongestConseqSubseq(arr, n)); }} // This code is contributed by Shrikant13 <script>// Javascript program to find longest// contiguous subsequence // Returns length of the longest// contiguous subsequencefunction findLongestConseqSubseq(arr, n) { let S = new Set(); let ans = 0; // Hash all the array elements for (let i = 0; i < n; i++) S.add(arr[i]); // check each possible sequence from // the start then update optimal length for (let i = 0; i < n; i++) { // if current element is the starting // element of a sequence if (!S.has(arr[i] - 1)) { // Then check for next elements // in the sequence let j = arr[i]; while (S.has(j)) j++; // update optimal length if // this length is more ans = Math.max(ans, j - arr[i]); } } return ans;} // Driver codelet arr = [1, 9, 3, 10, 4, 20, 2];let n = arr.length;document.write("Length of the Longest contiguous subsequence is " + findLongestConseqSubseq(arr, n)); // This code is contributed by gfgking.</script> Length of the Longest contiguous subsequence is 4 Complexity Analysis: Time complexity: O(n). Only one traversal is needed and the time complexity is O(n) under the assumption that hash insert and search take O(1) time. Auxiliary space: O(n). To store every element in hashmap O(n) space is needed Thanks to Gaurav Ahirwar for the above solution. Another Solution: This problem can be solved in O(N log N) time with another Method, this time the Idea is to use Priority Queue. Algorithm: Create a Priority Queue to store the elementStore the first element in a variableRemove it from the Priority QueueCheck the difference between this removed first element and the new peek elementIf the difference is equal to 1 increase count by 1 and repeats step 2 and step 3If the difference is greater than 1 set counter to 1 and repeat step 2 and step 3if the difference is equal to 0 repeat step 2 and 3if counter greater than the previous maximum then store counter to maximumContinue step 4 to 7 until we reach the end of the Priority QueueReturn the maximum value Create a Priority Queue to store the element Store the first element in a variable Remove it from the Priority Queue Check the difference between this removed first element and the new peek element If the difference is equal to 1 increase count by 1 and repeats step 2 and step 3 If the difference is greater than 1 set counter to 1 and repeat step 2 and step 3 if the difference is equal to 0 repeat step 2 and 3 if counter greater than the previous maximum then store counter to maximum Continue step 4 to 7 until we reach the end of the Priority Queue Return the maximum value C++ Java // CPP program for the above approach#include <bits/stdc++.h>using namespace std; int findLongestConseqSubseq(int arr[], int N){ priority_queue<int, vector<int>, greater<int> > pq; for (int i = 0; i < N; i++) { // adding element from // array to PriorityQueue pq.push(arr[i]); } // Storing the first element // of the Priority Queue // This first element is also // the smallest element int prev = pq.top(); pq.pop(); // Taking a counter variable with value 1 int c = 1; // Storing value of max as 1 // as there will always be // one element int max = 1; while (!pq.empty()) { // check if current peek // element minus previous // element is greater then // 1 This is done because // if it's greater than 1 // then the sequence // doesn't start or is broken here if (pq.top() - prev > 1) { // Store the value of counter to 1 // As new sequence may begin c = 1; // Update the previous position with the // current peek And remove it prev = pq.top(); pq.pop(); } // Check if the previous // element and peek are same else if (pq.top() - prev == 0) { // Update the previous position with the // current peek And remove it prev = pq.top(); pq.pop(); } // If the difference // between previous element and peek is 1 else { // Update the counter // These are consecutive elements c++; // Update the previous position // with the current peek And remove it prev = pq.top(); pq.pop(); } // Check if current longest // subsequence is the greatest if (max < c) { // Store the current subsequence count as // max max = c; } } return max;} // Driver Codeint main(){ int arr[] = { 1, 9, 3, 10, 4, 20, 2 }; int n = 7; cout << "Length of the Longest consecutive subsequence " "is " << findLongestConseqSubseq(arr, n); return 0;}// this code is contributed by Manu Pathria // Java Program to find longest consecutive// subsequence This Program uses Priority Queueimport java.io.*;import java.util.PriorityQueue;public class Longset_Sub{ // return the length of the longest // subsequence of consecutive integers static int findLongestConseqSubseq(int arr[], int N) { PriorityQueue<Integer> pq = new PriorityQueue<Integer>(); for (int i = 0; i < N; i++) { // adding element from // array to PriorityQueue pq.add(arr[i]); } // Storing the first element // of the Priority Queue // This first element is also // the smallest element int prev = pq.poll(); // Taking a counter variable with value 1 int c = 1; // Storing value of max as 1 // as there will always be // one element int max = 1; for (int i = 1; i < N; i++) { // check if current peek // element minus previous // element is greater then // 1 This is done because // if it's greater than 1 // then the sequence // doesn't start or is broken here if (pq.peek() - prev > 1) { // Store the value of counter to 1 // As new sequence may begin c = 1; // Update the previous position with the // current peek And remove it prev = pq.poll(); } // Check if the previous // element and peek are same else if (pq.peek() - prev == 0) { // Update the previous position with the // current peek And remove it prev = pq.poll(); } // if the difference // between previous element and peek is 1 else { // Update the counter // These are consecutive elements c++; // Update the previous position // with the current peek And remove it prev = pq.poll(); } // Check if current longest // subsequence is the greatest if (max < c) { // Store the current subsequence count as // max max = c; } } return max; } // Driver Code public static void main(String args[]) throws IOException { int arr[] = { 1, 9, 3, 10, 4, 20, 2 }; int n = arr.length; System.out.println( "Length of the Longest consecutive subsequence is " + findLongestConseqSubseq(arr, n)); }}// This code is contributed by Sudipa Sarkar Length of the Longest consecutive subsequence is 4 Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. shrikanth13 andrew1234 parascoding agrawalvaibhaw96 akashgoraya1 avanitrachhadiya2155 divyeshrabadiya07 sudipasarkar999 manupathria revathi727 lokeshpotta20 gfgking CoderSaty amartyaghoshgfg Amazon Linkedin subsequence Walmart Zoho Arrays Hash Sorting Zoho Amazon Walmart Linkedin Arrays Hash Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Arrays Multidimensional Arrays in Java Linked List vs Array Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Python | Using 2D arrays/lists the right way Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Internal Working of HashMap in Java Count pairs with given sum Hashing | Set 1 (Introduction) Hashing | Set 3 (Open Addressing)
[ { "code": null, "e": 26327, "s": 26299, "text": "\n20 Jan, 2022" }, { "code": null, "e": 26509, "s": 26327, "text": "Given an array of integers, find the length of the longest sub-sequence such that elements in the subsequence are consecutive integers, the consecutive numbers can be in any order. " }, { "code": null, "e": 26521, "s": 26509, "text": "Examples: " }, { "code": null, "e": 26836, "s": 26521, "text": "Input: arr[] = {1, 9, 3, 10, 4, 20, 2}\nOutput: 4\nExplanation: \nThe subsequence 1, 3, 4, 2 is the longest \nsubsequence of consecutive elements\n\nInput: arr[] = {36, 41, 56, 35, 44, 33, 34, 92, 43, 32, 42}\nOutput: 5\nExplanation: \nThe subsequence 36, 35, 33, 34, 32 is the longest \nsubsequence of consecutive elements." }, { "code": null, "e": 27270, "s": 26836, "text": "Naive Approach: The idea is to first sort the array and find the longest subarray with consecutive elements. After sorting the array and removing the multiple occurrences of elements, run a loop and keep a count and max (both initially zero). Run a loop from start to end and if the current element is not equal to the previous (element+1) then set the count to 1 else increase the count. Update max with a maximum of count and max. " }, { "code": null, "e": 27274, "s": 27270, "text": "C++" }, { "code": null, "e": 27279, "s": 27274, "text": "Java" }, { "code": null, "e": 27287, "s": 27279, "text": "Python3" }, { "code": null, "e": 27290, "s": 27287, "text": "C#" }, { "code": null, "e": 27301, "s": 27290, "text": "Javascript" }, { "code": "// C++ program to find longest// contiguous subsequence#include <bits/stdc++.h>using namespace std; // Returns length of the longest// contiguous subsequenceint findLongestConseqSubseq(int arr[], int n){ int ans = 0, count = 0; // sort the array sort(arr, arr + n); vector<int> v; v.push_back(arr[0]); //insert repeated elements only once in the vector for (int i = 1; i < n; i++) { if (arr[i] != arr[i - 1]) v.push_back(arr[i]); } // find the maximum length // by traversing the array for (int i = 0; i < v.size(); i++) { // Check if the current element is equal // to previous element +1 if (i > 0 && v[i] == v[i - 1] + 1) count++; // reset the count else count = 1; // update the maximum ans = max(ans, count); } return ans;} // Driver codeint main(){ int arr[] = { 1, 2, 2, 3 }; int n = sizeof arr / sizeof arr[0]; cout << \"Length of the Longest contiguous subsequence \" \"is \" << findLongestConseqSubseq(arr, n); return 0;}", "e": 28407, "s": 27301, "text": null }, { "code": "// Java program to find longest// contiguous subsequenceimport java.io.*;import java.util.*; class GFG{ static int findLongestConseqSubseq(int arr[], int n) { // Sort the array Arrays.sort(arr); int ans = 0, count = 0; ArrayList<Integer> v = new ArrayList<Integer>(); v.add(10); // Insert repeated elements // only once in the vector for (int i = 1; i < n; i++) { if (arr[i] != arr[i - 1]) v.add(arr[i]); } // Find the maximum length // by traversing the array for (int i = 0; i < v.size(); i++) { // Check if the current element is // equal to previous element +1 if (i > 0 &&v.get(i) == v.get(i - 1) + 1) count++; else count = 1; // Update the maximum ans = Math.max(ans, count); } return ans; } // Driver code public static void main(String[] args) { int arr[] = { 1, 9, 3, 10, 4, 20, 2 }; int n = arr.length; System.out.println( \"Length of the Longest \" + \"contiguous subsequence is \" + findLongestConseqSubseq(arr, n)); }} // This code is contributed by parascoding", "e": 29755, "s": 28407, "text": null }, { "code": "# Python3 program to find longest# contiguous subsequence # Returns length of the longest# contiguous subsequencedef findLongestConseqSubseq(arr, n): ans = 0 count = 0 # Sort the array arr.sort() v = [] v.append(arr[0]) # Insert repeated elements only # once in the vector for i in range(1, n): if (arr[i] != arr[i - 1]): v.append(arr[i]) # Find the maximum length # by traversing the array for i in range(len(v)): # Check if the current element is # equal to previous element +1 if (i > 0 and v[i] == v[i - 1] + 1): count += 1 # Reset the count else: count = 1 # Update the maximum ans = max(ans, count) return ans # Driver codearr = [ 1, 2, 2, 3 ]n = len(arr) print(\"Length of the Longest contiguous subsequence is\", findLongestConseqSubseq(arr, n)) # This code is contributed by avanitrachhadiya2155", "e": 30738, "s": 29755, "text": null }, { "code": "// C# program to find longest// contiguous subsequenceusing System;using System.Collections.Generic; class GFG{ static int findLongestConseqSubseq(int[] arr, int n){ // Sort the array Array.Sort(arr); int ans = 0, count = 0; List<int> v = new List<int>(); v.Add(10); // Insert repeated elements // only once in the vector for(int i = 1; i < n; i++) { if (arr[i] != arr[i - 1]) v.Add(arr[i]); } // Find the maximum length // by traversing the array for(int i = 0; i < v.Count; i++) { // Check if the current element is // equal to previous element +1 if (i > 0 && v[i] == v[i - 1] + 1) count++; else count = 1; // Update the maximum ans = Math.Max(ans, count); } return ans;} // Driver codestatic void Main(){ int[] arr = { 1, 9, 3, 10, 4, 20, 2 }; int n = arr.Length; Console.WriteLine(\"Length of the Longest \" + \"contiguous subsequence is \" + findLongestConseqSubseq(arr, n));}} // This code is contributed by divyeshrabadiya07", "e": 31916, "s": 30738, "text": null }, { "code": "<script> // JavaScript program to find longest // contiguous subsequence // Returns length of the longest // contiguous subsequence function findLongestConseqSubseq(arr, n) { let ans = 0, count = 0; // sort the array arr.sort(function (a, b) { return a - b; }) var v = []; v.push(arr[0]); //insert repeated elements only once in the vector for (let i = 1; i < n; i++) { if (arr[i] != arr[i - 1]) v.push(arr[i]); } // find the maximum length // by traversing the array for (let i = 0; i < v.length; i++) { // Check if the current element is equal // to previous element +1 if (i > 0 && v[i] == v[i - 1] + 1) count++; // reset the count else count = 1; // update the maximum ans = Math.max(ans, count); } return ans; } // Driver code let arr = [1, 2, 2, 3]; let n = arr.length; document.write( \"Length of the Longest contiguous subsequence is \" +findLongestConseqSubseq(arr, n) ); // This code is contributed by Potta Lokesh </script>", "e": 33122, "s": 31916, "text": null }, { "code": null, "e": 33172, "s": 33122, "text": "Length of the Longest contiguous subsequence is 3" }, { "code": null, "e": 33194, "s": 33172, "text": "Complexity Analysis: " }, { "code": null, "e": 33257, "s": 33194, "text": "Time complexity: O(nLogn). Time to sort the array is O(nlogn)." }, { "code": null, "e": 33310, "s": 33257, "text": "Auxiliary space : O(1). As no extra space is needed." }, { "code": null, "e": 33361, "s": 33310, "text": "Thanks to Hao.W for suggesting the above solution." }, { "code": null, "e": 33581, "s": 33361, "text": "Efficient solution: This problem can be solved in O(n) time using an Efficient Solution. The idea is to use Hashing. We first insert all elements in a Set. Then check all the possible starts of consecutive subsequences." }, { "code": null, "e": 33594, "s": 33581, "text": " Algorithm: " }, { "code": null, "e": 34129, "s": 33594, "text": "Create an empty hash.Insert all array elements to hash.Do following for every element arr[i]Check if this element is the starting point of a subsequence. To check this, simply look for arr[i] – 1 in the hash, if not found, then this is the first element a subsequence.If this element is the first element, then count the number of elements in the consecutive starting with this element. Iterate from arr[i] + 1 till the last element that can be found.If the count is more than the previous longest subsequence found, then update this." }, { "code": null, "e": 34151, "s": 34129, "text": "Create an empty hash." }, { "code": null, "e": 34186, "s": 34151, "text": "Insert all array elements to hash." }, { "code": null, "e": 34224, "s": 34186, "text": "Do following for every element arr[i]" }, { "code": null, "e": 34401, "s": 34224, "text": "Check if this element is the starting point of a subsequence. To check this, simply look for arr[i] – 1 in the hash, if not found, then this is the first element a subsequence." }, { "code": null, "e": 34585, "s": 34401, "text": "If this element is the first element, then count the number of elements in the consecutive starting with this element. Iterate from arr[i] + 1 till the last element that can be found." }, { "code": null, "e": 34669, "s": 34585, "text": "If the count is more than the previous longest subsequence found, then update this." }, { "code": null, "e": 34718, "s": 34669, "text": "Below image is a dry run of the above approach: " }, { "code": null, "e": 34770, "s": 34718, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 34774, "s": 34770, "text": "C++" }, { "code": null, "e": 34779, "s": 34774, "text": "Java" }, { "code": null, "e": 34787, "s": 34779, "text": "Python3" }, { "code": null, "e": 34790, "s": 34787, "text": "C#" }, { "code": null, "e": 34801, "s": 34790, "text": "Javascript" }, { "code": "// C++ program to find longest// contiguous subsequence#include <bits/stdc++.h>using namespace std; // Returns length of the longest// contiguous subsequenceint findLongestConseqSubseq(int arr[], int n){ unordered_set<int> S; int ans = 0; // Hash all the array elements for (int i = 0; i < n; i++) S.insert(arr[i]); // check each possible sequence from // the start then update optimal length for (int i = 0; i < n; i++) { // if current element is the starting // element of a sequence if (S.find(arr[i] - 1) == S.end()) { // Then check for next elements // in the sequence int j = arr[i]; while (S.find(j) != S.end()) j++; // update optimal length if // this length is more ans = max(ans, j - arr[i]); } } return ans;} // Driver codeint main(){ int arr[] = { 1, 9, 3, 10, 4, 20, 2 }; int n = sizeof arr / sizeof arr[0]; cout << \"Length of the Longest contiguous subsequence \" \"is \" << findLongestConseqSubseq(arr, n); return 0;}", "e": 35930, "s": 34801, "text": null }, { "code": "// Java program to find longest// consecutive subsequenceimport java.io.*;import java.util.*; class ArrayElements { // Returns length of the longest // consecutive subsequence static int findLongestConseqSubseq(int arr[], int n) { HashSet<Integer> S = new HashSet<Integer>(); int ans = 0; // Hash all the array elements for (int i = 0; i < n; ++i) S.add(arr[i]); // check each possible sequence from the start // then update optimal length for (int i = 0; i < n; ++i) { // if current element is the starting // element of a sequence if (!S.contains(arr[i] - 1)) { // Then check for next elements // in the sequence int j = arr[i]; while (S.contains(j)) j++; // update optimal length if this // length is more if (ans < j - arr[i]) ans = j - arr[i]; } } return ans; } // Driver Code public static void main(String args[]) { int arr[] = { 1, 9, 3, 10, 4, 20, 2 }; int n = arr.length; System.out.println( \"Length of the Longest consecutive subsequence is \" + findLongestConseqSubseq(arr, n)); }}// This code is contributed by Aakash Hasija", "e": 37321, "s": 35930, "text": null }, { "code": "# Python program to find longest contiguous subsequence def findLongestConseqSubseq(arr, n): s = set() ans = 0 # Hash all the array elements for ele in arr: s.add(ele) # check each possible sequence from the start # then update optimal length for i in range(n): # if current element is the starting # element of a sequence if (arr[i]-1) not in s: # Then check for next elements in the # sequence j = arr[i] while(j in s): j += 1 # update optimal length if this length # is more ans = max(ans, j-arr[i]) return ans # Driver codeif __name__ == '__main__': n = 7 arr = [1, 9, 3, 10, 4, 20, 2] print (\"Length of the Longest contiguous subsequence is \",findLongestConseqSubseq(arr, n)) # Contributed by: Harshit Sidhwa", "e": 38198, "s": 37321, "text": null }, { "code": "using System;using System.Collections.Generic; // C# program to find longest consecutive subsequence public class ArrayElements { // Returns length of the // longest consecutive subsequence public static int findLongestConseqSubseq(int[] arr, int n) { HashSet<int> S = new HashSet<int>(); int ans = 0; // Hash all the array elements for (int i = 0; i < n; ++i) { S.Add(arr[i]); } // check each possible sequence from the start // then update optimal length for (int i = 0; i < n; ++i) { // if current element is the starting // element of a sequence if (!S.Contains(arr[i] - 1)) { // Then check for next elements in the // sequence int j = arr[i]; while (S.Contains(j)) { j++; } // update optimal length if this length // is more if (ans < j - arr[i]) { ans = j - arr[i]; } } } return ans; } // Driver code public static void Main(string[] args) { int[] arr = new int[] { 1, 9, 3, 10, 4, 20, 2 }; int n = arr.Length; Console.WriteLine( \"Length of the Longest consecutive subsequence is \" + findLongestConseqSubseq(arr, n)); }} // This code is contributed by Shrikant13", "e": 39733, "s": 38198, "text": null }, { "code": "<script>// Javascript program to find longest// contiguous subsequence // Returns length of the longest// contiguous subsequencefunction findLongestConseqSubseq(arr, n) { let S = new Set(); let ans = 0; // Hash all the array elements for (let i = 0; i < n; i++) S.add(arr[i]); // check each possible sequence from // the start then update optimal length for (let i = 0; i < n; i++) { // if current element is the starting // element of a sequence if (!S.has(arr[i] - 1)) { // Then check for next elements // in the sequence let j = arr[i]; while (S.has(j)) j++; // update optimal length if // this length is more ans = Math.max(ans, j - arr[i]); } } return ans;} // Driver codelet arr = [1, 9, 3, 10, 4, 20, 2];let n = arr.length;document.write(\"Length of the Longest contiguous subsequence is \" + findLongestConseqSubseq(arr, n)); // This code is contributed by gfgking.</script>", "e": 40807, "s": 39733, "text": null }, { "code": null, "e": 40857, "s": 40807, "text": "Length of the Longest contiguous subsequence is 4" }, { "code": null, "e": 40880, "s": 40857, "text": " Complexity Analysis: " }, { "code": null, "e": 41029, "s": 40880, "text": "Time complexity: O(n). Only one traversal is needed and the time complexity is O(n) under the assumption that hash insert and search take O(1) time." }, { "code": null, "e": 41156, "s": 41029, "text": "Auxiliary space: O(n). To store every element in hashmap O(n) space is needed Thanks to Gaurav Ahirwar for the above solution." }, { "code": null, "e": 41174, "s": 41156, "text": "Another Solution:" }, { "code": null, "e": 41286, "s": 41174, "text": "This problem can be solved in O(N log N) time with another Method, this time the Idea is to use Priority Queue." }, { "code": null, "e": 41297, "s": 41286, "text": "Algorithm:" }, { "code": null, "e": 41868, "s": 41297, "text": "Create a Priority Queue to store the elementStore the first element in a variableRemove it from the Priority QueueCheck the difference between this removed first element and the new peek elementIf the difference is equal to 1 increase count by 1 and repeats step 2 and step 3If the difference is greater than 1 set counter to 1 and repeat step 2 and step 3if the difference is equal to 0 repeat step 2 and 3if counter greater than the previous maximum then store counter to maximumContinue step 4 to 7 until we reach the end of the Priority QueueReturn the maximum value" }, { "code": null, "e": 41913, "s": 41868, "text": "Create a Priority Queue to store the element" }, { "code": null, "e": 41951, "s": 41913, "text": "Store the first element in a variable" }, { "code": null, "e": 41985, "s": 41951, "text": "Remove it from the Priority Queue" }, { "code": null, "e": 42066, "s": 41985, "text": "Check the difference between this removed first element and the new peek element" }, { "code": null, "e": 42148, "s": 42066, "text": "If the difference is equal to 1 increase count by 1 and repeats step 2 and step 3" }, { "code": null, "e": 42230, "s": 42148, "text": "If the difference is greater than 1 set counter to 1 and repeat step 2 and step 3" }, { "code": null, "e": 42282, "s": 42230, "text": "if the difference is equal to 0 repeat step 2 and 3" }, { "code": null, "e": 42357, "s": 42282, "text": "if counter greater than the previous maximum then store counter to maximum" }, { "code": null, "e": 42423, "s": 42357, "text": "Continue step 4 to 7 until we reach the end of the Priority Queue" }, { "code": null, "e": 42448, "s": 42423, "text": "Return the maximum value" }, { "code": null, "e": 42452, "s": 42448, "text": "C++" }, { "code": null, "e": 42457, "s": 42452, "text": "Java" }, { "code": "// CPP program for the above approach#include <bits/stdc++.h>using namespace std; int findLongestConseqSubseq(int arr[], int N){ priority_queue<int, vector<int>, greater<int> > pq; for (int i = 0; i < N; i++) { // adding element from // array to PriorityQueue pq.push(arr[i]); } // Storing the first element // of the Priority Queue // This first element is also // the smallest element int prev = pq.top(); pq.pop(); // Taking a counter variable with value 1 int c = 1; // Storing value of max as 1 // as there will always be // one element int max = 1; while (!pq.empty()) { // check if current peek // element minus previous // element is greater then // 1 This is done because // if it's greater than 1 // then the sequence // doesn't start or is broken here if (pq.top() - prev > 1) { // Store the value of counter to 1 // As new sequence may begin c = 1; // Update the previous position with the // current peek And remove it prev = pq.top(); pq.pop(); } // Check if the previous // element and peek are same else if (pq.top() - prev == 0) { // Update the previous position with the // current peek And remove it prev = pq.top(); pq.pop(); } // If the difference // between previous element and peek is 1 else { // Update the counter // These are consecutive elements c++; // Update the previous position // with the current peek And remove it prev = pq.top(); pq.pop(); } // Check if current longest // subsequence is the greatest if (max < c) { // Store the current subsequence count as // max max = c; } } return max;} // Driver Codeint main(){ int arr[] = { 1, 9, 3, 10, 4, 20, 2 }; int n = 7; cout << \"Length of the Longest consecutive subsequence \" \"is \" << findLongestConseqSubseq(arr, n); return 0;}// this code is contributed by Manu Pathria", "e": 44779, "s": 42457, "text": null }, { "code": "// Java Program to find longest consecutive// subsequence This Program uses Priority Queueimport java.io.*;import java.util.PriorityQueue;public class Longset_Sub{ // return the length of the longest // subsequence of consecutive integers static int findLongestConseqSubseq(int arr[], int N) { PriorityQueue<Integer> pq = new PriorityQueue<Integer>(); for (int i = 0; i < N; i++) { // adding element from // array to PriorityQueue pq.add(arr[i]); } // Storing the first element // of the Priority Queue // This first element is also // the smallest element int prev = pq.poll(); // Taking a counter variable with value 1 int c = 1; // Storing value of max as 1 // as there will always be // one element int max = 1; for (int i = 1; i < N; i++) { // check if current peek // element minus previous // element is greater then // 1 This is done because // if it's greater than 1 // then the sequence // doesn't start or is broken here if (pq.peek() - prev > 1) { // Store the value of counter to 1 // As new sequence may begin c = 1; // Update the previous position with the // current peek And remove it prev = pq.poll(); } // Check if the previous // element and peek are same else if (pq.peek() - prev == 0) { // Update the previous position with the // current peek And remove it prev = pq.poll(); } // if the difference // between previous element and peek is 1 else { // Update the counter // These are consecutive elements c++; // Update the previous position // with the current peek And remove it prev = pq.poll(); } // Check if current longest // subsequence is the greatest if (max < c) { // Store the current subsequence count as // max max = c; } } return max; } // Driver Code public static void main(String args[]) throws IOException { int arr[] = { 1, 9, 3, 10, 4, 20, 2 }; int n = arr.length; System.out.println( \"Length of the Longest consecutive subsequence is \" + findLongestConseqSubseq(arr, n)); }}// This code is contributed by Sudipa Sarkar", "e": 47626, "s": 44779, "text": null }, { "code": null, "e": 47677, "s": 47626, "text": "Length of the Longest consecutive subsequence is 4" }, { "code": null, "e": 47802, "s": 47677, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 47814, "s": 47802, "text": "shrikanth13" }, { "code": null, "e": 47825, "s": 47814, "text": "andrew1234" }, { "code": null, "e": 47837, "s": 47825, "text": "parascoding" }, { "code": null, "e": 47854, "s": 47837, "text": "agrawalvaibhaw96" }, { "code": null, "e": 47867, "s": 47854, "text": "akashgoraya1" }, { "code": null, "e": 47888, "s": 47867, "text": "avanitrachhadiya2155" }, { "code": null, "e": 47906, "s": 47888, "text": "divyeshrabadiya07" }, { "code": null, "e": 47922, "s": 47906, "text": "sudipasarkar999" }, { "code": null, "e": 47934, "s": 47922, "text": "manupathria" }, { "code": null, "e": 47945, "s": 47934, "text": "revathi727" }, { "code": null, "e": 47959, "s": 47945, "text": "lokeshpotta20" }, { "code": null, "e": 47967, "s": 47959, "text": "gfgking" }, { "code": null, "e": 47977, "s": 47967, "text": "CoderSaty" }, { "code": null, "e": 47993, "s": 47977, "text": "amartyaghoshgfg" }, { "code": null, "e": 48000, "s": 47993, "text": "Amazon" }, { "code": null, "e": 48009, "s": 48000, "text": "Linkedin" }, { "code": null, "e": 48021, "s": 48009, "text": "subsequence" }, { "code": null, "e": 48029, "s": 48021, "text": "Walmart" }, { "code": null, "e": 48034, "s": 48029, "text": "Zoho" }, { "code": null, "e": 48041, "s": 48034, "text": "Arrays" }, { "code": null, "e": 48046, "s": 48041, "text": "Hash" }, { "code": null, "e": 48054, "s": 48046, "text": "Sorting" }, { "code": null, "e": 48059, "s": 48054, "text": "Zoho" }, { "code": null, "e": 48066, "s": 48059, "text": "Amazon" }, { "code": null, "e": 48074, "s": 48066, "text": "Walmart" }, { "code": null, "e": 48083, "s": 48074, "text": "Linkedin" }, { "code": null, "e": 48090, "s": 48083, "text": "Arrays" }, { "code": null, "e": 48095, "s": 48090, "text": "Hash" }, { "code": null, "e": 48103, "s": 48095, "text": "Sorting" }, { "code": null, "e": 48201, "s": 48103, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 48224, "s": 48201, "text": "Introduction to Arrays" }, { "code": null, "e": 48256, "s": 48224, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 48277, "s": 48256, "text": "Linked List vs Array" }, { "code": null, "e": 48362, "s": 48277, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 48407, "s": 48362, "text": "Python | Using 2D arrays/lists the right way" }, { "code": null, "e": 48492, "s": 48407, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 48528, "s": 48492, "text": "Internal Working of HashMap in Java" }, { "code": null, "e": 48555, "s": 48528, "text": "Count pairs with given sum" }, { "code": null, "e": 48586, "s": 48555, "text": "Hashing | Set 1 (Introduction)" } ]
StringBuffer substring() method in Java with Examples - GeeksforGeeks
30 Jul, 2019 In StringBuffer class, there are two types of substring method depending upon the parameters passed to it. The substring(int start) method of StringBuffer class is the inbuilt method used to return a substring start from index start and extends to end of this sequence. The string returned by this method contains all character from index start to end of the old sequence. Syntax: public String substring(int start) Parameters: This method accepts only one parameter start which is Integer type value refers to the start index of substring. Return Value: This method returns the substring lie in the range start to end of old sequence. Exception: This method throws StringIndexOutOfBoundsException if start is less than zero, or greater than the length of this object. Below programs illustrate the StringBuffer substring() method: Example 1: // Java program to demonstrate// the substring() Method. class GFG { public static void main(String[] args) { // create a StringBuffer object // with a String pass as parameter StringBuffer str = new StringBuffer("GeeksForGeeks"); // print string System.out.println("String contains = " + str); // get substring start from index 5 // using substring() and print results System.out.println("SubSequence = " + str.substring(5)); }} String contains = GeeksForGeeks SubSequence = ForGeeks Example 2: To demonstrate StringIndexOutOfBoundsException // Java program to demonstrate// Exception thrown by the substring() Method. class GFG { public static void main(String[] args) { // create a StringBuffer object // with a String pass as parameter StringBuffer str = new StringBuffer("Indian Team Played Well"); try { // get substring starts from index -7 // using substring() and print str.substring(-7); } catch (Exception e) { System.out.println("Exception: " + e); } }} Exception: java.lang.StringIndexOutOfBoundsException: String index out of range: -7 The substring(int start, int end) method of StringBuffer class is the inbuilt method used to return a substring start from index start and extends to the index end-1 of this sequence. The string returned by this method contains all character from index start to index end-1 of the old sequence. Syntax: public String substring(int start) Parameters: This method accepts two parameter start which is Integer type value refers to the start index of substring and end which is also a Integer type value refers to the end index of substring. Return Value: This method returns the substring lie in the range index start to index end-1 of old sequence. Exception: This method throws StringIndexOutOfBoundsException if start or end are negative or greater than length(), or start is greater than end. Below programs illustrate the StringBuffer.substring() method: Example 1: // Java program to demonstrate// the substring() Method. class GFG { public static void main(String[] args) { // create a StringBuffer object // with a String pass as parameter StringBuffer str = new StringBuffer("GeeksForGeeks"); // print string System.out.println("String contains = " + str); // get substring start from index 5 to index 8 // using substring() and print results System.out.println("SubSequence = " + str.substring(5, 8)); }} String contains = GeeksForGeeks SubSequence = For Example 2: To demonstrate StringIndexOutOfBoundsException // Java program to demonstrate// Exception thrown by the substring() Method. class GFG { public static void main(String[] args) { // create a StringBuffer object // with a String pass as parameter StringBuffer str = new StringBuffer("Indian Team Played Well"); try { // get substring starts from index 7 // and end at index 3 // using substring() and print str.substring(9, 3); } catch (Exception e) { System.out.println("Exception: " + e); } }} Exception: java.lang.StringIndexOutOfBoundsException: String index out of range: -6 References: https://docs.oracle.com/javase/10/docs/api/java/lang/StringBuffer.html#substring(int, int) https://docs.oracle.com/javase/10/docs/api/java/lang/StringBuffer.html#substring(int) Akanksha_Rai java-basics Java-Functions Java-lang package java-StringBuffer 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": 26185, "s": 26157, "text": "\n30 Jul, 2019" }, { "code": null, "e": 26292, "s": 26185, "text": "In StringBuffer class, there are two types of substring method depending upon the parameters passed to it." }, { "code": null, "e": 26558, "s": 26292, "text": "The substring(int start) method of StringBuffer class is the inbuilt method used to return a substring start from index start and extends to end of this sequence. The string returned by this method contains all character from index start to end of the old sequence." }, { "code": null, "e": 26566, "s": 26558, "text": "Syntax:" }, { "code": null, "e": 26601, "s": 26566, "text": "public String substring(int start)" }, { "code": null, "e": 26726, "s": 26601, "text": "Parameters: This method accepts only one parameter start which is Integer type value refers to the start index of substring." }, { "code": null, "e": 26821, "s": 26726, "text": "Return Value: This method returns the substring lie in the range start to end of old sequence." }, { "code": null, "e": 26954, "s": 26821, "text": "Exception: This method throws StringIndexOutOfBoundsException if start is less than zero, or greater than the length of this object." }, { "code": null, "e": 27017, "s": 26954, "text": "Below programs illustrate the StringBuffer substring() method:" }, { "code": null, "e": 27028, "s": 27017, "text": "Example 1:" }, { "code": "// Java program to demonstrate// the substring() Method. class GFG { public static void main(String[] args) { // create a StringBuffer object // with a String pass as parameter StringBuffer str = new StringBuffer(\"GeeksForGeeks\"); // print string System.out.println(\"String contains = \" + str); // get substring start from index 5 // using substring() and print results System.out.println(\"SubSequence = \" + str.substring(5)); }}", "e": 27593, "s": 27028, "text": null }, { "code": null, "e": 27649, "s": 27593, "text": "String contains = GeeksForGeeks\nSubSequence = ForGeeks\n" }, { "code": null, "e": 27707, "s": 27649, "text": "Example 2: To demonstrate StringIndexOutOfBoundsException" }, { "code": "// Java program to demonstrate// Exception thrown by the substring() Method. class GFG { public static void main(String[] args) { // create a StringBuffer object // with a String pass as parameter StringBuffer str = new StringBuffer(\"Indian Team Played Well\"); try { // get substring starts from index -7 // using substring() and print str.substring(-7); } catch (Exception e) { System.out.println(\"Exception: \" + e); } }}", "e": 28250, "s": 27707, "text": null }, { "code": null, "e": 28335, "s": 28250, "text": "Exception: java.lang.StringIndexOutOfBoundsException: String index out of range: -7\n" }, { "code": null, "e": 28630, "s": 28335, "text": "The substring(int start, int end) method of StringBuffer class is the inbuilt method used to return a substring start from index start and extends to the index end-1 of this sequence. The string returned by this method contains all character from index start to index end-1 of the old sequence." }, { "code": null, "e": 28638, "s": 28630, "text": "Syntax:" }, { "code": null, "e": 28673, "s": 28638, "text": "public String substring(int start)" }, { "code": null, "e": 28873, "s": 28673, "text": "Parameters: This method accepts two parameter start which is Integer type value refers to the start index of substring and end which is also a Integer type value refers to the end index of substring." }, { "code": null, "e": 28982, "s": 28873, "text": "Return Value: This method returns the substring lie in the range index start to index end-1 of old sequence." }, { "code": null, "e": 29129, "s": 28982, "text": "Exception: This method throws StringIndexOutOfBoundsException if start or end are negative or greater than length(), or start is greater than end." }, { "code": null, "e": 29192, "s": 29129, "text": "Below programs illustrate the StringBuffer.substring() method:" }, { "code": null, "e": 29203, "s": 29192, "text": "Example 1:" }, { "code": "// Java program to demonstrate// the substring() Method. class GFG { public static void main(String[] args) { // create a StringBuffer object // with a String pass as parameter StringBuffer str = new StringBuffer(\"GeeksForGeeks\"); // print string System.out.println(\"String contains = \" + str); // get substring start from index 5 to index 8 // using substring() and print results System.out.println(\"SubSequence = \" + str.substring(5, 8)); }}", "e": 29756, "s": 29203, "text": null }, { "code": null, "e": 29807, "s": 29756, "text": "String contains = GeeksForGeeks\nSubSequence = For\n" }, { "code": null, "e": 29865, "s": 29807, "text": "Example 2: To demonstrate StringIndexOutOfBoundsException" }, { "code": "// Java program to demonstrate// Exception thrown by the substring() Method. class GFG { public static void main(String[] args) { // create a StringBuffer object // with a String pass as parameter StringBuffer str = new StringBuffer(\"Indian Team Played Well\"); try { // get substring starts from index 7 // and end at index 3 // using substring() and print str.substring(9, 3); } catch (Exception e) { System.out.println(\"Exception: \" + e); } }}", "e": 30444, "s": 29865, "text": null }, { "code": null, "e": 30529, "s": 30444, "text": "Exception: java.lang.StringIndexOutOfBoundsException: String index out of range: -6\n" }, { "code": null, "e": 30541, "s": 30529, "text": "References:" }, { "code": null, "e": 30632, "s": 30541, "text": "https://docs.oracle.com/javase/10/docs/api/java/lang/StringBuffer.html#substring(int, int)" }, { "code": null, "e": 30718, "s": 30632, "text": "https://docs.oracle.com/javase/10/docs/api/java/lang/StringBuffer.html#substring(int)" }, { "code": null, "e": 30731, "s": 30718, "text": "Akanksha_Rai" }, { "code": null, "e": 30743, "s": 30731, "text": "java-basics" }, { "code": null, "e": 30758, "s": 30743, "text": "Java-Functions" }, { "code": null, "e": 30776, "s": 30758, "text": "Java-lang package" }, { "code": null, "e": 30794, "s": 30776, "text": "java-StringBuffer" }, { "code": null, "e": 30799, "s": 30794, "text": "Java" }, { "code": null, "e": 30804, "s": 30799, "text": "Java" }, { "code": null, "e": 30902, "s": 30804, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30953, "s": 30902, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 30983, "s": 30953, "text": "HashMap in Java with Examples" }, { "code": null, "e": 31002, "s": 30983, "text": "Interfaces in Java" }, { "code": null, "e": 31017, "s": 31002, "text": "Stream In Java" }, { "code": null, "e": 31048, "s": 31017, "text": "How to iterate any Map in Java" }, { "code": null, "e": 31066, "s": 31048, "text": "ArrayList in Java" }, { "code": null, "e": 31098, "s": 31066, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 31118, "s": 31098, "text": "Stack Class in Java" }, { "code": null, "e": 31150, "s": 31118, "text": "Multidimensional Arrays in Java" } ]
Pandas - Find the Difference between two Dataframes - GeeksforGeeks
16 Mar, 2021 In this article, we will discuss how to compare two DataFrames in pandas. First, let’s create two DataFrames. Creating two dataframes Python3 import pandas as pd # first dataframedf1 = pd.DataFrame({ 'Age': ['20', '14', '56', '28', '10'], 'Weight': [59, 29, 73, 56, 48]})display(df1) # second dataframedf2 = pd.DataFrame({ 'Age': ['16', '20', '24', '40', '22'], 'Weight': [55, 59, 73, 85, 56]})display(df2) Output: By using equals() function we can directly check if df1 is equal to df2. This function is used to determine if two dataframe objects in consideration are equal or not. Unlike dataframe.eq() method, the result of the operation is a scalar boolean value indicating if the dataframe objects are equal or not. Syntax: DataFrame.equals(df) Example: Python3 df1.equals(df2) Output: False We can also check for a particular column also. Example: Python3 df2['Age'].equals(df1['Age']) Output: False We can use either merge() function or concat() function. The merge() function serves as the entry point for all standard database join operations between DataFrame objects. Merge function is similar to SQL inner join, we find the common rows between two dataframes. The concat() function does all the heavy lifting of performing concatenation operations along with an axis od Pandas objects while performing optional set logic (union or intersection) of the indexes (if any) on the other axes. Example 1: Using merge function Python3 df = df1.merge(df2, how = 'inner' ,indicator=False)df Output: Example 2: Using concat function We add the second dataframe(df2) below the first dataframe(df1) by using concat function. Then we groupby the new dataframe using columns and then we see which rows have a count greater than 1. These are the common rows. This is how we can use- Python3 df = pd.concat([df1, df2]) df = df.reset_index(drop=True) df_group = df.groupby(list(df.columns)) idx = [x[0] for x in df_group.groups.values() if len(x) > 1]df.reindex(idx) Output: We have seen that how we can get the common rows between two dataframes. Now for uncommon rows, we can use concat function with a parameter drop_duplicate. Example: Python3 pd.concat([df1,df2]).drop_duplicates(keep=False) Output: Picked Python pandas-dataFrame Python-pandas Technical Scripter 2020 Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | Get unique values from a list Python | os.path.join() method Defaultdict in Python Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n16 Mar, 2021" }, { "code": null, "e": 25647, "s": 25537, "text": "In this article, we will discuss how to compare two DataFrames in pandas. First, let’s create two DataFrames." }, { "code": null, "e": 25671, "s": 25647, "text": "Creating two dataframes" }, { "code": null, "e": 25679, "s": 25671, "text": "Python3" }, { "code": "import pandas as pd # first dataframedf1 = pd.DataFrame({ 'Age': ['20', '14', '56', '28', '10'], 'Weight': [59, 29, 73, 56, 48]})display(df1) # second dataframedf2 = pd.DataFrame({ 'Age': ['16', '20', '24', '40', '22'], 'Weight': [55, 59, 73, 85, 56]})display(df2)", "e": 25960, "s": 25679, "text": null }, { "code": null, "e": 25968, "s": 25960, "text": "Output:" }, { "code": null, "e": 26274, "s": 25968, "text": "By using equals() function we can directly check if df1 is equal to df2. This function is used to determine if two dataframe objects in consideration are equal or not. Unlike dataframe.eq() method, the result of the operation is a scalar boolean value indicating if the dataframe objects are equal or not." }, { "code": null, "e": 26282, "s": 26274, "text": "Syntax:" }, { "code": null, "e": 26303, "s": 26282, "text": "DataFrame.equals(df)" }, { "code": null, "e": 26312, "s": 26303, "text": "Example:" }, { "code": null, "e": 26320, "s": 26312, "text": "Python3" }, { "code": "df1.equals(df2)", "e": 26336, "s": 26320, "text": null }, { "code": null, "e": 26344, "s": 26336, "text": "Output:" }, { "code": null, "e": 26350, "s": 26344, "text": "False" }, { "code": null, "e": 26398, "s": 26350, "text": "We can also check for a particular column also." }, { "code": null, "e": 26407, "s": 26398, "text": "Example:" }, { "code": null, "e": 26415, "s": 26407, "text": "Python3" }, { "code": "df2['Age'].equals(df1['Age'])", "e": 26445, "s": 26415, "text": null }, { "code": null, "e": 26453, "s": 26445, "text": "Output:" }, { "code": null, "e": 26459, "s": 26453, "text": "False" }, { "code": null, "e": 26517, "s": 26459, "text": "We can use either merge() function or concat() function. " }, { "code": null, "e": 26727, "s": 26517, "text": "The merge() function serves as the entry point for all standard database join operations between DataFrame objects. Merge function is similar to SQL inner join, we find the common rows between two dataframes. " }, { "code": null, "e": 26955, "s": 26727, "text": "The concat() function does all the heavy lifting of performing concatenation operations along with an axis od Pandas objects while performing optional set logic (union or intersection) of the indexes (if any) on the other axes." }, { "code": null, "e": 26987, "s": 26955, "text": "Example 1: Using merge function" }, { "code": null, "e": 26995, "s": 26987, "text": "Python3" }, { "code": "df = df1.merge(df2, how = 'inner' ,indicator=False)df", "e": 27049, "s": 26995, "text": null }, { "code": null, "e": 27057, "s": 27049, "text": "Output:" }, { "code": null, "e": 27090, "s": 27057, "text": "Example 2: Using concat function" }, { "code": null, "e": 27335, "s": 27090, "text": "We add the second dataframe(df2) below the first dataframe(df1) by using concat function. Then we groupby the new dataframe using columns and then we see which rows have a count greater than 1. These are the common rows. This is how we can use-" }, { "code": null, "e": 27343, "s": 27335, "text": "Python3" }, { "code": "df = pd.concat([df1, df2]) df = df.reset_index(drop=True) df_group = df.groupby(list(df.columns)) idx = [x[0] for x in df_group.groups.values() if len(x) > 1]df.reindex(idx)", "e": 27520, "s": 27343, "text": null }, { "code": null, "e": 27528, "s": 27520, "text": "Output:" }, { "code": null, "e": 27685, "s": 27528, "text": "We have seen that how we can get the common rows between two dataframes. Now for uncommon rows, we can use concat function with a parameter drop_duplicate. " }, { "code": null, "e": 27694, "s": 27685, "text": "Example:" }, { "code": null, "e": 27702, "s": 27694, "text": "Python3" }, { "code": "pd.concat([df1,df2]).drop_duplicates(keep=False)", "e": 27751, "s": 27702, "text": null }, { "code": null, "e": 27759, "s": 27751, "text": "Output:" }, { "code": null, "e": 27766, "s": 27759, "text": "Picked" }, { "code": null, "e": 27790, "s": 27766, "text": "Python pandas-dataFrame" }, { "code": null, "e": 27804, "s": 27790, "text": "Python-pandas" }, { "code": null, "e": 27828, "s": 27804, "text": "Technical Scripter 2020" }, { "code": null, "e": 27835, "s": 27828, "text": "Python" }, { "code": null, "e": 27854, "s": 27835, "text": "Technical Scripter" }, { "code": null, "e": 27952, "s": 27854, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27984, "s": 27952, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28026, "s": 27984, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28068, "s": 28026, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28124, "s": 28068, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28151, "s": 28124, "text": "Python Classes and Objects" }, { "code": null, "e": 28190, "s": 28151, "text": "Python | Get unique values from a list" }, { "code": null, "e": 28221, "s": 28190, "text": "Python | os.path.join() method" }, { "code": null, "e": 28243, "s": 28221, "text": "Defaultdict in Python" }, { "code": null, "e": 28272, "s": 28243, "text": "Create a directory in Python" } ]
continue command in Linux with examples - GeeksforGeeks
15 May, 2019 continue is a command which is used to skip the current iteration in for, while and until loop. It takes one more parameter [N], if N is mentioned then it continues from the nth enclosing loop. Syntax: continue or continue [N] continue statement in for loop : continue statement in while loop : continue statement in until loop : continue --help : Displays help information. DrRoot_ linux-command Linux-Shell-Commands Picked Technical Scripter 2018 Linux-Unix Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. tar command in Linux with examples curl command in Linux with Examples Conditional Statements | Shell Script UDP Server-Client implementation in C Tail command in Linux with examples Cat command in Linux with examples touch command in Linux with Examples echo command in Linux with Examples scp command in Linux with Examples Compiling with g++
[ { "code": null, "e": 25259, "s": 25231, "text": "\n15 May, 2019" }, { "code": null, "e": 25453, "s": 25259, "text": "continue is a command which is used to skip the current iteration in for, while and until loop. It takes one more parameter [N], if N is mentioned then it continues from the nth enclosing loop." }, { "code": null, "e": 25461, "s": 25453, "text": "Syntax:" }, { "code": null, "e": 25487, "s": 25461, "text": "continue\nor \ncontinue [N]" }, { "code": null, "e": 25522, "s": 25489, "text": "continue statement in for loop :" }, { "code": null, "e": 25557, "s": 25522, "text": "continue statement in while loop :" }, { "code": null, "e": 25592, "s": 25557, "text": "continue statement in until loop :" }, { "code": null, "e": 25637, "s": 25592, "text": "continue --help : Displays help information." }, { "code": null, "e": 25645, "s": 25637, "text": "DrRoot_" }, { "code": null, "e": 25659, "s": 25645, "text": "linux-command" }, { "code": null, "e": 25680, "s": 25659, "text": "Linux-Shell-Commands" }, { "code": null, "e": 25687, "s": 25680, "text": "Picked" }, { "code": null, "e": 25711, "s": 25687, "text": "Technical Scripter 2018" }, { "code": null, "e": 25722, "s": 25711, "text": "Linux-Unix" }, { "code": null, "e": 25741, "s": 25722, "text": "Technical Scripter" }, { "code": null, "e": 25839, "s": 25741, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25874, "s": 25839, "text": "tar command in Linux with examples" }, { "code": null, "e": 25910, "s": 25874, "text": "curl command in Linux with Examples" }, { "code": null, "e": 25948, "s": 25910, "text": "Conditional Statements | Shell Script" }, { "code": null, "e": 25986, "s": 25948, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 26022, "s": 25986, "text": "Tail command in Linux with examples" }, { "code": null, "e": 26057, "s": 26022, "text": "Cat command in Linux with examples" }, { "code": null, "e": 26094, "s": 26057, "text": "touch command in Linux with Examples" }, { "code": null, "e": 26130, "s": 26094, "text": "echo command in Linux with Examples" }, { "code": null, "e": 26165, "s": 26130, "text": "scp command in Linux with Examples" } ]
Finite and Infinite Recursion with examples - GeeksforGeeks
23 Jul, 2021 The process in which a function calls itself directly or indirectly is called Recursion and the corresponding function is called a Recursive function. Using Recursion, certain problems can be solved quite easily. Examples of such problems are Towers of Hanoi (TOH), Inorder/Preorder/Postorder Tree Traversals, DFS, etc. Types of Recursions: Recursion can be further classified into two kinds, depending on when they terminate: Finite RecursionInfinite Recursion Finite Recursion Infinite Recursion Finite Recursion: Finite Recursion occurs when the recursion terminates after a finite number of recursive calls. A recursion terminates only when a base condition is met. Example: Below is an implementation to demonstrate Finite Recursion. C++ Java Python3 C# Javascript // C++ program to demsonstrate Finite Recursion#include <bits/stdc++.h>using namespace std; // Recursive functionvoid Geek(int N){ // Base condition // When this condition is met, // the recursion terminates if (N == 0) return; // Print the current value of N cout << N << " "; // Call itself recursively Geek(N - 1);} // Driver codeint main(){ // Initial value of N int N = 5; // Call the recursive function Geek(N); return 0;} // Java program for the above approachclass GFG{ // Recursive functionstatic void Geek(int N){ // Base condition // When this condition is met, // the recursion terminates if (N == 0) return; // Print the current value of N System.out.println(N + " "); // Call itself recursively Geek(N - 1);} // Driver codepublic static void main(String[] args){ // Initial value of N int N = 5; // Call the recursive function Geek(N);}} // This code is contributed by abhinavjain194 # Python program to demsonstrate Finite Recursion# Recursive functiondef Geek( N): # Base condition # When this condition is met, # the recursion terminates if (N == 0): return # Pr the current value of N print( N, end =" " ) # Call itself recursively Geek(N - 1) # Driver code# Initial value of NN = 5 # Call the recursive functionGeek(N) # this code is contributed by shivanisinghss2110 // C# program for the above approachusing System;using System.Collections.Generic; class GFG{ // Recursive functionstatic void Geek(int N){ // Base condition // When this condition is met, // the recursion terminates if (N == 0) return; // Print the current value of N Console.Write(N + " "); // Call itself recursively Geek(N - 1);} // Driver Codepublic static void Main(String[] args){ // Initial value of N int N = 5; // Call the recursive function Geek(N);}} // This code is contributed by target_2. <script> // JavaScript program to demsonstrate Finite Recursion// Recursive functionfunction Geek(N){ // Base condition // When this condition is met, // the recursion terminates if (N == 0) return; // Print the current value of N document.write(N +" "); // Call itself recursively Geek(N - 1);} // Driver code// Initial value of N var N = 5; // Call the recursive function Geek(N); // this code is contributed by shivanisinghss2110 </script> 5 4 3 2 1 The recursion tree for the above recursive function looks like this. Recursion Tree When the value of N becomes 0, because of the base condition, the recursion terminates. Infinite Recursion: Infinite Recursion occurs when the recursion does not terminate after a finite number of recursive calls. As the base condition is never met, the recursion carries on infinitely. Example: Below is an implementation to demonstrate Infinite Recursion. C++ Java Python3 C# Javascript // C++ program to demsonstrate Infinite Recursion#include <bits/stdc++.h>using namespace std; // Recursive functionvoid Geek(int N){ // Base condition // This condition is never met here if (N == 0) return; // Print the current value of N cout << N << " "; // Call itself recursively Geek(N);} // Driver codeint main(){ // Initial value of N int N = 5; // Call the recursive function Geek(N); return 0;} // Java program to demsonstrate Infinite Recursionimport java.io.*; class GFG{// Recursive functionstatic void Geek(int N){ // Base condition // This condition is never met here if (N == 0) return; // Print the current value of N System.out.print( N +" "); // Call itself recursively Geek(N);} // Driver codepublic static void main(String[] args) { // Initial value of N int N = 5; // Call the recursive function Geek(N); }} // This code is contributed by shivanisinghss2110 # Python3 to demsonstrate Infinite Recursion # Recursive functiondef Geek(N): # Base condition # This condition is never met here if (N == 0): return # Print the current value of N print(N, end = " " ) # Call itself recursively Geek(N) # Driver code # Initial value of NN = 5 # Call the recursive functionGeek(N) # This code is contributed by shivanisinghss2110 // C# program to demsonstrate Infinite Recursionusing System; class GFG{// Recursive functionstatic void Geek(int N){ // Base condition // This condition is never met here if (N == 0) return; // Print the current value of N Console.Write( N +" "); // Call itself recursively Geek(N);} // Driver codepublic static void Main(String[] args) { // Initial value of N int N = 5; // Call the recursive function Geek(N); }} // This code is contributed by shivanisinghss2110 <script>// JavaScript program to demsonstrate Infinite Recursion// Recursive functionfunction Geek(N){ // Base condition // This condition is never met here if (N == 0) return; // Print the current value of N document.write( N +" "); // Call itself recursively Geek(N);} // Driver code // Initial value of N var N = 5; // Call the recursive function Geek(N); // This code is contributed by shivanisinghss2110</script> The recursion tree for the above recursive function looks like this. Recursion Tree Since the value of N never becomes 0, so the recursion never terminates. Instead, the recursion continues until the implicit stack becomes full which results in a Stack Overflow. Some compilers directly give the output as Segmentation Fault (Core Dumped), while others may abnormally terminate for some value and then show Segmentation fault. abhinavjain194 target_2 shivanisinghss2110 GATE-CS-C-Language C Language C++ Recursion Recursion CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. TCP Server-Client implementation in C Exception Handling in C++ Multithreading in C 'this' pointer in C++ Arrow operator -> in C/C++ with Examples Vector in C++ STL Initialize a vector in C++ (6 different ways) Inheritance in C++ Map in C++ Standard Template Library (STL) C++ Classes and Objects
[ { "code": null, "e": 25531, "s": 25503, "text": "\n23 Jul, 2021" }, { "code": null, "e": 25851, "s": 25531, "text": "The process in which a function calls itself directly or indirectly is called Recursion and the corresponding function is called a Recursive function. Using Recursion, certain problems can be solved quite easily. Examples of such problems are Towers of Hanoi (TOH), Inorder/Preorder/Postorder Tree Traversals, DFS, etc." }, { "code": null, "e": 25872, "s": 25851, "text": "Types of Recursions:" }, { "code": null, "e": 25958, "s": 25872, "text": "Recursion can be further classified into two kinds, depending on when they terminate:" }, { "code": null, "e": 25993, "s": 25958, "text": "Finite RecursionInfinite Recursion" }, { "code": null, "e": 26010, "s": 25993, "text": "Finite Recursion" }, { "code": null, "e": 26029, "s": 26010, "text": "Infinite Recursion" }, { "code": null, "e": 26047, "s": 26029, "text": "Finite Recursion:" }, { "code": null, "e": 26201, "s": 26047, "text": "Finite Recursion occurs when the recursion terminates after a finite number of recursive calls. A recursion terminates only when a base condition is met." }, { "code": null, "e": 26210, "s": 26201, "text": "Example:" }, { "code": null, "e": 26270, "s": 26210, "text": "Below is an implementation to demonstrate Finite Recursion." }, { "code": null, "e": 26274, "s": 26270, "text": "C++" }, { "code": null, "e": 26279, "s": 26274, "text": "Java" }, { "code": null, "e": 26287, "s": 26279, "text": "Python3" }, { "code": null, "e": 26290, "s": 26287, "text": "C#" }, { "code": null, "e": 26301, "s": 26290, "text": "Javascript" }, { "code": "// C++ program to demsonstrate Finite Recursion#include <bits/stdc++.h>using namespace std; // Recursive functionvoid Geek(int N){ // Base condition // When this condition is met, // the recursion terminates if (N == 0) return; // Print the current value of N cout << N << \" \"; // Call itself recursively Geek(N - 1);} // Driver codeint main(){ // Initial value of N int N = 5; // Call the recursive function Geek(N); return 0;}", "e": 26780, "s": 26301, "text": null }, { "code": "// Java program for the above approachclass GFG{ // Recursive functionstatic void Geek(int N){ // Base condition // When this condition is met, // the recursion terminates if (N == 0) return; // Print the current value of N System.out.println(N + \" \"); // Call itself recursively Geek(N - 1);} // Driver codepublic static void main(String[] args){ // Initial value of N int N = 5; // Call the recursive function Geek(N);}} // This code is contributed by abhinavjain194", "e": 27305, "s": 26780, "text": null }, { "code": "# Python program to demsonstrate Finite Recursion# Recursive functiondef Geek( N): # Base condition # When this condition is met, # the recursion terminates if (N == 0): return # Pr the current value of N print( N, end =\" \" ) # Call itself recursively Geek(N - 1) # Driver code# Initial value of NN = 5 # Call the recursive functionGeek(N) # this code is contributed by shivanisinghss2110", "e": 27729, "s": 27305, "text": null }, { "code": "// C# program for the above approachusing System;using System.Collections.Generic; class GFG{ // Recursive functionstatic void Geek(int N){ // Base condition // When this condition is met, // the recursion terminates if (N == 0) return; // Print the current value of N Console.Write(N + \" \"); // Call itself recursively Geek(N - 1);} // Driver Codepublic static void Main(String[] args){ // Initial value of N int N = 5; // Call the recursive function Geek(N);}} // This code is contributed by target_2.", "e": 28291, "s": 27729, "text": null }, { "code": "<script> // JavaScript program to demsonstrate Finite Recursion// Recursive functionfunction Geek(N){ // Base condition // When this condition is met, // the recursion terminates if (N == 0) return; // Print the current value of N document.write(N +\" \"); // Call itself recursively Geek(N - 1);} // Driver code// Initial value of N var N = 5; // Call the recursive function Geek(N); // this code is contributed by shivanisinghss2110 </script>", "e": 28783, "s": 28291, "text": null }, { "code": null, "e": 28794, "s": 28783, "text": "5 4 3 2 1 " }, { "code": null, "e": 28863, "s": 28794, "text": "The recursion tree for the above recursive function looks like this." }, { "code": null, "e": 28878, "s": 28863, "text": "Recursion Tree" }, { "code": null, "e": 28966, "s": 28878, "text": "When the value of N becomes 0, because of the base condition, the recursion terminates." }, { "code": null, "e": 28986, "s": 28966, "text": "Infinite Recursion:" }, { "code": null, "e": 29165, "s": 28986, "text": "Infinite Recursion occurs when the recursion does not terminate after a finite number of recursive calls. As the base condition is never met, the recursion carries on infinitely." }, { "code": null, "e": 29175, "s": 29165, "text": "Example: " }, { "code": null, "e": 29238, "s": 29175, "text": "Below is an implementation to demonstrate Infinite Recursion. " }, { "code": null, "e": 29242, "s": 29238, "text": "C++" }, { "code": null, "e": 29247, "s": 29242, "text": "Java" }, { "code": null, "e": 29255, "s": 29247, "text": "Python3" }, { "code": null, "e": 29258, "s": 29255, "text": "C#" }, { "code": null, "e": 29269, "s": 29258, "text": "Javascript" }, { "code": "// C++ program to demsonstrate Infinite Recursion#include <bits/stdc++.h>using namespace std; // Recursive functionvoid Geek(int N){ // Base condition // This condition is never met here if (N == 0) return; // Print the current value of N cout << N << \" \"; // Call itself recursively Geek(N);} // Driver codeint main(){ // Initial value of N int N = 5; // Call the recursive function Geek(N); return 0;}", "e": 29720, "s": 29269, "text": null }, { "code": "// Java program to demsonstrate Infinite Recursionimport java.io.*; class GFG{// Recursive functionstatic void Geek(int N){ // Base condition // This condition is never met here if (N == 0) return; // Print the current value of N System.out.print( N +\" \"); // Call itself recursively Geek(N);} // Driver codepublic static void main(String[] args) { // Initial value of N int N = 5; // Call the recursive function Geek(N); }} // This code is contributed by shivanisinghss2110", "e": 30246, "s": 29720, "text": null }, { "code": "# Python3 to demsonstrate Infinite Recursion # Recursive functiondef Geek(N): # Base condition # This condition is never met here if (N == 0): return # Print the current value of N print(N, end = \" \" ) # Call itself recursively Geek(N) # Driver code # Initial value of NN = 5 # Call the recursive functionGeek(N) # This code is contributed by shivanisinghss2110", "e": 30643, "s": 30246, "text": null }, { "code": "// C# program to demsonstrate Infinite Recursionusing System; class GFG{// Recursive functionstatic void Geek(int N){ // Base condition // This condition is never met here if (N == 0) return; // Print the current value of N Console.Write( N +\" \"); // Call itself recursively Geek(N);} // Driver codepublic static void Main(String[] args) { // Initial value of N int N = 5; // Call the recursive function Geek(N); }} // This code is contributed by shivanisinghss2110", "e": 31160, "s": 30643, "text": null }, { "code": "<script>// JavaScript program to demsonstrate Infinite Recursion// Recursive functionfunction Geek(N){ // Base condition // This condition is never met here if (N == 0) return; // Print the current value of N document.write( N +\" \"); // Call itself recursively Geek(N);} // Driver code // Initial value of N var N = 5; // Call the recursive function Geek(N); // This code is contributed by shivanisinghss2110</script>", "e": 31621, "s": 31160, "text": null }, { "code": null, "e": 31690, "s": 31621, "text": "The recursion tree for the above recursive function looks like this." }, { "code": null, "e": 31705, "s": 31690, "text": "Recursion Tree" }, { "code": null, "e": 32049, "s": 31705, "text": "Since the value of N never becomes 0, so the recursion never terminates. Instead, the recursion continues until the implicit stack becomes full which results in a Stack Overflow. Some compilers directly give the output as Segmentation Fault (Core Dumped), while others may abnormally terminate for some value and then show Segmentation fault. " }, { "code": null, "e": 32064, "s": 32049, "text": "abhinavjain194" }, { "code": null, "e": 32073, "s": 32064, "text": "target_2" }, { "code": null, "e": 32092, "s": 32073, "text": "shivanisinghss2110" }, { "code": null, "e": 32111, "s": 32092, "text": "GATE-CS-C-Language" }, { "code": null, "e": 32122, "s": 32111, "text": "C Language" }, { "code": null, "e": 32126, "s": 32122, "text": "C++" }, { "code": null, "e": 32136, "s": 32126, "text": "Recursion" }, { "code": null, "e": 32146, "s": 32136, "text": "Recursion" }, { "code": null, "e": 32150, "s": 32146, "text": "CPP" }, { "code": null, "e": 32248, "s": 32150, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32286, "s": 32248, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 32312, "s": 32286, "text": "Exception Handling in C++" }, { "code": null, "e": 32332, "s": 32312, "text": "Multithreading in C" }, { "code": null, "e": 32354, "s": 32332, "text": "'this' pointer in C++" }, { "code": null, "e": 32395, "s": 32354, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 32413, "s": 32395, "text": "Vector in C++ STL" }, { "code": null, "e": 32459, "s": 32413, "text": "Initialize a vector in C++ (6 different ways)" }, { "code": null, "e": 32478, "s": 32459, "text": "Inheritance in C++" }, { "code": null, "e": 32521, "s": 32478, "text": "Map in C++ Standard Template Library (STL)" } ]
Granting Permissions to Roles in Cassandra - GeeksforGeeks
05 Jun, 2020 In this article, we are going to discuss how we can granting permission to roles in Cassandra. First, we will create a new role and show how it can access the database. Creating a new role:In this step, we are going to create a new role such that user_access is a new role and want to access the database. To create a new role using the following cqlsh query. cassandra@cqlsh> create role user_access ... with password = 'user_access' ... and LOGIN = true; Output: Now, If we can see “user_access” role access by using the following cqlsh query. cassandra@cqlsh> list all permissions of 'user_access'; role | resource | permissions ------+----------+------------- (0 rows) cassandra@cqlsh> Right now, it can’t access the Existing keyspace ‘University’. let’s have a look. cassandra@cqlsh> login user_access Password:user_access user_access@cqlsh> Output: To resolve this error “Unauthorized: Error from server: code=2100 [Unauthorized] message=”User user_access has no SELECT permission on Consider if we want only access “student” table on university keyspace then we can use the following cqlsh query. cassandra@cqlsh> grant all permissions on university.student to user_access; Only we can grant permission to access “university.student” table. Output: Now, used the following cqlsh query if we want to give the grant access to all tables on a university keyspace. cassandra@cqlsh> grant all permissions on keyspace university to user_access; We can see all the permissions by using “list all permissions”. Output: If we want to give the grant access to the full database then used the following cqlsh query. cassandra@cqlsh> grant all permissions on all keyspaces to user_access; Output: Ashish_rana Apache DBMS GBlog Write From Home DBMS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. SQL Interview Questions Introduction of B-Tree CTE in SQL Difference between Clustered and Non-clustered index Data Preprocessing in Data Mining Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ... DSA Sheet by Love Babbar Socket Programming in C/C++ GET and POST requests using Python Must Do Coding Questions for Product Based Companies
[ { "code": null, "e": 25223, "s": 25195, "text": "\n05 Jun, 2020" }, { "code": null, "e": 25392, "s": 25223, "text": "In this article, we are going to discuss how we can granting permission to roles in Cassandra. First, we will create a new role and show how it can access the database." }, { "code": null, "e": 25583, "s": 25392, "text": "Creating a new role:In this step, we are going to create a new role such that user_access is a new role and want to access the database. To create a new role using the following cqlsh query." }, { "code": null, "e": 25687, "s": 25583, "text": "cassandra@cqlsh> create role user_access\n ... with password = 'user_access'\n ... and LOGIN = true;\n" }, { "code": null, "e": 25695, "s": 25687, "text": "Output:" }, { "code": null, "e": 25776, "s": 25695, "text": "Now, If we can see “user_access” role access by using the following cqlsh query." }, { "code": null, "e": 25924, "s": 25776, "text": "cassandra@cqlsh> list all permissions of 'user_access';\n\n role | resource | permissions\n------+----------+-------------\n\n(0 rows)\ncassandra@cqlsh>\n" }, { "code": null, "e": 26006, "s": 25924, "text": "Right now, it can’t access the Existing keyspace ‘University’. let’s have a look." }, { "code": null, "e": 26082, "s": 26006, "text": "cassandra@cqlsh> login user_access\nPassword:user_access\nuser_access@cqlsh> " }, { "code": null, "e": 26090, "s": 26082, "text": "Output:" }, { "code": null, "e": 26225, "s": 26090, "text": "To resolve this error “Unauthorized: Error from server: code=2100 [Unauthorized] message=”User user_access has no SELECT permission on" }, { "code": null, "e": 26339, "s": 26225, "text": "Consider if we want only access “student” table on university keyspace then we can use the following cqlsh query." }, { "code": null, "e": 26357, "s": 26339, "text": "cassandra@cqlsh> " }, { "code": null, "e": 26417, "s": 26357, "text": "grant all permissions on university.student to user_access;" }, { "code": null, "e": 26484, "s": 26417, "text": "Only we can grant permission to access “university.student” table." }, { "code": null, "e": 26492, "s": 26484, "text": "Output:" }, { "code": null, "e": 26604, "s": 26492, "text": "Now, used the following cqlsh query if we want to give the grant access to all tables on a university keyspace." }, { "code": null, "e": 26621, "s": 26604, "text": "cassandra@cqlsh>" }, { "code": null, "e": 26682, "s": 26621, "text": "grant all permissions on keyspace university to user_access;" }, { "code": null, "e": 26746, "s": 26682, "text": "We can see all the permissions by using “list all permissions”." }, { "code": null, "e": 26754, "s": 26746, "text": "Output:" }, { "code": null, "e": 26848, "s": 26754, "text": "If we want to give the grant access to the full database then used the following cqlsh query." }, { "code": null, "e": 26865, "s": 26848, "text": "cassandra@cqlsh>" }, { "code": null, "e": 26920, "s": 26865, "text": "grant all permissions on all keyspaces to user_access;" }, { "code": null, "e": 26928, "s": 26920, "text": "Output:" }, { "code": null, "e": 26940, "s": 26928, "text": "Ashish_rana" }, { "code": null, "e": 26947, "s": 26940, "text": "Apache" }, { "code": null, "e": 26952, "s": 26947, "text": "DBMS" }, { "code": null, "e": 26958, "s": 26952, "text": "GBlog" }, { "code": null, "e": 26974, "s": 26958, "text": "Write From Home" }, { "code": null, "e": 26979, "s": 26974, "text": "DBMS" }, { "code": null, "e": 27077, "s": 26979, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27101, "s": 27077, "text": "SQL Interview Questions" }, { "code": null, "e": 27124, "s": 27101, "text": "Introduction of B-Tree" }, { "code": null, "e": 27135, "s": 27124, "text": "CTE in SQL" }, { "code": null, "e": 27188, "s": 27135, "text": "Difference between Clustered and Non-clustered index" }, { "code": null, "e": 27222, "s": 27188, "text": "Data Preprocessing in Data Mining" }, { "code": null, "e": 27296, "s": 27222, "text": "Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ..." }, { "code": null, "e": 27321, "s": 27296, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 27349, "s": 27321, "text": "Socket Programming in C/C++" }, { "code": null, "e": 27384, "s": 27349, "text": "GET and POST requests using Python" } ]
Print unique rows in a given Binary matrix - GeeksforGeeks
19 Apr, 2022 Given a binary matrix, print all unique rows of the given matrix. Example: Input: {0, 1, 0, 0, 1} {1, 0, 1, 1, 0} {0, 1, 0, 0, 1} {1, 1, 1, 0, 0} Output: 0 1 0 0 1 1 0 1 1 0 1 1 1 0 0 Explanation: The rows are r1={0, 1, 0, 0, 1}, r2={1, 0, 1, 1, 0}, r3={0, 1, 0, 0, 1}, r4={1, 1, 1, 0, 0}, As r1 = r3, remove r3 and print the other rows. Input: {0, 1, 0} {1, 0, 1} {0, 1, 0} Output: 0 1 0 1 0 1 Explanation: The rows are r1={0, 1, 0}, r2={1, 0, 1}, r3={0, 1, 0} As r1 = r3, remove r3 and print the other rows. Method 1: This method explains the simple approach towards solving the above problem. Approach: A simple approach would be to check each row with all processed rows. Print the first row. Now, starting from the second row, for each row, compare the row with already processed rows. If the row matches with any of the processed rows, skip it else print it. Algorithm: Traverse the matrix row-wiseFor each row check if there is any similar row less than the current index.If any two rows are similar then do not print the row.Else print the row. Traverse the matrix row-wise For each row check if there is any similar row less than the current index. If any two rows are similar then do not print the row. Else print the row. Implementation: C++ Java Python3 C# Javascript // Given a binary matrix of M X N of integers,// you need to return only unique rows of binary array#include <bits/stdc++.h>using namespace std;#define ROW 4#define COL 5 // The main function that prints// all unique rows in a given matrix.void findUniqueRows(int M[ROW][COL]){ //Traverse through the matrix for(int i=0; i<ROW; i++) { int flag=0; //check if there is similar column //is already printed, i.e if i and //jth column match. for(int j=0; j<i; j++) { flag=1; for(int k=0; k<=COL; k++) if(M[i][k]!=M[j][k]) flag=0; if(flag==1) break; } //if no row is similar if(flag==0) { //print the row for(int j=0; j<COL; j++) cout<<M[i][j]<<" "; cout<<endl; } }} // Driver Codeint main(){ int M[ROW][COL] = {{0, 1, 0, 0, 1}, {1, 0, 1, 1, 0}, {0, 1, 0, 0, 1}, {1, 0, 1, 0, 0}}; findUniqueRows(M); return 0;} // Given a binary matrix of M X N// of integers, you need to return// only unique rows of binary array class GFG{ static int ROW = 4;static int COL = 5; // Function that prints all// unique rows in a given matrix.static void findUniqueRows(int M[][]){ // Traverse through the matrix for(int i = 0; i < ROW; i++) { int flag = 0; // Check if there is similar column // is already printed, i.e if i and // jth column match. for(int j = 0; j < i; j++) { flag = 1; for(int k = 0; k < COL; k++) if (M[i][k] != M[j][k]) flag = 0; if (flag == 1) break; } // If no row is similar if (flag == 0) { // Print the row for(int j = 0; j < COL; j++) System.out.print(M[i][j] + " "); System.out.println(); } }} // Driver Codepublic static void main(String[] args){ int M[][] = { { 0, 1, 0, 0, 1 }, { 1, 0, 1, 1, 0 }, { 0, 1, 0, 0, 1 }, { 1, 0, 1, 0, 0 } }; findUniqueRows(M);}} // This code is contributed by mark_85 # Given a binary matrix of M X N of# integers, you need to return only# unique rows of binary arrayROW = 4COL = 5 # The main function that prints# all unique rows in a given matrix.def findUniqueRows(M): # Traverse through the matrix for i in range(ROW): flag = 0 # Check if there is similar column # is already printed, i.e if i and # jth column match. for j in range(i): flag = 1 for k in range(COL): if (M[i][k] != M[j][k]): flag = 0 if (flag == 1): break # If no row is similar if (flag == 0): # Print the row for j in range(COL): print(M[i][j], end = " ") print() # Driver Codeif __name__ == '__main__': M = [ [ 0, 1, 0, 0, 1 ], [ 1, 0, 1, 1, 0 ], [ 0, 1, 0, 0, 1 ], [ 1, 0, 1, 0, 0 ] ] findUniqueRows(M) # This code is contributed by mohit kumar 29 // Given a binary matrix of M X N // of integers, you need to return// only unique rows of binary array using System; class GFG{ static int ROW = 4;static int COL = 5; // Function that prints all // unique rows in a given matrix.static void findUniqueRows(int[,] M){ // Traverse through the matrix for(int i = 0; i < ROW; i++) { int flag = 0; // Check if there is similar column // is already printed, i.e if i and // jth column match. for(int j = 0; j < i; j++) { flag = 1; for(int k = 0; k < COL; k++) if (M[i, k] != M[j, k]) flag = 0; if (flag == 1) break; } // If no row is similar if (flag == 0) { // Print the row for(int j = 0; j < COL; j++) Console.Write(M[i, j] + " "); Console.WriteLine(); } }} // Driver codestatic void Main(){ int[,] M = { { 0, 1, 0, 0, 1 }, { 1, 0, 1, 1, 0 }, { 0, 1, 0, 0, 1 }, { 1, 0, 1, 0, 0 } }; findUniqueRows(M);}} // This code is contributed by divyeshrabadiya07 <script>// Given a binary matrix of M X N// of integers, you need to return// only unique rows of binary array let ROW = 4; let COL = 5; // Function that prints all// unique rows in a given matrix. function findUniqueRows(M) { // Traverse through the matrix for(let i = 0; i < ROW; i++) { let flag = 0; // Check if there is similar column // is already printed, i.e if i and // jth column match. for(let j = 0; j < i; j++) { flag = 1; for(let k = 0; k < COL; k++) if (M[i][k] != M[j][k]) flag = 0; if (flag == 1) break; } // If no row is similar if (flag == 0) { // Print the row for(let j = 0; j < COL; j++) document.write(M[i][j] + " "); document.write("<br>"); } } } // Driver Code let M = [ [ 0, 1, 0, 0, 1 ], [ 1, 0, 1, 1, 0 ], [ 0, 1, 0, 0, 1 ], [ 1, 0, 1, 0, 0 ] ] findUniqueRows(M) // This code is contributed by unknown2108</script> Output: 0 1 0 0 1 1 0 1 1 0 1 0 1 0 0 Complexity Analysis: Time complexity: O( ROW^2 x COL ). So for every row check if there is any other similar row. So the time complexity is O( ROW^2 x COL ). Auxiliary Space: O(1). As no extra space is required. Method 2: This method uses Binary Search Tree to solve the above operation. The Binary Search Tree is a node-based binary tree data structure which has the following properties: The left subtree of a node contains only nodes with keys lesser than the node’s key. The right subtree of a node contains only nodes with keys greater than the node’s key. The left and right subtree each must also be a binary search tree. There must be no duplicate nodes. The above properties of Binary Search Tree provide ordering among keys so that the operations like search, minimum and maximum can be done fast. If there is no order, then we may have to compare every key to search a given key. Approach: The process must begin from finding the decimal equivalent of each row and inserting them into a BST. As we know, each node of the BST will contain two fields, one field for the decimal value, other for row number. One must not insert a node if it is duplicated. Finally, traverse the BST and print the corresponding rows. Algorithm: Create a BST in which no duplicate elements can be stored. Create a function to convert a row into decimal and to convert the decimal value into binary array.Traverse through the matrix and insert the row into the BST.Traverse the BST (inorder traversal) and convert the decimal into binary array and print it. Create a BST in which no duplicate elements can be stored. Create a function to convert a row into decimal and to convert the decimal value into binary array. Traverse through the matrix and insert the row into the BST. Traverse the BST (inorder traversal) and convert the decimal into binary array and print it. Implementation: C++14 Java C# Python3 Javascript // Given a binary matrix of M X N of integers,// you need to return only unique rows of binary array#include <bits/stdc++.h>using namespace std;#define ROW 4#define COL 5 class BST{ int data; BST *left, *right; public: // Default constructor. BST(); // Parameterized constructor. BST(int); // Insert function. BST* Insert(BST *, int); // Inorder traversal. void Inorder(BST *);}; //convert array to decimalint convert(int arr[]){ int sum=0; for(int i=0; i<COL; i++) { sum+=pow(2,i)*arr[i]; } return sum;} //print the column represented as integersvoid print(int p){ for(int i=0; i<COL; i++) { cout<<p%2<<" "; p/=2; } cout<<endl;} // Default Constructor definition.BST :: BST() : data(0), left(NULL), right(NULL){} // Parameterized Constructor definition.BST :: BST(int value){ data = value; left = right = NULL;} // Insert function definition.BST* BST :: Insert(BST *root, int value){ if(!root) { // Insert the first node, if root is NULL. return new BST(value); } //if the value is present if(value == root->data) return root; // Insert data. if(value > root->data) { // Insert right node data, if the 'value' // to be inserted is greater than 'root' node data. // Process right nodes. root->right = Insert(root->right, value); } else { // Insert left node data, if the 'value' // to be inserted is greater than 'root' node data. // Process left nodes. root->left = Insert(root->left, value); } // Return 'root' node, after insertion. return root;} // Inorder traversal function.// This gives data in sorted order.void BST :: Inorder(BST *root){ if(!root) { return; } Inorder(root->left); print( root->data ); Inorder(root->right);} // The main function that prints// all unique rows in a given matrix.void findUniqueRows(int M[ROW][COL]){ BST b, *root = NULL; //Traverse through the matrix for(int i=0; i<ROW; i++) { //insert the row into BST root=b.Insert(root,convert(M[i])); } //print b.Inorder(root); } // Driver Codeint main(){ int M[ROW][COL] = {{0, 1, 0, 0, 1}, {1, 0, 1, 1, 0}, {0, 1, 0, 0, 1}, {1, 0, 1, 0, 0}}; findUniqueRows(M); return 0;} // Given a binary matrix of M X N of integers,// you need to return only unique rows of binary arrayimport java.util.*; class GFG{ static class BST { int data; BST left,right; BST(int v){ this.data = v; this.left = this.right = null; } } final static int ROW = 4; final static int COL = 5; // convert array to decimal static int convert(int arr[]) { int sum = 0; for(int i = 0; i < COL; i++) { sum += Math.pow(2,i)*arr[i]; } return sum; } // print the column represented as integers static void print(int p) { for(int i = 0; i < COL; i++) { System.out.print(p%2+" "); p /= 2; } System.out.println(); } // Insert function definition. static BST Insert(BST root, int value) { if(root == null) { // Insert the first node, if root is null. return new BST(value); } //if the value is present if(value == root.data) return root; // Insert data. if(value > root.data) { // Insert right node data, if the 'value' // to be inserted is greater than 'root' node data. // Process right nodes. root.right = Insert(root.right, value); } else { // Insert left node data, if the 'value' // to be inserted is greater than 'root' node data. // Process left nodes. root.left = Insert(root.left, value); } // Return 'root' node, after insertion. return root; } // Inorder traversal function. // This gives data in sorted order. static void Inorder(BST root) { if(root == null) { return; } Inorder(root.left); print( root.data ); Inorder(root.right); } // The main function that prints // all unique rows in a given matrix. static void findUniqueRows(int M[][]) { BST b, root = null; // Traverse through the matrix for(int i = 0; i < ROW; i++) { // insert the row into BST root=Insert(root, convert(M[i])); } //print Inorder(root); } // Driver Code public static void main(String[] args) { int M[][] = {{0, 1, 0, 0, 1}, {1, 0, 1, 1, 0}, {0, 1, 0, 0, 1}, {1, 0, 1, 0, 0}}; findUniqueRows(M); }} // This code is contributed by Rajput-Ji // Given a binary matrix of M X N of integers,// you need to return only unique rows of binary arrayusing System;using System.Collections.Generic; public class GFG{ public class BST { public int data; public BST left,right; public BST(int v){ this.data = v; this.left = this.right = null; } } readonly static int ROW = 4; readonly static int COL = 5; // convert array to decimal static int convert(int []arr) { int sum = 0; for(int i = 0; i < COL; i++) { sum += (int)Math.Pow(2,i)*arr[i]; } return sum; } // print the column represented as integers static void print(int p) { for(int i = 0; i < COL; i++) { Console.Write(p%2+" "); p /= 2; } Console.WriteLine(); } // Insert function definition. static BST Insert(BST root, int value) { if(root == null) { // Insert the first node, if root is null. return new BST(value); } // if the value is present if(value == root.data) return root; // Insert data. if(value > root.data) { // Insert right node data, if the 'value' // to be inserted is greater than 'root' node data. // Process right nodes. root.right = Insert(root.right, value); } else { // Insert left node data, if the 'value' // to be inserted is greater than 'root' node data. // Process left nodes. root.left = Insert(root.left, value); } // Return 'root' node, after insertion. return root; } // Inorder traversal function. // This gives data in sorted order. static void Inorder(BST root) { if(root == null) { return; } Inorder(root.left); print( root.data ); Inorder(root.right); } public static int[] GetRow(int[,] matrix, int row) { var rowLength = matrix.GetLength(1); var rowVector = new int[rowLength]; for (var i = 0; i < rowLength; i++) rowVector[i] = matrix[row, i]; return rowVector; } // The main function that prints // all unique rows in a given matrix. static void findUniqueRows(int [,]M) { BST b, root = null; // Traverse through the matrix for(int i = 0; i < ROW; i++) { // insert the row into BST int[] row = GetRow(M,i); root=Insert(root, convert(row)); } //print Inorder(root); } // Driver Code public static void Main(String[] args) { int [,]M = {{0, 1, 0, 0, 1}, {1, 0, 1, 1, 0}, {0, 1, 0, 0, 1}, {1, 0, 1, 0, 0}}; findUniqueRows(M); }} // This code contributed by Rajput-Ji # Given a binary matrix of M X N of integers,# you need to return only unique rows of binary arrayROW = 4COL = 5 # print the column represented as integersdef Print(p): for i in range(COL): print(p % 2 ,end = " ") p = int(p//2) print("") class BST: def __init__(self,data): self.data = data self.left = None self.right = None # Insert function definition. def Insert(self,root, value): if(not root): # Insert the first node, if root is NULL. return BST(value) #if the value is present if(value == root.data): return root # Insert data. if(value > root.data): # Insert right node data, if the 'value' # to be inserted is greater than 'root' node data. # Process right nodes. root.right = self.Insert(root.right, value) else: # Insert left node data, if the 'value' # to be inserted is greater than 'root' node data. # Process left nodes. root.left = self.Insert(root.left, value) # Return 'root' node, after insertion. return root # Inorder traversal function. # This gives data in sorted order. def Inorder(self,root): if(not root): return self.Inorder(root.left); Print( root.data ); self.Inorder(root.right) # convert array to decimaldef convert(arr): sum=0 for i in range(COL): sum+=pow(2,i)*arr[i] return sum # The main function that prints# all unique rows in a given matrix.def findUniqueRows(M): b,root =BST(0),None #Traverse through the matrix for i in range(ROW): #insert the row into BST root = b.Insert(root,convert(M[i])) #print b.Inorder(root) # Driver CodeM = [[0, 1, 0, 0, 1], [1, 0, 1, 1, 0], [0, 1, 0, 0, 1], [1, 0, 1, 0, 0]] findUniqueRows(M) # This code is contributed by shinjanpatra <script> // Given a binary matrix of M X N of integers,// you need to return only unique rows of binary arrayvar ROW = 4var COL = 5 class BST{ constructor(data) { this.data = data; this.left = null; this.right = null; } // Insert function definition. Insert(root, value) { if(!root) { // Insert the first node, if root is NULL. return new BST(value); } //if the value is present if(value == root.data) return root; // Insert data. if(value > root.data) { // Insert right node data, if the 'value' // to be inserted is greater than 'root' node data. // Process right nodes. root.right = this.Insert(root.right, value); } else { // Insert left node data, if the 'value' // to be inserted is greater than 'root' node data. // Process left nodes. root.left = this.Insert(root.left, value); } // Return 'root' node, after insertion. return root; } // Inorder traversal function. // This gives data in sorted order. Inorder(root) { if(!root) { return; } this.Inorder(root.left); print( root.data ); this.Inorder(root.right); }}; // convert array to decimalfunction convert(arr){ var sum=0; for(var i=0; i<COL; i++) { sum+=Math.pow(2,i)*arr[i]; } return sum;} // print the column represented as integersfunction print(p){ for(var i=0; i<COL; i++) { document.write(p%2 + " "); p=parseInt(p/2); } document.write("<br>");} // The main function that prints// all unique rows in a given matrix.function findUniqueRows(M){ var b =new BST(0),root = null; //Traverse through the matrix for(var i=0; i<ROW; i++) { //insert the row into BST root=b.Insert(root,convert(M[i])); } //print b.Inorder(root); } // Driver Codevar M = [[0, 1, 0, 0, 1], [1, 0, 1, 1, 0], [0, 1, 0, 0, 1], [1, 0, 1, 0, 0]];findUniqueRows(M); // This code is contributed by rutvik_56.</script> Output: 1 0 1 0 0 1 0 1 1 0 0 1 0 0 1 Complexity Analysis: Time complexity: O( ROW x COL + ROW x log( ROW ) ). To traverse the matrix time complexity is O( ROW x COL) and to insert them into BST time complexity is O(log ROW) for each row. So overall time complexity is O( ROW x COL + ROW x log( ROW ) ) Auxiliary Space: O( ROW ). To store the BST O(ROW) space is needed. Method 3: This method uses Trie data structure to solve the above problem. Trie is an efficient information retrieval data structure. Using Trie, search complexities can be brought to an optimal limit (key length). If we store keys in the binary search tree, a well-balanced BST will need time proportional to M * log N, where M is maximum string length and N is the number of keys in the tree. Using Trie, we can search the key in O(M) time. However, the penalty is on Trie storage requirements.Note: This method will lead to Integer Overflow if the number of columns is large. Approach: Since the matrix is boolean, a variant of Trie data structure can be used where each node will be having two children one for 0 and other for 1. Insert each row in the Trie. If the row is already there, don’t print the row. If the row is not there in Trie, insert it in Trie and print it. Algorithm: Create a Trie where rows can be stored.Traverse through the matrix and insert the row into the Trie.Trie cannot store duplicate entries so the duplicates will be removedTraverse the Trie and print the rows. Create a Trie where rows can be stored. Traverse through the matrix and insert the row into the Trie. Trie cannot store duplicate entries so the duplicates will be removed Traverse the Trie and print the rows. Implementation: C++ C // Given a binary matrix of M X N of integers,// you need to return only unique rows of binary array#include <bits/stdc++.h>using namespace std;#define ROW 4#define COL 5 // A Trie nodeclass Node{ public: bool isEndOfCol; Node *child[2]; // Only two children needed for 0 and 1} ; // A utility function to allocate memory// for a new Trie nodeNode* newNode(){ Node* temp = new Node(); temp->isEndOfCol = 0; temp->child[0] = temp->child[1] = NULL; return temp;} // Inserts a new matrix row to Trie.// If row is already present,// then returns 0, otherwise insets the row and// return 1bool insert(Node** root, int (*M)[COL], int row, int col ){ // base case if (*root == NULL) *root = newNode(); // Recur if there are more entries in this row if (col < COL) return insert (&((*root)->child[M[row][col]]), M, row, col + 1); else // If all entries of this row are processed { // unique row found, return 1 if (!((*root)->isEndOfCol)) return (*root)->isEndOfCol = 1; // duplicate row found, return 0 return 0; }} // A utility function to print a rowvoid printRow(int(*M)[COL], int row){ int i; for(i = 0; i < COL; ++i) cout << M[row][i] << " "; cout << endl;} // The main function that prints// all unique rows in a given matrix.void findUniqueRows(int (*M)[COL]){ Node* root = NULL; // create an empty Trie int i; // Iterate through all rows for (i = 0; i < ROW; ++i) // insert row to TRIE if (insert(&root, M, i, 0)) // unique row found, print it printRow(M, i);} // Driver Codeint main(){ int M[ROW][COL] = {{0, 1, 0, 0, 1}, {1, 0, 1, 1, 0}, {0, 1, 0, 0, 1}, {1, 0, 1, 0, 0}}; findUniqueRows(M); return 0;} // This code is contributed by rathbhupendra //Given a binary matrix of M X N of integers, you need to return only unique rows of binary array#include <stdio.h>#include <stdlib.h>#include <stdbool.h> #define ROW 4#define COL 5 // A Trie nodetypedef struct Node{ bool isEndOfCol; struct Node *child[2]; // Only two children needed for 0 and 1} Node; // A utility function to allocate memory for a new Trie nodeNode* newNode(){ Node* temp = (Node *)malloc( sizeof( Node ) ); temp->isEndOfCol = 0; temp->child[0] = temp->child[1] = NULL; return temp;} // Inserts a new matrix row to Trie. If row is already// present, then returns 0, otherwise insets the row and// return 1bool insert( Node** root, int (*M)[COL], int row, int col ){ // base case if ( *root == NULL ) *root = newNode(); // Recur if there are more entries in this row if ( col < COL ) return insert ( &( (*root)->child[ M[row][col] ] ), M, row, col+1 ); else // If all entries of this row are processed { // unique row found, return 1 if ( !( (*root)->isEndOfCol ) ) return (*root)->isEndOfCol = 1; // duplicate row found, return 0 return 0; }} // A utility function to print a rowvoid printRow( int (*M)[COL], int row ){ int i; for( i = 0; i < COL; ++i ) printf( "%d ", M[row][i] ); printf("\n");} // The main function that prints all unique rows in a// given matrix.void findUniqueRows( int (*M)[COL] ){ Node* root = NULL; // create an empty Trie int i; // Iterate through all rows for ( i = 0; i < ROW; ++i ) // insert row to TRIE if ( insert(&root, M, i, 0) ) // unique row found, print it printRow( M, i );} // Driver program to test above functionsint main(){ int M[ROW][COL] = {{0, 1, 0, 0, 1}, {1, 0, 1, 1, 0}, {0, 1, 0, 0, 1}, {1, 0, 1, 0, 0} }; findUniqueRows( M ); return 0;} Output: 0 1 0 0 1 1 0 1 1 0 1 0 1 0 0 Complexity Analysis: Time complexity: O( ROW x COL ). To traverse the matrix and insert in the trie the time complexity is O( ROW x COL). This method has better time complexity. Also, the relative order of rows is maintained while printing but it takes a toll on space. Auxiliary Space: O( ROW x COL ). To store the Trie O(ROW x COL) space complexity is needed. Method 4: This method uses HashSet data structure to solve the above problem. The HashSet class implements the Set interface, backed by a hash table which is actually a HashMap instance. No guarantee is made as to the iteration order of the set which means that the class does not guarantee the constant order of elements over time. This class permits the null element. The class offers constant time performance for the basic operations like add, remove, contains and size assuming the hash function disperses the elements properly among the buckets. Approach: In this method convert the whole row into a single String and then if check it is already present in the HashSet or not. If the row is present then we will leave it otherwise we will print unique row and add it to HashSet. Algorithm: Create a HashSet where rows can be stored as a String.Traverse through the matrix and insert the row as String into the HashSet.HashSet cannot store duplicate entries so the duplicates will be removedTraverse the HashSet and print the rows. Create a HashSet where rows can be stored as a String. Traverse through the matrix and insert the row as String into the HashSet. HashSet cannot store duplicate entries so the duplicates will be removed Traverse the HashSet and print the rows. Implementation: C++ Java Python3 C# Javascript // C++ code to print unique row in a// given binary matrix#include<bits/stdc++.h>using namespace std; void printArray(int arr[][5], int row, int col){ unordered_set<string> uset; for(int i = 0; i < row; i++) { string s = ""; for(int j = 0; j < col; j++) s += to_string(arr[i][j]); if(uset.count(s) == 0) { uset.insert(s); cout << s << endl; } }} // Driver codeint main(){ int arr[][5] = {{0, 1, 0, 0, 1}, {1, 0, 1, 1, 0}, {0, 1, 0, 0, 1}, {1, 1, 1, 0, 0}}; printArray(arr, 4, 5);} // This code is contributed by// rathbhupendra // Java code to print unique row in a// given binary matriximport java.util.HashSet; public class GFG { public static void printArray(int arr[][], int row,int col) { HashSet<String> set = new HashSet<String>(); for(int i = 0; i < row; i++) { String s = ""; for(int j = 0; j < col; j++) s += String.valueOf(arr[i][j]); if(!set.contains(s)) { set.add(s); System.out.println(s); } } } // Driver code public static void main(String[] args) { int arr[][] = { {0, 1, 0, 0, 1}, {1, 0, 1, 1, 0}, {0, 1, 0, 0, 1}, {1, 1, 1, 0, 0} }; printArray(arr, 4, 5); }} # Python3 code to print unique row in a# given binary matrix def printArray(matrix): rowCount = len(matrix) if rowCount == 0: return columnCount = len(matrix[0]) if columnCount == 0: return row_output_format = " ".join(["%s"] * columnCount) printed = {} for row in matrix: routput = row_output_format % tuple(row) if routput not in printed: printed[routput] = True print(routput) # Driver Codemat = [[0, 1, 0, 0, 1], [1, 0, 1, 1, 0], [0, 1, 0, 0, 1], [1, 1, 1, 0, 0]] printArray(mat) # This code is contributed by myronwalker using System;using System.Collections.Generic; // c# code to print unique row in a // given binary matrix public class GFG{ public static void printArray(int[][] arr, int row, int col) { HashSet<string> set = new HashSet<string>(); for (int i = 0; i < row; i++) { string s = ""; for (int j = 0; j < col; j++) { s += arr[i][j].ToString(); } if (!set.Contains(s)) { set.Add(s); Console.WriteLine(s); } } } // Driver code public static void Main(string[] args) { int[][] arr = new int[][] { new int[] {0, 1, 0, 0, 1}, new int[] {1, 0, 1, 1, 0}, new int[] {0, 1, 0, 0, 1}, new int[] {1, 1, 1, 0, 0} }; printArray(arr, 4, 5); }} // This code is contributed by Shrikant13 <script>// Javascript code to print unique row in a// given binary matrix function printArray(arr,row,col){ let set = new Set(); for(let i = 0; i < row; i++) { let s = ""; for(let j = 0; j < col; j++) s += (arr[i][j]).toString(); if(!set.has(s)) { set.add(s); document.write(s+"<br>"); } }} // Driver codelet arr = [[0, 1, 0, 0, 1], [1, 0, 1, 1, 0], [0, 1, 0, 0, 1], [1, 1, 1, 0, 0]];printArray(arr, 4, 5); // This code is contributed by avanitrachhadiya2155</script> Output: 01001 10110 11100 Complexity Analysis: Time complexity: O( ROW x COL ). To traverse the matrix and insert in the HashSet the time complexity is O( ROW x COL) Auxiliary Space: O( ROW ). To store the HashSet O(ROW x COL) space complexity is needed. Thanks, Anshuman Kaushik for suggesting this method. YouTubeGeeksforGeeks507K subscribersPrint unique rows in a given boolean matrix | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 14:56•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=GixyVinjtFk" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Anshuman Kaushik shrikanth13 rathbhupendra myronwalker andrew1234 mohit kumar 29 sujitmeshram divyeshrabadiya07 unknown2108 avanitrachhadiya2155 rutvik_56 Rajput-Ji shinjanpatra Amazon Trie Zoho Advanced Data Structure Matrix Zoho Amazon Matrix Trie Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Decision Tree Introduction with example Ordered Set and GNU C++ PBDS Red-Black Tree | Set 2 (Insert) Disjoint Set Data Structures Binary Indexed Tree or Fenwick Tree Matrix Chain Multiplication | DP-8 Program to find largest element in an array Rat in a Maze | Backtracking-2 Sudoku | Backtracking-7 Find the number of islands | Set 1 (Using DFS)
[ { "code": null, "e": 26231, "s": 26203, "text": "\n19 Apr, 2022" }, { "code": null, "e": 26298, "s": 26231, "text": "Given a binary matrix, print all unique rows of the given matrix. " }, { "code": null, "e": 26308, "s": 26298, "text": "Example: " }, { "code": null, "e": 26826, "s": 26308, "text": "Input:\n {0, 1, 0, 0, 1}\n {1, 0, 1, 1, 0}\n {0, 1, 0, 0, 1}\n {1, 1, 1, 0, 0}\nOutput:\n 0 1 0 0 1 \n 1 0 1 1 0 \n 1 1 1 0 0 \nExplanation: \nThe rows are r1={0, 1, 0, 0, 1}, \nr2={1, 0, 1, 1, 0}, r3={0, 1, 0, 0, 1}, \nr4={1, 1, 1, 0, 0}, As r1 = r3, remove r3\nand print the other rows.\n\nInput:\n {0, 1, 0}\n {1, 0, 1}\n {0, 1, 0}\nOutput:\n 0 1 0\n 1 0 1\nExplanation: \nThe rows are r1={0, 1, 0}, \nr2={1, 0, 1}, r3={0, 1, 0} As r1 = r3,\nremove r3 and print the other rows." }, { "code": null, "e": 26913, "s": 26826, "text": "Method 1: This method explains the simple approach towards solving the above problem. " }, { "code": null, "e": 27182, "s": 26913, "text": "Approach: A simple approach would be to check each row with all processed rows. Print the first row. Now, starting from the second row, for each row, compare the row with already processed rows. If the row matches with any of the processed rows, skip it else print it." }, { "code": null, "e": 27194, "s": 27182, "text": "Algorithm: " }, { "code": null, "e": 27371, "s": 27194, "text": "Traverse the matrix row-wiseFor each row check if there is any similar row less than the current index.If any two rows are similar then do not print the row.Else print the row." }, { "code": null, "e": 27400, "s": 27371, "text": "Traverse the matrix row-wise" }, { "code": null, "e": 27476, "s": 27400, "text": "For each row check if there is any similar row less than the current index." }, { "code": null, "e": 27531, "s": 27476, "text": "If any two rows are similar then do not print the row." }, { "code": null, "e": 27551, "s": 27531, "text": "Else print the row." }, { "code": null, "e": 27568, "s": 27551, "text": "Implementation: " }, { "code": null, "e": 27572, "s": 27568, "text": "C++" }, { "code": null, "e": 27577, "s": 27572, "text": "Java" }, { "code": null, "e": 27585, "s": 27577, "text": "Python3" }, { "code": null, "e": 27588, "s": 27585, "text": "C#" }, { "code": null, "e": 27599, "s": 27588, "text": "Javascript" }, { "code": "// Given a binary matrix of M X N of integers,// you need to return only unique rows of binary array#include <bits/stdc++.h>using namespace std;#define ROW 4#define COL 5 // The main function that prints// all unique rows in a given matrix.void findUniqueRows(int M[ROW][COL]){ //Traverse through the matrix for(int i=0; i<ROW; i++) { int flag=0; //check if there is similar column //is already printed, i.e if i and //jth column match. for(int j=0; j<i; j++) { flag=1; for(int k=0; k<=COL; k++) if(M[i][k]!=M[j][k]) flag=0; if(flag==1) break; } //if no row is similar if(flag==0) { //print the row for(int j=0; j<COL; j++) cout<<M[i][j]<<\" \"; cout<<endl; } }} // Driver Codeint main(){ int M[ROW][COL] = {{0, 1, 0, 0, 1}, {1, 0, 1, 1, 0}, {0, 1, 0, 0, 1}, {1, 0, 1, 0, 0}}; findUniqueRows(M); return 0;}", "e": 28732, "s": 27599, "text": null }, { "code": "// Given a binary matrix of M X N// of integers, you need to return// only unique rows of binary array class GFG{ static int ROW = 4;static int COL = 5; // Function that prints all// unique rows in a given matrix.static void findUniqueRows(int M[][]){ // Traverse through the matrix for(int i = 0; i < ROW; i++) { int flag = 0; // Check if there is similar column // is already printed, i.e if i and // jth column match. for(int j = 0; j < i; j++) { flag = 1; for(int k = 0; k < COL; k++) if (M[i][k] != M[j][k]) flag = 0; if (flag == 1) break; } // If no row is similar if (flag == 0) { // Print the row for(int j = 0; j < COL; j++) System.out.print(M[i][j] + \" \"); System.out.println(); } }} // Driver Codepublic static void main(String[] args){ int M[][] = { { 0, 1, 0, 0, 1 }, { 1, 0, 1, 1, 0 }, { 0, 1, 0, 0, 1 }, { 1, 0, 1, 0, 0 } }; findUniqueRows(M);}} // This code is contributed by mark_85", "e": 29944, "s": 28732, "text": null }, { "code": "# Given a binary matrix of M X N of# integers, you need to return only# unique rows of binary arrayROW = 4COL = 5 # The main function that prints# all unique rows in a given matrix.def findUniqueRows(M): # Traverse through the matrix for i in range(ROW): flag = 0 # Check if there is similar column # is already printed, i.e if i and # jth column match. for j in range(i): flag = 1 for k in range(COL): if (M[i][k] != M[j][k]): flag = 0 if (flag == 1): break # If no row is similar if (flag == 0): # Print the row for j in range(COL): print(M[i][j], end = \" \") print() # Driver Codeif __name__ == '__main__': M = [ [ 0, 1, 0, 0, 1 ], [ 1, 0, 1, 1, 0 ], [ 0, 1, 0, 0, 1 ], [ 1, 0, 1, 0, 0 ] ] findUniqueRows(M) # This code is contributed by mohit kumar 29", "e": 30965, "s": 29944, "text": null }, { "code": "// Given a binary matrix of M X N // of integers, you need to return// only unique rows of binary array using System; class GFG{ static int ROW = 4;static int COL = 5; // Function that prints all // unique rows in a given matrix.static void findUniqueRows(int[,] M){ // Traverse through the matrix for(int i = 0; i < ROW; i++) { int flag = 0; // Check if there is similar column // is already printed, i.e if i and // jth column match. for(int j = 0; j < i; j++) { flag = 1; for(int k = 0; k < COL; k++) if (M[i, k] != M[j, k]) flag = 0; if (flag == 1) break; } // If no row is similar if (flag == 0) { // Print the row for(int j = 0; j < COL; j++) Console.Write(M[i, j] + \" \"); Console.WriteLine(); } }} // Driver codestatic void Main(){ int[,] M = { { 0, 1, 0, 0, 1 }, { 1, 0, 1, 1, 0 }, { 0, 1, 0, 0, 1 }, { 1, 0, 1, 0, 0 } }; findUniqueRows(M);}} // This code is contributed by divyeshrabadiya07", "e": 32202, "s": 30965, "text": null }, { "code": "<script>// Given a binary matrix of M X N// of integers, you need to return// only unique rows of binary array let ROW = 4; let COL = 5; // Function that prints all// unique rows in a given matrix. function findUniqueRows(M) { // Traverse through the matrix for(let i = 0; i < ROW; i++) { let flag = 0; // Check if there is similar column // is already printed, i.e if i and // jth column match. for(let j = 0; j < i; j++) { flag = 1; for(let k = 0; k < COL; k++) if (M[i][k] != M[j][k]) flag = 0; if (flag == 1) break; } // If no row is similar if (flag == 0) { // Print the row for(let j = 0; j < COL; j++) document.write(M[i][j] + \" \"); document.write(\"<br>\"); } } } // Driver Code let M = [ [ 0, 1, 0, 0, 1 ], [ 1, 0, 1, 1, 0 ], [ 0, 1, 0, 0, 1 ], [ 1, 0, 1, 0, 0 ] ] findUniqueRows(M) // This code is contributed by unknown2108</script>", "e": 33385, "s": 32202, "text": null }, { "code": null, "e": 33394, "s": 33385, "text": "Output: " }, { "code": null, "e": 33426, "s": 33394, "text": "0 1 0 0 1 \n1 0 1 1 0 \n1 0 1 0 0" }, { "code": null, "e": 33448, "s": 33426, "text": "Complexity Analysis: " }, { "code": null, "e": 33585, "s": 33448, "text": "Time complexity: O( ROW^2 x COL ). So for every row check if there is any other similar row. So the time complexity is O( ROW^2 x COL )." }, { "code": null, "e": 33639, "s": 33585, "text": "Auxiliary Space: O(1). As no extra space is required." }, { "code": null, "e": 33818, "s": 33639, "text": "Method 2: This method uses Binary Search Tree to solve the above operation. The Binary Search Tree is a node-based binary tree data structure which has the following properties: " }, { "code": null, "e": 33903, "s": 33818, "text": "The left subtree of a node contains only nodes with keys lesser than the node’s key." }, { "code": null, "e": 33990, "s": 33903, "text": "The right subtree of a node contains only nodes with keys greater than the node’s key." }, { "code": null, "e": 34057, "s": 33990, "text": "The left and right subtree each must also be a binary search tree." }, { "code": null, "e": 34091, "s": 34057, "text": "There must be no duplicate nodes." }, { "code": null, "e": 34319, "s": 34091, "text": "The above properties of Binary Search Tree provide ordering among keys so that the operations like search, minimum and maximum can be done fast. If there is no order, then we may have to compare every key to search a given key." }, { "code": null, "e": 34652, "s": 34319, "text": "Approach: The process must begin from finding the decimal equivalent of each row and inserting them into a BST. As we know, each node of the BST will contain two fields, one field for the decimal value, other for row number. One must not insert a node if it is duplicated. Finally, traverse the BST and print the corresponding rows." }, { "code": null, "e": 34664, "s": 34652, "text": "Algorithm: " }, { "code": null, "e": 34975, "s": 34664, "text": "Create a BST in which no duplicate elements can be stored. Create a function to convert a row into decimal and to convert the decimal value into binary array.Traverse through the matrix and insert the row into the BST.Traverse the BST (inorder traversal) and convert the decimal into binary array and print it." }, { "code": null, "e": 35134, "s": 34975, "text": "Create a BST in which no duplicate elements can be stored. Create a function to convert a row into decimal and to convert the decimal value into binary array." }, { "code": null, "e": 35195, "s": 35134, "text": "Traverse through the matrix and insert the row into the BST." }, { "code": null, "e": 35288, "s": 35195, "text": "Traverse the BST (inorder traversal) and convert the decimal into binary array and print it." }, { "code": null, "e": 35305, "s": 35288, "text": "Implementation: " }, { "code": null, "e": 35311, "s": 35305, "text": "C++14" }, { "code": null, "e": 35316, "s": 35311, "text": "Java" }, { "code": null, "e": 35319, "s": 35316, "text": "C#" }, { "code": null, "e": 35327, "s": 35319, "text": "Python3" }, { "code": null, "e": 35338, "s": 35327, "text": "Javascript" }, { "code": "// Given a binary matrix of M X N of integers,// you need to return only unique rows of binary array#include <bits/stdc++.h>using namespace std;#define ROW 4#define COL 5 class BST{ int data; BST *left, *right; public: // Default constructor. BST(); // Parameterized constructor. BST(int); // Insert function. BST* Insert(BST *, int); // Inorder traversal. void Inorder(BST *);}; //convert array to decimalint convert(int arr[]){ int sum=0; for(int i=0; i<COL; i++) { sum+=pow(2,i)*arr[i]; } return sum;} //print the column represented as integersvoid print(int p){ for(int i=0; i<COL; i++) { cout<<p%2<<\" \"; p/=2; } cout<<endl;} // Default Constructor definition.BST :: BST() : data(0), left(NULL), right(NULL){} // Parameterized Constructor definition.BST :: BST(int value){ data = value; left = right = NULL;} // Insert function definition.BST* BST :: Insert(BST *root, int value){ if(!root) { // Insert the first node, if root is NULL. return new BST(value); } //if the value is present if(value == root->data) return root; // Insert data. if(value > root->data) { // Insert right node data, if the 'value' // to be inserted is greater than 'root' node data. // Process right nodes. root->right = Insert(root->right, value); } else { // Insert left node data, if the 'value' // to be inserted is greater than 'root' node data. // Process left nodes. root->left = Insert(root->left, value); } // Return 'root' node, after insertion. return root;} // Inorder traversal function.// This gives data in sorted order.void BST :: Inorder(BST *root){ if(!root) { return; } Inorder(root->left); print( root->data ); Inorder(root->right);} // The main function that prints// all unique rows in a given matrix.void findUniqueRows(int M[ROW][COL]){ BST b, *root = NULL; //Traverse through the matrix for(int i=0; i<ROW; i++) { //insert the row into BST root=b.Insert(root,convert(M[i])); } //print b.Inorder(root); } // Driver Codeint main(){ int M[ROW][COL] = {{0, 1, 0, 0, 1}, {1, 0, 1, 1, 0}, {0, 1, 0, 0, 1}, {1, 0, 1, 0, 0}}; findUniqueRows(M); return 0;}", "e": 37812, "s": 35338, "text": null }, { "code": "// Given a binary matrix of M X N of integers,// you need to return only unique rows of binary arrayimport java.util.*; class GFG{ static class BST { int data; BST left,right; BST(int v){ this.data = v; this.left = this.right = null; } } final static int ROW = 4; final static int COL = 5; // convert array to decimal static int convert(int arr[]) { int sum = 0; for(int i = 0; i < COL; i++) { sum += Math.pow(2,i)*arr[i]; } return sum; } // print the column represented as integers static void print(int p) { for(int i = 0; i < COL; i++) { System.out.print(p%2+\" \"); p /= 2; } System.out.println(); } // Insert function definition. static BST Insert(BST root, int value) { if(root == null) { // Insert the first node, if root is null. return new BST(value); } //if the value is present if(value == root.data) return root; // Insert data. if(value > root.data) { // Insert right node data, if the 'value' // to be inserted is greater than 'root' node data. // Process right nodes. root.right = Insert(root.right, value); } else { // Insert left node data, if the 'value' // to be inserted is greater than 'root' node data. // Process left nodes. root.left = Insert(root.left, value); } // Return 'root' node, after insertion. return root; } // Inorder traversal function. // This gives data in sorted order. static void Inorder(BST root) { if(root == null) { return; } Inorder(root.left); print( root.data ); Inorder(root.right); } // The main function that prints // all unique rows in a given matrix. static void findUniqueRows(int M[][]) { BST b, root = null; // Traverse through the matrix for(int i = 0; i < ROW; i++) { // insert the row into BST root=Insert(root, convert(M[i])); } //print Inorder(root); } // Driver Code public static void main(String[] args) { int M[][] = {{0, 1, 0, 0, 1}, {1, 0, 1, 1, 0}, {0, 1, 0, 0, 1}, {1, 0, 1, 0, 0}}; findUniqueRows(M); }} // This code is contributed by Rajput-Ji", "e": 40046, "s": 37812, "text": null }, { "code": "// Given a binary matrix of M X N of integers,// you need to return only unique rows of binary arrayusing System;using System.Collections.Generic; public class GFG{ public class BST { public int data; public BST left,right; public BST(int v){ this.data = v; this.left = this.right = null; } } readonly static int ROW = 4; readonly static int COL = 5; // convert array to decimal static int convert(int []arr) { int sum = 0; for(int i = 0; i < COL; i++) { sum += (int)Math.Pow(2,i)*arr[i]; } return sum; } // print the column represented as integers static void print(int p) { for(int i = 0; i < COL; i++) { Console.Write(p%2+\" \"); p /= 2; } Console.WriteLine(); } // Insert function definition. static BST Insert(BST root, int value) { if(root == null) { // Insert the first node, if root is null. return new BST(value); } // if the value is present if(value == root.data) return root; // Insert data. if(value > root.data) { // Insert right node data, if the 'value' // to be inserted is greater than 'root' node data. // Process right nodes. root.right = Insert(root.right, value); } else { // Insert left node data, if the 'value' // to be inserted is greater than 'root' node data. // Process left nodes. root.left = Insert(root.left, value); } // Return 'root' node, after insertion. return root; } // Inorder traversal function. // This gives data in sorted order. static void Inorder(BST root) { if(root == null) { return; } Inorder(root.left); print( root.data ); Inorder(root.right); } public static int[] GetRow(int[,] matrix, int row) { var rowLength = matrix.GetLength(1); var rowVector = new int[rowLength]; for (var i = 0; i < rowLength; i++) rowVector[i] = matrix[row, i]; return rowVector; } // The main function that prints // all unique rows in a given matrix. static void findUniqueRows(int [,]M) { BST b, root = null; // Traverse through the matrix for(int i = 0; i < ROW; i++) { // insert the row into BST int[] row = GetRow(M,i); root=Insert(root, convert(row)); } //print Inorder(root); } // Driver Code public static void Main(String[] args) { int [,]M = {{0, 1, 0, 0, 1}, {1, 0, 1, 1, 0}, {0, 1, 0, 0, 1}, {1, 0, 1, 0, 0}}; findUniqueRows(M); }} // This code contributed by Rajput-Ji", "e": 42605, "s": 40046, "text": null }, { "code": "# Given a binary matrix of M X N of integers,# you need to return only unique rows of binary arrayROW = 4COL = 5 # print the column represented as integersdef Print(p): for i in range(COL): print(p % 2 ,end = \" \") p = int(p//2) print(\"\") class BST: def __init__(self,data): self.data = data self.left = None self.right = None # Insert function definition. def Insert(self,root, value): if(not root): # Insert the first node, if root is NULL. return BST(value) #if the value is present if(value == root.data): return root # Insert data. if(value > root.data): # Insert right node data, if the 'value' # to be inserted is greater than 'root' node data. # Process right nodes. root.right = self.Insert(root.right, value) else: # Insert left node data, if the 'value' # to be inserted is greater than 'root' node data. # Process left nodes. root.left = self.Insert(root.left, value) # Return 'root' node, after insertion. return root # Inorder traversal function. # This gives data in sorted order. def Inorder(self,root): if(not root): return self.Inorder(root.left); Print( root.data ); self.Inorder(root.right) # convert array to decimaldef convert(arr): sum=0 for i in range(COL): sum+=pow(2,i)*arr[i] return sum # The main function that prints# all unique rows in a given matrix.def findUniqueRows(M): b,root =BST(0),None #Traverse through the matrix for i in range(ROW): #insert the row into BST root = b.Insert(root,convert(M[i])) #print b.Inorder(root) # Driver CodeM = [[0, 1, 0, 0, 1], [1, 0, 1, 1, 0], [0, 1, 0, 0, 1], [1, 0, 1, 0, 0]] findUniqueRows(M) # This code is contributed by shinjanpatra", "e": 44616, "s": 42605, "text": null }, { "code": "<script> // Given a binary matrix of M X N of integers,// you need to return only unique rows of binary arrayvar ROW = 4var COL = 5 class BST{ constructor(data) { this.data = data; this.left = null; this.right = null; } // Insert function definition. Insert(root, value) { if(!root) { // Insert the first node, if root is NULL. return new BST(value); } //if the value is present if(value == root.data) return root; // Insert data. if(value > root.data) { // Insert right node data, if the 'value' // to be inserted is greater than 'root' node data. // Process right nodes. root.right = this.Insert(root.right, value); } else { // Insert left node data, if the 'value' // to be inserted is greater than 'root' node data. // Process left nodes. root.left = this.Insert(root.left, value); } // Return 'root' node, after insertion. return root; } // Inorder traversal function. // This gives data in sorted order. Inorder(root) { if(!root) { return; } this.Inorder(root.left); print( root.data ); this.Inorder(root.right); }}; // convert array to decimalfunction convert(arr){ var sum=0; for(var i=0; i<COL; i++) { sum+=Math.pow(2,i)*arr[i]; } return sum;} // print the column represented as integersfunction print(p){ for(var i=0; i<COL; i++) { document.write(p%2 + \" \"); p=parseInt(p/2); } document.write(\"<br>\");} // The main function that prints// all unique rows in a given matrix.function findUniqueRows(M){ var b =new BST(0),root = null; //Traverse through the matrix for(var i=0; i<ROW; i++) { //insert the row into BST root=b.Insert(root,convert(M[i])); } //print b.Inorder(root); } // Driver Codevar M = [[0, 1, 0, 0, 1], [1, 0, 1, 1, 0], [0, 1, 0, 0, 1], [1, 0, 1, 0, 0]];findUniqueRows(M); // This code is contributed by rutvik_56.</script>", "e": 46909, "s": 44616, "text": null }, { "code": null, "e": 46918, "s": 46909, "text": "Output: " }, { "code": null, "e": 46950, "s": 46918, "text": "1 0 1 0 0 \n1 0 1 1 0 \n0 1 0 0 1" }, { "code": null, "e": 46972, "s": 46950, "text": "Complexity Analysis: " }, { "code": null, "e": 47216, "s": 46972, "text": "Time complexity: O( ROW x COL + ROW x log( ROW ) ). To traverse the matrix time complexity is O( ROW x COL) and to insert them into BST time complexity is O(log ROW) for each row. So overall time complexity is O( ROW x COL + ROW x log( ROW ) )" }, { "code": null, "e": 47284, "s": 47216, "text": "Auxiliary Space: O( ROW ). To store the BST O(ROW) space is needed." }, { "code": null, "e": 47864, "s": 47284, "text": "Method 3: This method uses Trie data structure to solve the above problem. Trie is an efficient information retrieval data structure. Using Trie, search complexities can be brought to an optimal limit (key length). If we store keys in the binary search tree, a well-balanced BST will need time proportional to M * log N, where M is maximum string length and N is the number of keys in the tree. Using Trie, we can search the key in O(M) time. However, the penalty is on Trie storage requirements.Note: This method will lead to Integer Overflow if the number of columns is large. " }, { "code": null, "e": 48163, "s": 47864, "text": "Approach: Since the matrix is boolean, a variant of Trie data structure can be used where each node will be having two children one for 0 and other for 1. Insert each row in the Trie. If the row is already there, don’t print the row. If the row is not there in Trie, insert it in Trie and print it." }, { "code": null, "e": 48175, "s": 48163, "text": "Algorithm: " }, { "code": null, "e": 48382, "s": 48175, "text": "Create a Trie where rows can be stored.Traverse through the matrix and insert the row into the Trie.Trie cannot store duplicate entries so the duplicates will be removedTraverse the Trie and print the rows." }, { "code": null, "e": 48422, "s": 48382, "text": "Create a Trie where rows can be stored." }, { "code": null, "e": 48484, "s": 48422, "text": "Traverse through the matrix and insert the row into the Trie." }, { "code": null, "e": 48554, "s": 48484, "text": "Trie cannot store duplicate entries so the duplicates will be removed" }, { "code": null, "e": 48592, "s": 48554, "text": "Traverse the Trie and print the rows." }, { "code": null, "e": 48609, "s": 48592, "text": "Implementation: " }, { "code": null, "e": 48613, "s": 48609, "text": "C++" }, { "code": null, "e": 48615, "s": 48613, "text": "C" }, { "code": "// Given a binary matrix of M X N of integers,// you need to return only unique rows of binary array#include <bits/stdc++.h>using namespace std;#define ROW 4#define COL 5 // A Trie nodeclass Node{ public: bool isEndOfCol; Node *child[2]; // Only two children needed for 0 and 1} ; // A utility function to allocate memory// for a new Trie nodeNode* newNode(){ Node* temp = new Node(); temp->isEndOfCol = 0; temp->child[0] = temp->child[1] = NULL; return temp;} // Inserts a new matrix row to Trie.// If row is already present,// then returns 0, otherwise insets the row and// return 1bool insert(Node** root, int (*M)[COL], int row, int col ){ // base case if (*root == NULL) *root = newNode(); // Recur if there are more entries in this row if (col < COL) return insert (&((*root)->child[M[row][col]]), M, row, col + 1); else // If all entries of this row are processed { // unique row found, return 1 if (!((*root)->isEndOfCol)) return (*root)->isEndOfCol = 1; // duplicate row found, return 0 return 0; }} // A utility function to print a rowvoid printRow(int(*M)[COL], int row){ int i; for(i = 0; i < COL; ++i) cout << M[row][i] << \" \"; cout << endl;} // The main function that prints// all unique rows in a given matrix.void findUniqueRows(int (*M)[COL]){ Node* root = NULL; // create an empty Trie int i; // Iterate through all rows for (i = 0; i < ROW; ++i) // insert row to TRIE if (insert(&root, M, i, 0)) // unique row found, print it printRow(M, i);} // Driver Codeint main(){ int M[ROW][COL] = {{0, 1, 0, 0, 1}, {1, 0, 1, 1, 0}, {0, 1, 0, 0, 1}, {1, 0, 1, 0, 0}}; findUniqueRows(M); return 0;} // This code is contributed by rathbhupendra", "e": 50575, "s": 48615, "text": null }, { "code": "//Given a binary matrix of M X N of integers, you need to return only unique rows of binary array#include <stdio.h>#include <stdlib.h>#include <stdbool.h> #define ROW 4#define COL 5 // A Trie nodetypedef struct Node{ bool isEndOfCol; struct Node *child[2]; // Only two children needed for 0 and 1} Node; // A utility function to allocate memory for a new Trie nodeNode* newNode(){ Node* temp = (Node *)malloc( sizeof( Node ) ); temp->isEndOfCol = 0; temp->child[0] = temp->child[1] = NULL; return temp;} // Inserts a new matrix row to Trie. If row is already// present, then returns 0, otherwise insets the row and// return 1bool insert( Node** root, int (*M)[COL], int row, int col ){ // base case if ( *root == NULL ) *root = newNode(); // Recur if there are more entries in this row if ( col < COL ) return insert ( &( (*root)->child[ M[row][col] ] ), M, row, col+1 ); else // If all entries of this row are processed { // unique row found, return 1 if ( !( (*root)->isEndOfCol ) ) return (*root)->isEndOfCol = 1; // duplicate row found, return 0 return 0; }} // A utility function to print a rowvoid printRow( int (*M)[COL], int row ){ int i; for( i = 0; i < COL; ++i ) printf( \"%d \", M[row][i] ); printf(\"\\n\");} // The main function that prints all unique rows in a// given matrix.void findUniqueRows( int (*M)[COL] ){ Node* root = NULL; // create an empty Trie int i; // Iterate through all rows for ( i = 0; i < ROW; ++i ) // insert row to TRIE if ( insert(&root, M, i, 0) ) // unique row found, print it printRow( M, i );} // Driver program to test above functionsint main(){ int M[ROW][COL] = {{0, 1, 0, 0, 1}, {1, 0, 1, 1, 0}, {0, 1, 0, 0, 1}, {1, 0, 1, 0, 0} }; findUniqueRows( M ); return 0;}", "e": 52477, "s": 50575, "text": null }, { "code": null, "e": 52486, "s": 52477, "text": "Output: " }, { "code": null, "e": 52518, "s": 52486, "text": "0 1 0 0 1 \n1 0 1 1 0 \n1 0 1 0 0" }, { "code": null, "e": 52540, "s": 52518, "text": "Complexity Analysis: " }, { "code": null, "e": 52789, "s": 52540, "text": "Time complexity: O( ROW x COL ). To traverse the matrix and insert in the trie the time complexity is O( ROW x COL). This method has better time complexity. Also, the relative order of rows is maintained while printing but it takes a toll on space." }, { "code": null, "e": 52881, "s": 52789, "text": "Auxiliary Space: O( ROW x COL ). To store the Trie O(ROW x COL) space complexity is needed." }, { "code": null, "e": 53434, "s": 52881, "text": "Method 4: This method uses HashSet data structure to solve the above problem. The HashSet class implements the Set interface, backed by a hash table which is actually a HashMap instance. No guarantee is made as to the iteration order of the set which means that the class does not guarantee the constant order of elements over time. This class permits the null element. The class offers constant time performance for the basic operations like add, remove, contains and size assuming the hash function disperses the elements properly among the buckets. " }, { "code": null, "e": 53667, "s": 53434, "text": "Approach: In this method convert the whole row into a single String and then if check it is already present in the HashSet or not. If the row is present then we will leave it otherwise we will print unique row and add it to HashSet." }, { "code": null, "e": 53679, "s": 53667, "text": "Algorithm: " }, { "code": null, "e": 53920, "s": 53679, "text": "Create a HashSet where rows can be stored as a String.Traverse through the matrix and insert the row as String into the HashSet.HashSet cannot store duplicate entries so the duplicates will be removedTraverse the HashSet and print the rows." }, { "code": null, "e": 53975, "s": 53920, "text": "Create a HashSet where rows can be stored as a String." }, { "code": null, "e": 54050, "s": 53975, "text": "Traverse through the matrix and insert the row as String into the HashSet." }, { "code": null, "e": 54123, "s": 54050, "text": "HashSet cannot store duplicate entries so the duplicates will be removed" }, { "code": null, "e": 54164, "s": 54123, "text": "Traverse the HashSet and print the rows." }, { "code": null, "e": 54181, "s": 54164, "text": "Implementation: " }, { "code": null, "e": 54185, "s": 54181, "text": "C++" }, { "code": null, "e": 54190, "s": 54185, "text": "Java" }, { "code": null, "e": 54198, "s": 54190, "text": "Python3" }, { "code": null, "e": 54201, "s": 54198, "text": "C#" }, { "code": null, "e": 54212, "s": 54201, "text": "Javascript" }, { "code": "// C++ code to print unique row in a// given binary matrix#include<bits/stdc++.h>using namespace std; void printArray(int arr[][5], int row, int col){ unordered_set<string> uset; for(int i = 0; i < row; i++) { string s = \"\"; for(int j = 0; j < col; j++) s += to_string(arr[i][j]); if(uset.count(s) == 0) { uset.insert(s); cout << s << endl; } }} // Driver codeint main(){ int arr[][5] = {{0, 1, 0, 0, 1}, {1, 0, 1, 1, 0}, {0, 1, 0, 0, 1}, {1, 1, 1, 0, 0}}; printArray(arr, 4, 5);} // This code is contributed by// rathbhupendra", "e": 54953, "s": 54212, "text": null }, { "code": "// Java code to print unique row in a// given binary matriximport java.util.HashSet; public class GFG { public static void printArray(int arr[][], int row,int col) { HashSet<String> set = new HashSet<String>(); for(int i = 0; i < row; i++) { String s = \"\"; for(int j = 0; j < col; j++) s += String.valueOf(arr[i][j]); if(!set.contains(s)) { set.add(s); System.out.println(s); } } } // Driver code public static void main(String[] args) { int arr[][] = { {0, 1, 0, 0, 1}, {1, 0, 1, 1, 0}, {0, 1, 0, 0, 1}, {1, 1, 1, 0, 0} }; printArray(arr, 4, 5); }}", "e": 55836, "s": 54953, "text": null }, { "code": "# Python3 code to print unique row in a# given binary matrix def printArray(matrix): rowCount = len(matrix) if rowCount == 0: return columnCount = len(matrix[0]) if columnCount == 0: return row_output_format = \" \".join([\"%s\"] * columnCount) printed = {} for row in matrix: routput = row_output_format % tuple(row) if routput not in printed: printed[routput] = True print(routput) # Driver Codemat = [[0, 1, 0, 0, 1], [1, 0, 1, 1, 0], [0, 1, 0, 0, 1], [1, 1, 1, 0, 0]] printArray(mat) # This code is contributed by myronwalker", "e": 56456, "s": 55836, "text": null }, { "code": "using System;using System.Collections.Generic; // c# code to print unique row in a // given binary matrix public class GFG{ public static void printArray(int[][] arr, int row, int col) { HashSet<string> set = new HashSet<string>(); for (int i = 0; i < row; i++) { string s = \"\"; for (int j = 0; j < col; j++) { s += arr[i][j].ToString(); } if (!set.Contains(s)) { set.Add(s); Console.WriteLine(s); } } } // Driver code public static void Main(string[] args) { int[][] arr = new int[][] { new int[] {0, 1, 0, 0, 1}, new int[] {1, 0, 1, 1, 0}, new int[] {0, 1, 0, 0, 1}, new int[] {1, 1, 1, 0, 0} }; printArray(arr, 4, 5); }} // This code is contributed by Shrikant13", "e": 57374, "s": 56456, "text": null }, { "code": "<script>// Javascript code to print unique row in a// given binary matrix function printArray(arr,row,col){ let set = new Set(); for(let i = 0; i < row; i++) { let s = \"\"; for(let j = 0; j < col; j++) s += (arr[i][j]).toString(); if(!set.has(s)) { set.add(s); document.write(s+\"<br>\"); } }} // Driver codelet arr = [[0, 1, 0, 0, 1], [1, 0, 1, 1, 0], [0, 1, 0, 0, 1], [1, 1, 1, 0, 0]];printArray(arr, 4, 5); // This code is contributed by avanitrachhadiya2155</script>", "e": 58066, "s": 57374, "text": null }, { "code": null, "e": 58075, "s": 58066, "text": "Output: " }, { "code": null, "e": 58093, "s": 58075, "text": "01001\n10110\n11100" }, { "code": null, "e": 58115, "s": 58093, "text": "Complexity Analysis: " }, { "code": null, "e": 58234, "s": 58115, "text": "Time complexity: O( ROW x COL ). To traverse the matrix and insert in the HashSet the time complexity is O( ROW x COL)" }, { "code": null, "e": 58323, "s": 58234, "text": "Auxiliary Space: O( ROW ). To store the HashSet O(ROW x COL) space complexity is needed." }, { "code": null, "e": 58376, "s": 58323, "text": "Thanks, Anshuman Kaushik for suggesting this method." }, { "code": null, "e": 59219, "s": 58376, "text": "YouTubeGeeksforGeeks507K subscribersPrint unique rows in a given boolean matrix | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 14:56•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=GixyVinjtFk\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 59345, "s": 59219, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 59368, "s": 59351, "text": "Anshuman Kaushik" }, { "code": null, "e": 59380, "s": 59368, "text": "shrikanth13" }, { "code": null, "e": 59394, "s": 59380, "text": "rathbhupendra" }, { "code": null, "e": 59406, "s": 59394, "text": "myronwalker" }, { "code": null, "e": 59417, "s": 59406, "text": "andrew1234" }, { "code": null, "e": 59432, "s": 59417, "text": "mohit kumar 29" }, { "code": null, "e": 59445, "s": 59432, "text": "sujitmeshram" }, { "code": null, "e": 59463, "s": 59445, "text": "divyeshrabadiya07" }, { "code": null, "e": 59475, "s": 59463, "text": "unknown2108" }, { "code": null, "e": 59496, "s": 59475, "text": "avanitrachhadiya2155" }, { "code": null, "e": 59506, "s": 59496, "text": "rutvik_56" }, { "code": null, "e": 59516, "s": 59506, "text": "Rajput-Ji" }, { "code": null, "e": 59529, "s": 59516, "text": "shinjanpatra" }, { "code": null, "e": 59536, "s": 59529, "text": "Amazon" }, { "code": null, "e": 59541, "s": 59536, "text": "Trie" }, { "code": null, "e": 59546, "s": 59541, "text": "Zoho" }, { "code": null, "e": 59570, "s": 59546, "text": "Advanced Data Structure" }, { "code": null, "e": 59577, "s": 59570, "text": "Matrix" }, { "code": null, "e": 59582, "s": 59577, "text": "Zoho" }, { "code": null, "e": 59589, "s": 59582, "text": "Amazon" }, { "code": null, "e": 59596, "s": 59589, "text": "Matrix" }, { "code": null, "e": 59601, "s": 59596, "text": "Trie" }, { "code": null, "e": 59699, "s": 59601, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 59739, "s": 59699, "text": "Decision Tree Introduction with example" }, { "code": null, "e": 59768, "s": 59739, "text": "Ordered Set and GNU C++ PBDS" }, { "code": null, "e": 59800, "s": 59768, "text": "Red-Black Tree | Set 2 (Insert)" }, { "code": null, "e": 59829, "s": 59800, "text": "Disjoint Set Data Structures" }, { "code": null, "e": 59865, "s": 59829, "text": "Binary Indexed Tree or Fenwick Tree" }, { "code": null, "e": 59900, "s": 59865, "text": "Matrix Chain Multiplication | DP-8" }, { "code": null, "e": 59944, "s": 59900, "text": "Program to find largest element in an array" }, { "code": null, "e": 59975, "s": 59944, "text": "Rat in a Maze | Backtracking-2" }, { "code": null, "e": 59999, "s": 59975, "text": "Sudoku | Backtracking-7" } ]
BeautifulSoup - Find all children of an element - GeeksforGeeks
26 Mar, 2021 You might have seen there are various websites that are complex as well as lengthy, from which searching anything becomes difficult. To ease our work of searching, modifying, and iteration, Python gives us some inbuilt libraries, such as Requests, Xml, Beautiful Soup, Selenium, Scrapy, etc. Among all these available libraries, Beautiful Soup is the one that does web scrapping comparatively faster than those other available in Python. Sometimes, there occurs situations, when we need to find all the children of an element with the help of Beautiful Soup. If you don’t know, how to find these. Don’t worry! In this article, we will be discussing the procedure of finding the children of an element. Syntax: unordered_list=soup.find(“#Widget Name”, {“id”:”#Id name of element of which you want to find children “}) children = unordered_list.findChildren() Below is the HTML file for considering: HTML <!DOCTYPE html><html> <head> My First Heading </head> <body> <p id="para"> Vinayak Rai </p> <ul id="list">Fruits <li>Apple</li> <li>Banana</li> <li>Mango</li> </ul> </body></html> Step 1: First, import the libraries Beautiful Soup and os. Python3 from bs4 import BeautifulSoup as bsimport os Step 2: Now, remove the last segment of the path by giving the same name to abspath as given to your Python file. Python3 base=os.path.dirname(os.path.abspath(#Name of your Python file)) Step 3: Then, open the HTML file you wish to open. Python3 html=open(os.path.join(base, '#Name of HTML file')) Step 4: Parsing HTML in Beautiful Soup. Python3 soup=bs(html, 'html.parser') Step 5: Further, give the location of an element for which you want to find children Python3 unordered_list=soup.find("#Widget Name", {"id":"#Id name of element of which you want to find children "}) Step 6: Next, find all the children of an element. Python3 children = unordered_list.findChildren() Step 7: Finally, print all the children of an element that you have found in the last step. Python3 for child in children: print (child) Below is the full implementation: Python # Python program to find all the children# of an element using Beautiful Soup # Import the libraries BeautifulSoup and osfrom bs4 import BeautifulSoup as bsimport os # Remove the last segment of the path # Give same name in abspath as given to Python filebase = os.path.dirname(os.path.abspath('run.py')) # Open the HTML in which you want to make changeshtml = open(os.path.join(base, 'gfg.html')) # Parse HTML file in Beautiful Soupsoup = bs(html, 'html.parser') # Give location where text is stored which you wish to alterunordered_list = soup.find("ul", {"id": "list"}) # Find children of an elementchildren = unordered_list.findChildren() # Print all children of an elementfor child in children: print(child) Output: Picked Python BeautifulSoup Python bs4-Exercises Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 26324, "s": 26296, "text": "\n26 Mar, 2021" }, { "code": null, "e": 27026, "s": 26324, "text": "You might have seen there are various websites that are complex as well as lengthy, from which searching anything becomes difficult. To ease our work of searching, modifying, and iteration, Python gives us some inbuilt libraries, such as Requests, Xml, Beautiful Soup, Selenium, Scrapy, etc. Among all these available libraries, Beautiful Soup is the one that does web scrapping comparatively faster than those other available in Python. Sometimes, there occurs situations, when we need to find all the children of an element with the help of Beautiful Soup. If you don’t know, how to find these. Don’t worry! In this article, we will be discussing the procedure of finding the children of an element." }, { "code": null, "e": 27034, "s": 27026, "text": "Syntax:" }, { "code": null, "e": 27141, "s": 27034, "text": "unordered_list=soup.find(“#Widget Name”, {“id”:”#Id name of element of which you want to find children “})" }, { "code": null, "e": 27182, "s": 27141, "text": "children = unordered_list.findChildren()" }, { "code": null, "e": 27222, "s": 27182, "text": "Below is the HTML file for considering:" }, { "code": null, "e": 27227, "s": 27222, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> My First Heading </head> <body> <p id=\"para\"> Vinayak Rai </p> <ul id=\"list\">Fruits <li>Apple</li> <li>Banana</li> <li>Mango</li> </ul> </body></html>", "e": 27417, "s": 27227, "text": null }, { "code": null, "e": 27476, "s": 27417, "text": "Step 1: First, import the libraries Beautiful Soup and os." }, { "code": null, "e": 27484, "s": 27476, "text": "Python3" }, { "code": "from bs4 import BeautifulSoup as bsimport os", "e": 27529, "s": 27484, "text": null }, { "code": null, "e": 27643, "s": 27529, "text": "Step 2: Now, remove the last segment of the path by giving the same name to abspath as given to your Python file." }, { "code": null, "e": 27651, "s": 27643, "text": "Python3" }, { "code": "base=os.path.dirname(os.path.abspath(#Name of your Python file))", "e": 27716, "s": 27651, "text": null }, { "code": null, "e": 27767, "s": 27716, "text": "Step 3: Then, open the HTML file you wish to open." }, { "code": null, "e": 27775, "s": 27767, "text": "Python3" }, { "code": "html=open(os.path.join(base, '#Name of HTML file'))", "e": 27827, "s": 27775, "text": null }, { "code": null, "e": 27867, "s": 27827, "text": "Step 4: Parsing HTML in Beautiful Soup." }, { "code": null, "e": 27875, "s": 27867, "text": "Python3" }, { "code": "soup=bs(html, 'html.parser')", "e": 27904, "s": 27875, "text": null }, { "code": null, "e": 27989, "s": 27904, "text": "Step 5: Further, give the location of an element for which you want to find children" }, { "code": null, "e": 27997, "s": 27989, "text": "Python3" }, { "code": "unordered_list=soup.find(\"#Widget Name\", {\"id\":\"#Id name of element of which you want to find children \"})", "e": 28110, "s": 27997, "text": null }, { "code": null, "e": 28161, "s": 28110, "text": "Step 6: Next, find all the children of an element." }, { "code": null, "e": 28169, "s": 28161, "text": "Python3" }, { "code": "children = unordered_list.findChildren()", "e": 28210, "s": 28169, "text": null }, { "code": null, "e": 28302, "s": 28210, "text": "Step 7: Finally, print all the children of an element that you have found in the last step." }, { "code": null, "e": 28310, "s": 28302, "text": "Python3" }, { "code": "for child in children: print (child)", "e": 28350, "s": 28310, "text": null }, { "code": null, "e": 28384, "s": 28350, "text": "Below is the full implementation:" }, { "code": null, "e": 28391, "s": 28384, "text": "Python" }, { "code": "# Python program to find all the children# of an element using Beautiful Soup # Import the libraries BeautifulSoup and osfrom bs4 import BeautifulSoup as bsimport os # Remove the last segment of the path # Give same name in abspath as given to Python filebase = os.path.dirname(os.path.abspath('run.py')) # Open the HTML in which you want to make changeshtml = open(os.path.join(base, 'gfg.html')) # Parse HTML file in Beautiful Soupsoup = bs(html, 'html.parser') # Give location where text is stored which you wish to alterunordered_list = soup.find(\"ul\", {\"id\": \"list\"}) # Find children of an elementchildren = unordered_list.findChildren() # Print all children of an elementfor child in children: print(child)", "e": 29114, "s": 28391, "text": null }, { "code": null, "e": 29122, "s": 29114, "text": "Output:" }, { "code": null, "e": 29129, "s": 29122, "text": "Picked" }, { "code": null, "e": 29150, "s": 29129, "text": "Python BeautifulSoup" }, { "code": null, "e": 29171, "s": 29150, "text": "Python bs4-Exercises" }, { "code": null, "e": 29178, "s": 29171, "text": "Python" }, { "code": null, "e": 29276, "s": 29178, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29294, "s": 29276, "text": "Python Dictionary" }, { "code": null, "e": 29329, "s": 29294, "text": "Read a file line by line in Python" }, { "code": null, "e": 29361, "s": 29329, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29383, "s": 29361, "text": "Enumerate() in Python" }, { "code": null, "e": 29425, "s": 29383, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 29455, "s": 29425, "text": "Iterate over a list in Python" }, { "code": null, "e": 29481, "s": 29455, "text": "Python String | replace()" }, { "code": null, "e": 29510, "s": 29481, "text": "*args and **kwargs in Python" }, { "code": null, "e": 29554, "s": 29510, "text": "Reading and Writing to text files in Python" } ]
Inheritance in Scala - GeeksforGeeks
12 Jan, 2022 Inheritance is an important pillar of OOP(Object Oriented Programming). It is the mechanism in Scala by which one class is allowed to inherit the features(fields and methods) of another class. Important terminology: Super Class: The class whose features are inherited is known as superclass(or a base class or a parent class). Sub Class: The class that inherits the other class is known as subclass(or a derived class, extended class, or child class). The subclass can add its own fields and methods in addition to the superclass fields and methods. Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to create a new class and there is already a class that includes some of the code that we want, we can derive our new class from the existing class. By doing this, we are reusing the fields and methods of the existing class. The keyword used for inheritance is extends. Syntax: class child_class_name extends parent_class_name { // Methods and fields } Example: Scala // Scala program to illustrate the// implementation of inheritance // Base classclass Geeks1{ var Name: String = "Ankita"} // Derived class// Using extends keywordclass Geeks2 extends Geeks1{ var Article_no: Int = 130 // Method def details() { println("Author name: " +Name); println("Total numbers of articles: " +Article_no); }} object Main{ // Driver code def main(args: Array[String]) { // Creating object of derived class val ob = new Geeks2(); ob.details(); }} Output: Author name: Ankita Total numbers of articles: 130 Explanation: In the above example Geeks1 is the base class and Geeks2 is the derived class which is derived from Geeks1 using extends keyword. In the main method when we create the object of Geeks2 class, a copy of all the methods and fields of the base class acquires memory in this object. That is why by using the object of the derived class we can also access the members of the base class. Below are the different types of inheritance which are supported by Scala. Single Inheritance: In single inheritance, derived class inherits the features of one base class. In the image below, class A serves as a base class for the derived class B. Example: Scala // Scala program to illustrate the// Single inheritance // Base classclass Parent{ var Name: String = "Ankita"} // Derived class// Using extends keywordclass Child extends Parent{ var Age: Int = 22 // Method def details() { println("Name: " +Name); println("Age: " +Age); }} object Main{ // Driver code def main(args: Array[String]) { // Creating object of the derived class val ob = new Child(); ob.details(); }} Output: Name: Ankita Age: 22 Multilevel Inheritance: In Multilevel Inheritance, a derived class will be inheriting a base class and as well as the derived class also act as the base class to another class. In the below image, the class A serves as a base class for the derived class B, which in turn serves as a base class for the derived class C. Example: Scala // Scala program to illustrate the// Multilevel inheritance // Base classclass Parent{ var Name: String = "Soniya"} // Derived from parent class// Base class for Child2 classclass Child1 extends Parent{ var Age: Int = 32} // Derived from Child1 classclass Child2 extends Child1{ // Method def details(){ println("Name: " +Name); println("Age: " +Age); }} object Main{ // Drived Code def main(args: Array[String]) { // Creating object of the derived class val ob = new Child2(); ob.details(); }} Output: Name: Soniya Age: 32 Hierarchical Inheritance: In Hierarchical Inheritance, one class serves as a superclass (base class) for more than one subclass.In below image, class A serves as a base class for the derived class B, C, and D. Example: Scala // Scala program to illustrate the// Hierarchical inheritance // Base classclass Parent{ var Name1: String = "Siya" var Name2: String = "Soniya"} // Derived from the parent classclass Child1 extends Parent{ var Age: Int = 32 def details1() { println(" Name: " +Name1); println(" Age: " +Age); }} // Derived from Parent classclass Child2 extends Parent{ var Height: Int = 164 // Method def details2() { println(" Name: " +Name2); println(" Height: " +Height); }} object Main{ // Driver code def main(args: Array[String]) { // Creating objects of both derived classes val ob1 = new Child1(); val ob2 = new Child2(); ob1.details1(); ob2.details2(); }} Output: Name: Siya Age: 32 Name: Soniya Height: 164 Multiple Inheritance: In Multiple inheritance ,one class can have more than one superclass and inherit features from all parent classes. Scala does not support multiple inheritance with classes, but it can be achieved by traits. Example: Scala // Scala program to illustrate the// multiple inheritance using traits // Trait 1trait Geeks1{ def method1()} // Trait 2trait Geeks2{ def method2()} // Class that implement both Geeks1 and Geeks2 traitsclass GFG extends Geeks1 with Geeks2{ // method1 from Geeks1 def method1() { println("Trait 1"); } // method2 from Geeks2 def method2() { println("Trait 2"); }}object Main{ // Driver code def main(args: Array[String]) { // Creating object of GFG class var obj = new GFG(); obj.method1(); obj.method2(); }} Output: Trait 1 Trait 2 Hybrid Inheritance: It is a mix of two or more of the above types of inheritance. Since Scala doesn’t support multiple inheritance with classes, the hybrid inheritance is also not possible with classes. In Scala, we can achieve hybrid inheritance only through traits. rkkatta28 Scala Scala-Inheritance Scala-OOPS Scala Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. For Loop in Scala Scala | flatMap Method Scala | map() method Scala List filter() method with example Scala | reduce() Function String concatenation in Scala Type Casting in Scala Scala Tutorial – Learn Scala with Step By Step Guide Scala List contains() method with example Scala String substring() method with example
[ { "code": null, "e": 26087, "s": 26059, "text": "\n12 Jan, 2022" }, { "code": null, "e": 26305, "s": 26087, "text": "Inheritance is an important pillar of OOP(Object Oriented Programming). It is the mechanism in Scala by which one class is allowed to inherit the features(fields and methods) of another class. Important terminology: " }, { "code": null, "e": 26416, "s": 26305, "text": "Super Class: The class whose features are inherited is known as superclass(or a base class or a parent class)." }, { "code": null, "e": 26639, "s": 26416, "text": "Sub Class: The class that inherits the other class is known as subclass(or a derived class, extended class, or child class). The subclass can add its own fields and methods in addition to the superclass fields and methods." }, { "code": null, "e": 26947, "s": 26639, "text": "Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to create a new class and there is already a class that includes some of the code that we want, we can derive our new class from the existing class. By doing this, we are reusing the fields and methods of the existing class. " }, { "code": null, "e": 27002, "s": 26947, "text": "The keyword used for inheritance is extends. Syntax: " }, { "code": null, "e": 27077, "s": 27002, "text": "class child_class_name extends parent_class_name {\n// Methods and fields\n}" }, { "code": null, "e": 27088, "s": 27077, "text": "Example: " }, { "code": null, "e": 27094, "s": 27088, "text": "Scala" }, { "code": "// Scala program to illustrate the// implementation of inheritance // Base classclass Geeks1{ var Name: String = \"Ankita\"} // Derived class// Using extends keywordclass Geeks2 extends Geeks1{ var Article_no: Int = 130 // Method def details() { println(\"Author name: \" +Name); println(\"Total numbers of articles: \" +Article_no); }} object Main{ // Driver code def main(args: Array[String]) { // Creating object of derived class val ob = new Geeks2(); ob.details(); }}", "e": 27637, "s": 27094, "text": null }, { "code": null, "e": 27647, "s": 27637, "text": "Output: " }, { "code": null, "e": 27698, "s": 27647, "text": "Author name: Ankita\nTotal numbers of articles: 130" }, { "code": null, "e": 28095, "s": 27698, "text": "Explanation: In the above example Geeks1 is the base class and Geeks2 is the derived class which is derived from Geeks1 using extends keyword. In the main method when we create the object of Geeks2 class, a copy of all the methods and fields of the base class acquires memory in this object. That is why by using the object of the derived class we can also access the members of the base class. " }, { "code": null, "e": 28172, "s": 28095, "text": "Below are the different types of inheritance which are supported by Scala. " }, { "code": null, "e": 28348, "s": 28172, "text": "Single Inheritance: In single inheritance, derived class inherits the features of one base class. In the image below, class A serves as a base class for the derived class B. " }, { "code": null, "e": 28359, "s": 28348, "text": "Example: " }, { "code": null, "e": 28365, "s": 28359, "text": "Scala" }, { "code": "// Scala program to illustrate the// Single inheritance // Base classclass Parent{ var Name: String = \"Ankita\"} // Derived class// Using extends keywordclass Child extends Parent{ var Age: Int = 22 // Method def details() { println(\"Name: \" +Name); println(\"Age: \" +Age); }} object Main{ // Driver code def main(args: Array[String]) { // Creating object of the derived class val ob = new Child(); ob.details(); }}", "e": 28855, "s": 28365, "text": null }, { "code": null, "e": 28865, "s": 28855, "text": "Output: " }, { "code": null, "e": 28886, "s": 28865, "text": "Name: Ankita\nAge: 22" }, { "code": null, "e": 29207, "s": 28886, "text": "Multilevel Inheritance: In Multilevel Inheritance, a derived class will be inheriting a base class and as well as the derived class also act as the base class to another class. In the below image, the class A serves as a base class for the derived class B, which in turn serves as a base class for the derived class C. " }, { "code": null, "e": 29218, "s": 29207, "text": "Example: " }, { "code": null, "e": 29224, "s": 29218, "text": "Scala" }, { "code": "// Scala program to illustrate the// Multilevel inheritance // Base classclass Parent{ var Name: String = \"Soniya\"} // Derived from parent class// Base class for Child2 classclass Child1 extends Parent{ var Age: Int = 32} // Derived from Child1 classclass Child2 extends Child1{ // Method def details(){ println(\"Name: \" +Name); println(\"Age: \" +Age); }} object Main{ // Drived Code def main(args: Array[String]) { // Creating object of the derived class val ob = new Child2(); ob.details(); }}", "e": 29787, "s": 29224, "text": null }, { "code": null, "e": 29797, "s": 29787, "text": "Output: " }, { "code": null, "e": 29818, "s": 29797, "text": "Name: Soniya\nAge: 32" }, { "code": null, "e": 30030, "s": 29818, "text": "Hierarchical Inheritance: In Hierarchical Inheritance, one class serves as a superclass (base class) for more than one subclass.In below image, class A serves as a base class for the derived class B, C, and D. " }, { "code": null, "e": 30041, "s": 30030, "text": "Example: " }, { "code": null, "e": 30047, "s": 30041, "text": "Scala" }, { "code": "// Scala program to illustrate the// Hierarchical inheritance // Base classclass Parent{ var Name1: String = \"Siya\" var Name2: String = \"Soniya\"} // Derived from the parent classclass Child1 extends Parent{ var Age: Int = 32 def details1() { println(\" Name: \" +Name1); println(\" Age: \" +Age); }} // Derived from Parent classclass Child2 extends Parent{ var Height: Int = 164 // Method def details2() { println(\" Name: \" +Name2); println(\" Height: \" +Height); }} object Main{ // Driver code def main(args: Array[String]) { // Creating objects of both derived classes val ob1 = new Child1(); val ob2 = new Child2(); ob1.details1(); ob2.details2(); }}", "e": 30807, "s": 30047, "text": null }, { "code": null, "e": 30817, "s": 30807, "text": "Output: " }, { "code": null, "e": 30865, "s": 30817, "text": " Name: Siya\n Age: 32\n Name: Soniya\n Height: 164" }, { "code": null, "e": 31096, "s": 30865, "text": "Multiple Inheritance: In Multiple inheritance ,one class can have more than one superclass and inherit features from all parent classes. Scala does not support multiple inheritance with classes, but it can be achieved by traits. " }, { "code": null, "e": 31107, "s": 31096, "text": "Example: " }, { "code": null, "e": 31113, "s": 31107, "text": "Scala" }, { "code": "// Scala program to illustrate the// multiple inheritance using traits // Trait 1trait Geeks1{ def method1()} // Trait 2trait Geeks2{ def method2()} // Class that implement both Geeks1 and Geeks2 traitsclass GFG extends Geeks1 with Geeks2{ // method1 from Geeks1 def method1() { println(\"Trait 1\"); } // method2 from Geeks2 def method2() { println(\"Trait 2\"); }}object Main{ // Driver code def main(args: Array[String]) { // Creating object of GFG class var obj = new GFG(); obj.method1(); obj.method2(); }}", "e": 31724, "s": 31113, "text": null }, { "code": null, "e": 31733, "s": 31724, "text": "Output: " }, { "code": null, "e": 31749, "s": 31733, "text": "Trait 1\nTrait 2" }, { "code": null, "e": 32019, "s": 31749, "text": "Hybrid Inheritance: It is a mix of two or more of the above types of inheritance. Since Scala doesn’t support multiple inheritance with classes, the hybrid inheritance is also not possible with classes. In Scala, we can achieve hybrid inheritance only through traits. " }, { "code": null, "e": 32031, "s": 32021, "text": "rkkatta28" }, { "code": null, "e": 32037, "s": 32031, "text": "Scala" }, { "code": null, "e": 32055, "s": 32037, "text": "Scala-Inheritance" }, { "code": null, "e": 32066, "s": 32055, "text": "Scala-OOPS" }, { "code": null, "e": 32072, "s": 32066, "text": "Scala" }, { "code": null, "e": 32170, "s": 32072, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32188, "s": 32170, "text": "For Loop in Scala" }, { "code": null, "e": 32211, "s": 32188, "text": "Scala | flatMap Method" }, { "code": null, "e": 32232, "s": 32211, "text": "Scala | map() method" }, { "code": null, "e": 32272, "s": 32232, "text": "Scala List filter() method with example" }, { "code": null, "e": 32298, "s": 32272, "text": "Scala | reduce() Function" }, { "code": null, "e": 32328, "s": 32298, "text": "String concatenation in Scala" }, { "code": null, "e": 32350, "s": 32328, "text": "Type Casting in Scala" }, { "code": null, "e": 32403, "s": 32350, "text": "Scala Tutorial – Learn Scala with Step By Step Guide" }, { "code": null, "e": 32445, "s": 32403, "text": "Scala List contains() method with example" } ]
Compare numbers represented by Linked Lists - GeeksforGeeks
08 Mar, 2022 Given the pointers to the head nodes of two linked lists. The task is to compare the numbers represented by the linked lists. The numbers represented by the lists may contain leading zeros. If the numbers are equal then print 0.If the number represented by the first linked list is greater than print 1.If the number represented by the second linked list is greater than print -1. If the numbers are equal then print 0. If the number represented by the first linked list is greater than print 1. If the number represented by the second linked list is greater than print -1. Examples: Input: List1 = 2 -> 3 -> 1 -> 2 -> 4 -> NULL List2 = 2 -> 3 -> 2 -> 4 -> 2 -> NULL Output: -1 Input: List1 = 0 -> 0 -> 1 -> 2 -> 4 -> NULL List2 = 0 -> 0 -> 0 -> 4 -> 2 -> NULL Output: 1 Approach: Since the numbers may contain leading zeros, first remove all the leading zeros from the start of the linked lists. After that compare their lengths, if the lengths are unequal, this means that one of the numbers is definitely greater and returns 1 or -1 based upon whose length is greater. Else traverse both the lists simultaneously, and while traversing we compare the digits at every node. If at any point, the digit is unequal then return either 1 or -1 based on the value of the digits. If the end of the linked lists is reached then the linked lists are identical and hence return 0. 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; /* Structure for a linked list node */struct Node { int data; struct Node* next;}; /* A helper function to remove zeros fromthe start of the linked list */Node* removeLeadingZeros(struct Node* a){ if (a != NULL && a->data == 0) return removeLeadingZeros(a->next); else return a;} /* A helper function to find the length oflinked list*/int getSize(struct Node* a){ int sz = 0; while (a != NULL) { a = a->next; sz++; } return sz;} /* Given a reference (pointer to pointer) to thehead of a list and an int, push a new node on thefront of the list. */void push(struct Node** head_ref, int new_data){ /* Allocate node */ struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); /* Set the data */ new_node->data = new_data; /* Link the old list after the new node */ new_node->next = (*head_ref); /* Set the head to point to the new node */ (*head_ref) = new_node;} // Function to compare the numbers// represented as linked listsint compare(struct Node* a, struct Node* b){ // Remover leading zeroes from // the linked lists a = removeLeadingZeros(a); b = removeLeadingZeros(b); int lenA = getSize(a); int lenB = getSize(b); if (lenA > lenB) { /* Since the number represented by a has a greater length, it will be greater*/ return 1; } else if (lenB > lenA) { return -1; } /* If the lengths of two numbers are equal we have to check their magnitudes*/ while (a != NULL && b != NULL) { if (a->data > b->data) return 1; else if (a->data < b->data) return -1; /* If we reach here, then a and b are not NULL and their data is same, so move to next nodes in both lists */ a = a->next; b = b->next; } // If linked lists are identical, then // we need to return zero return 0;} // Driver codeint main(){ /* The constructed linked lists are : a: 5->6->7 b: 2->3->3 */ struct Node* a = NULL; push(&a, 7); push(&a, 6); push(&a, 5); struct Node* b = NULL; push(&b, 3); push(&b, 3); push(&b, 2); cout << compare(a, b); return 0;} // Java implementation of the approachclass GFG{ /* Structure for a linked list node */static class Node{ int data; Node next;}; /* A helper function to remove zeros fromthe start of the linked list */static Node removeLeadingZeros(Node a){ if (a != null && a.data == 0) return removeLeadingZeros(a.next); else return a;} /* A helper function to find the length oflinked list*/static int getSize(Node a){ int sz = 0; while (a != null) { a = a.next; sz++; } return sz;} /* Given a reference (pointer to pointer) to thehead of a list and an int, push a new node on thefront of the list. */static Node push(Node head_ref, int new_data){ /* Allocate node */ Node new_node = new Node(); /* Set the data */ new_node.data = new_data; /* Link the old list after the new node */ new_node.next = head_ref; /* Set the head to point to the new node */ head_ref = new_node; return head_ref;} // Function to compare the numbers// represented as linked listsstatic int compare(Node a, Node b){ // Remover leading zeroes from // the linked lists a = removeLeadingZeros(a); b = removeLeadingZeros(b); int lenA = getSize(a); int lenB = getSize(b); if (lenA > lenB) { /* Since the number represented by a has a greater length, it will be greater*/ return 1; } else if (lenB > lenA) { return -1; } /* If the lengths of two numbers are equal we have to check their magnitudes*/ while (a != null && b != null) { if (a.data > b.data) return 1; else if (a.data < b.data) return -1; /* If we reach here, then a and b are not null and their data is same, so move to next nodes in both lists */ a = a.next; b = b.next; } // If linked lists are identical, then // we need to return zero return 0;} // Driver codepublic static void main(String[] args){ /* The constructed linked lists are : a: 5->6->7 b: 2->3->3 */ Node a = null; a = push(a, 7); a = push(a, 6); a = push(a, 5); Node b = null; b = push(b, 3); b = push(b, 3); b = push(b, 2); System.out.println(compare(a, b));}} // This code is contributed by Rajput-Ji # Python3 implementation of the approach ''' Structure for a linked list node '''class Node: def __init__(self): self.data = 0 self.next = None ''' A helper function to remove zeros fromthe start of the linked list '''def removeLeadingZeros(a): if (a != None and a.data == 0): return removeLeadingZeros(a.next); else: return a; ''' A helper function to find the length oflinked list'''def getSize(a): sz = 0; while (a != None): a = a.next; sz += 1 return sz; ''' Given a reference (pointer to pointer) to thehead of a list and an int, push a new node on thefront of the list. '''def push(head_ref, new_data): ''' Allocate node ''' new_node = Node() ''' Set the data ''' new_node.data = new_data; ''' Link the old list after the new node ''' new_node.next = (head_ref); ''' Set the head to point to the new node ''' (head_ref) = new_node; return head_ref # Function to compare the numbers# represented as linked listsdef compare(a, b): # Remover leading zeroes from # the linked lists a = removeLeadingZeros(a); b = removeLeadingZeros(b); lenA = getSize(a); lenB = getSize(b); if (lenA > lenB): ''' Since the number represented by a has a greater length, it will be greater''' return 1; elif (lenB > lenA): return -1; ''' If the lengths of two numbers are equal we have to check their magnitudes''' while (a != None and b != None): if (a.data > b.data): return 1; elif (a.data < b.data): return -1; ''' If we reach here, then a and b are not None and their data is same, so move to next nodes in both lists ''' a = a.next; b = b.next; # If linked lists are identical, then # we need to return zero return 0; # Driver codeif __name__=='__main__': ''' The constructed linked lists are : a: 5.6.7 b: 2.3.3 ''' a = None; a = push(a, 7); a = push(a, 6); a = push(a, 5); b = None; b = push(b, 3); b = push(b, 3); b = push(b, 2); print(compare(a, b)) # This code is contributed by rutvik_56 // C# implementation of the approachusing System;using System.Collections.Generic; class GFG{ /* Structure for a linked list node */public class Node{ public int data; public Node next;}; /* A helper function to remove zeros fromthe start of the linked list */static Node removeLeadingZeros(Node a){ if (a != null && a.data == 0) return removeLeadingZeros(a.next); else return a;} /* A helper function to find the length oflinked list*/static int getSize(Node a){ int sz = 0; while (a != null) { a = a.next; sz++; } return sz;} /* Given a reference (pointer to pointer) to thehead of a list and an int, push a new node on thefront of the list. */static Node push(Node head_ref, int new_data){ /* Allocate node */ Node new_node = new Node(); /* Set the data */ new_node.data = new_data; /* Link the old list after the new node */ new_node.next = head_ref; /* Set the head to point to the new node */ head_ref = new_node; return head_ref;} // Function to compare the numbers// represented as linked listsstatic int compare(Node a, Node b){ // Remover leading zeroes from // the linked lists a = removeLeadingZeros(a); b = removeLeadingZeros(b); int lenA = getSize(a); int lenB = getSize(b); if (lenA > lenB) { /* Since the number represented by a has a greater length, it will be greater*/ return 1; } else if (lenB > lenA) { return -1; } /* If the lengths of two numbers are equal we have to check their magnitudes*/ while (a != null && b != null) { if (a.data > b.data) return 1; else if (a.data < b.data) return -1; /* If we reach here, then a and b are not null and their data is same, so move to next nodes in both lists */ a = a.next; b = b.next; } // If linked lists are identical, then // we need to return zero return 0;} // Driver codepublic static void Main(String[] args){ /* The constructed linked lists are : a: 5->6->7 b: 2->3->3 */ Node a = null; a = push(a, 7); a = push(a, 6); a = push(a, 5); Node b = null; b = push(b, 3); b = push(b, 3); b = push(b, 2); Console.WriteLine(compare(a, b));}} // This code is contributed by 29AjayKumar <script> // JavaScript implementation of the approach /* Structure for a linked list node */class Node { constructor() { this.data = 0; this.next = null; } } /* A helper function to remove zeros fromthe start of the linked list */function removeLeadingZeros( a){ if (a != null && a.data == 0) return removeLeadingZeros(a.next); else return a;} /* A helper function to find the length oflinked list*/function getSize( a){ let sz = 0; while (a != null) { a = a.next; sz++; } return sz;} /* Given a reference (pointer to pointer) to thehead of a list and an int, push a new node on thefront of the list. */function push( head_ref, new_data){ /* Allocate node */ var new_node = new Node(); /* Set the data */ new_node.data = new_data; /* Link the old list after the new node */ new_node.next = head_ref; /* Set the head to point to the new node */ head_ref = new_node; return head_ref;} // Function to compare the numbers// represented as linked listsfunction compare( a, b){ // Remover leading zeroes from // the linked lists a = removeLeadingZeros(a); b = removeLeadingZeros(b); let lenA = getSize(a); let lenB = getSize(b); if (lenA > lenB) { /* Since the number represented by a has a greater length, it will be greater*/ return 1; } else if (lenB > lenA) { return -1; } /* If the lengths of two numbers are equal we have to check their magnitudes*/ while (a != null && b != null) { if (a.data > b.data) return 1; else if (a.data < b.data) return -1; /* If we reach here, then a and b are not null and their data is same, so move to next nodes in both lists */ a = a.next; b = b.next; } // If linked lists are identical, then // we need to return zero return 0;} // Driver Code /* The constructed linked lists are :a: 5->6->7b: 2->3->3 */var a = null;a = push(a, 7);a = push(a, 6);a = push(a, 5); var b = null;b = push(b, 3);b = push(b, 3);b = push(b, 2); document.write(compare(a, b)); </script> 1 Time Complexity: O(max(N, M)) where N and M are the lengths of the linked lists. Auxiliary Space: O(1) Rajput-Ji 29AjayKumar rutvik_56 jana_sayantan anikakapoor prachisoda1234 arorakashish0911 surinderdawra388 subhammahato348 Numbers Linked List Mathematical Linked List Mathematical Numbers Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Circular Linked List | Set 2 (Traversal) Swap nodes in a linked list without swapping data Program to implement Singly Linked List in C++ using class Circular Singly Linked List | Insertion Given a linked list which is sorted, how will you insert in sorted way 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": 26179, "s": 26151, "text": "\n08 Mar, 2022" }, { "code": null, "e": 26370, "s": 26179, "text": "Given the pointers to the head nodes of two linked lists. The task is to compare the numbers represented by the linked lists. The numbers represented by the lists may contain leading zeros. " }, { "code": null, "e": 26561, "s": 26370, "text": "If the numbers are equal then print 0.If the number represented by the first linked list is greater than print 1.If the number represented by the second linked list is greater than print -1." }, { "code": null, "e": 26600, "s": 26561, "text": "If the numbers are equal then print 0." }, { "code": null, "e": 26676, "s": 26600, "text": "If the number represented by the first linked list is greater than print 1." }, { "code": null, "e": 26754, "s": 26676, "text": "If the number represented by the second linked list is greater than print -1." }, { "code": null, "e": 26766, "s": 26754, "text": "Examples: " }, { "code": null, "e": 26860, "s": 26766, "text": "Input: List1 = 2 -> 3 -> 1 -> 2 -> 4 -> NULL List2 = 2 -> 3 -> 2 -> 4 -> 2 -> NULL Output: -1" }, { "code": null, "e": 26954, "s": 26860, "text": "Input: List1 = 0 -> 0 -> 1 -> 2 -> 4 -> NULL List2 = 0 -> 0 -> 0 -> 4 -> 2 -> NULL Output: 1 " }, { "code": null, "e": 27555, "s": 26954, "text": "Approach: Since the numbers may contain leading zeros, first remove all the leading zeros from the start of the linked lists. After that compare their lengths, if the lengths are unequal, this means that one of the numbers is definitely greater and returns 1 or -1 based upon whose length is greater. Else traverse both the lists simultaneously, and while traversing we compare the digits at every node. If at any point, the digit is unequal then return either 1 or -1 based on the value of the digits. If the end of the linked lists is reached then the linked lists are identical and hence return 0." }, { "code": null, "e": 27608, "s": 27555, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 27612, "s": 27608, "text": "C++" }, { "code": null, "e": 27617, "s": 27612, "text": "Java" }, { "code": null, "e": 27625, "s": 27617, "text": "Python3" }, { "code": null, "e": 27628, "s": 27625, "text": "C#" }, { "code": null, "e": 27639, "s": 27628, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; /* Structure for a linked list node */struct Node { int data; struct Node* next;}; /* A helper function to remove zeros fromthe start of the linked list */Node* removeLeadingZeros(struct Node* a){ if (a != NULL && a->data == 0) return removeLeadingZeros(a->next); else return a;} /* A helper function to find the length oflinked list*/int getSize(struct Node* a){ int sz = 0; while (a != NULL) { a = a->next; sz++; } return sz;} /* Given a reference (pointer to pointer) to thehead of a list and an int, push a new node on thefront of the list. */void push(struct Node** head_ref, int new_data){ /* Allocate node */ struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); /* Set the data */ new_node->data = new_data; /* Link the old list after the new node */ new_node->next = (*head_ref); /* Set the head to point to the new node */ (*head_ref) = new_node;} // Function to compare the numbers// represented as linked listsint compare(struct Node* a, struct Node* b){ // Remover leading zeroes from // the linked lists a = removeLeadingZeros(a); b = removeLeadingZeros(b); int lenA = getSize(a); int lenB = getSize(b); if (lenA > lenB) { /* Since the number represented by a has a greater length, it will be greater*/ return 1; } else if (lenB > lenA) { return -1; } /* If the lengths of two numbers are equal we have to check their magnitudes*/ while (a != NULL && b != NULL) { if (a->data > b->data) return 1; else if (a->data < b->data) return -1; /* If we reach here, then a and b are not NULL and their data is same, so move to next nodes in both lists */ a = a->next; b = b->next; } // If linked lists are identical, then // we need to return zero return 0;} // Driver codeint main(){ /* The constructed linked lists are : a: 5->6->7 b: 2->3->3 */ struct Node* a = NULL; push(&a, 7); push(&a, 6); push(&a, 5); struct Node* b = NULL; push(&b, 3); push(&b, 3); push(&b, 2); cout << compare(a, b); return 0;}", "e": 29938, "s": 27639, "text": null }, { "code": "// Java implementation of the approachclass GFG{ /* Structure for a linked list node */static class Node{ int data; Node next;}; /* A helper function to remove zeros fromthe start of the linked list */static Node removeLeadingZeros(Node a){ if (a != null && a.data == 0) return removeLeadingZeros(a.next); else return a;} /* A helper function to find the length oflinked list*/static int getSize(Node a){ int sz = 0; while (a != null) { a = a.next; sz++; } return sz;} /* Given a reference (pointer to pointer) to thehead of a list and an int, push a new node on thefront of the list. */static Node push(Node head_ref, int new_data){ /* Allocate node */ Node new_node = new Node(); /* Set the data */ new_node.data = new_data; /* Link the old list after the new node */ new_node.next = head_ref; /* Set the head to point to the new node */ head_ref = new_node; return head_ref;} // Function to compare the numbers// represented as linked listsstatic int compare(Node a, Node b){ // Remover leading zeroes from // the linked lists a = removeLeadingZeros(a); b = removeLeadingZeros(b); int lenA = getSize(a); int lenB = getSize(b); if (lenA > lenB) { /* Since the number represented by a has a greater length, it will be greater*/ return 1; } else if (lenB > lenA) { return -1; } /* If the lengths of two numbers are equal we have to check their magnitudes*/ while (a != null && b != null) { if (a.data > b.data) return 1; else if (a.data < b.data) return -1; /* If we reach here, then a and b are not null and their data is same, so move to next nodes in both lists */ a = a.next; b = b.next; } // If linked lists are identical, then // we need to return zero return 0;} // Driver codepublic static void main(String[] args){ /* The constructed linked lists are : a: 5->6->7 b: 2->3->3 */ Node a = null; a = push(a, 7); a = push(a, 6); a = push(a, 5); Node b = null; b = push(b, 3); b = push(b, 3); b = push(b, 2); System.out.println(compare(a, b));}} // This code is contributed by Rajput-Ji", "e": 32250, "s": 29938, "text": null }, { "code": "# Python3 implementation of the approach ''' Structure for a linked list node '''class Node: def __init__(self): self.data = 0 self.next = None ''' A helper function to remove zeros fromthe start of the linked list '''def removeLeadingZeros(a): if (a != None and a.data == 0): return removeLeadingZeros(a.next); else: return a; ''' A helper function to find the length oflinked list'''def getSize(a): sz = 0; while (a != None): a = a.next; sz += 1 return sz; ''' Given a reference (pointer to pointer) to thehead of a list and an int, push a new node on thefront of the list. '''def push(head_ref, new_data): ''' Allocate node ''' new_node = Node() ''' Set the data ''' new_node.data = new_data; ''' Link the old list after the new node ''' new_node.next = (head_ref); ''' Set the head to point to the new node ''' (head_ref) = new_node; return head_ref # Function to compare the numbers# represented as linked listsdef compare(a, b): # Remover leading zeroes from # the linked lists a = removeLeadingZeros(a); b = removeLeadingZeros(b); lenA = getSize(a); lenB = getSize(b); if (lenA > lenB): ''' Since the number represented by a has a greater length, it will be greater''' return 1; elif (lenB > lenA): return -1; ''' If the lengths of two numbers are equal we have to check their magnitudes''' while (a != None and b != None): if (a.data > b.data): return 1; elif (a.data < b.data): return -1; ''' If we reach here, then a and b are not None and their data is same, so move to next nodes in both lists ''' a = a.next; b = b.next; # If linked lists are identical, then # we need to return zero return 0; # Driver codeif __name__=='__main__': ''' The constructed linked lists are : a: 5.6.7 b: 2.3.3 ''' a = None; a = push(a, 7); a = push(a, 6); a = push(a, 5); b = None; b = push(b, 3); b = push(b, 3); b = push(b, 2); print(compare(a, b)) # This code is contributed by rutvik_56", "e": 34471, "s": 32250, "text": null }, { "code": "// C# implementation of the approachusing System;using System.Collections.Generic; class GFG{ /* Structure for a linked list node */public class Node{ public int data; public Node next;}; /* A helper function to remove zeros fromthe start of the linked list */static Node removeLeadingZeros(Node a){ if (a != null && a.data == 0) return removeLeadingZeros(a.next); else return a;} /* A helper function to find the length oflinked list*/static int getSize(Node a){ int sz = 0; while (a != null) { a = a.next; sz++; } return sz;} /* Given a reference (pointer to pointer) to thehead of a list and an int, push a new node on thefront of the list. */static Node push(Node head_ref, int new_data){ /* Allocate node */ Node new_node = new Node(); /* Set the data */ new_node.data = new_data; /* Link the old list after the new node */ new_node.next = head_ref; /* Set the head to point to the new node */ head_ref = new_node; return head_ref;} // Function to compare the numbers// represented as linked listsstatic int compare(Node a, Node b){ // Remover leading zeroes from // the linked lists a = removeLeadingZeros(a); b = removeLeadingZeros(b); int lenA = getSize(a); int lenB = getSize(b); if (lenA > lenB) { /* Since the number represented by a has a greater length, it will be greater*/ return 1; } else if (lenB > lenA) { return -1; } /* If the lengths of two numbers are equal we have to check their magnitudes*/ while (a != null && b != null) { if (a.data > b.data) return 1; else if (a.data < b.data) return -1; /* If we reach here, then a and b are not null and their data is same, so move to next nodes in both lists */ a = a.next; b = b.next; } // If linked lists are identical, then // we need to return zero return 0;} // Driver codepublic static void Main(String[] args){ /* The constructed linked lists are : a: 5->6->7 b: 2->3->3 */ Node a = null; a = push(a, 7); a = push(a, 6); a = push(a, 5); Node b = null; b = push(b, 3); b = push(b, 3); b = push(b, 2); Console.WriteLine(compare(a, b));}} // This code is contributed by 29AjayKumar", "e": 36837, "s": 34471, "text": null }, { "code": "<script> // JavaScript implementation of the approach /* Structure for a linked list node */class Node { constructor() { this.data = 0; this.next = null; } } /* A helper function to remove zeros fromthe start of the linked list */function removeLeadingZeros( a){ if (a != null && a.data == 0) return removeLeadingZeros(a.next); else return a;} /* A helper function to find the length oflinked list*/function getSize( a){ let sz = 0; while (a != null) { a = a.next; sz++; } return sz;} /* Given a reference (pointer to pointer) to thehead of a list and an int, push a new node on thefront of the list. */function push( head_ref, new_data){ /* Allocate node */ var new_node = new Node(); /* Set the data */ new_node.data = new_data; /* Link the old list after the new node */ new_node.next = head_ref; /* Set the head to point to the new node */ head_ref = new_node; return head_ref;} // Function to compare the numbers// represented as linked listsfunction compare( a, b){ // Remover leading zeroes from // the linked lists a = removeLeadingZeros(a); b = removeLeadingZeros(b); let lenA = getSize(a); let lenB = getSize(b); if (lenA > lenB) { /* Since the number represented by a has a greater length, it will be greater*/ return 1; } else if (lenB > lenA) { return -1; } /* If the lengths of two numbers are equal we have to check their magnitudes*/ while (a != null && b != null) { if (a.data > b.data) return 1; else if (a.data < b.data) return -1; /* If we reach here, then a and b are not null and their data is same, so move to next nodes in both lists */ a = a.next; b = b.next; } // If linked lists are identical, then // we need to return zero return 0;} // Driver Code /* The constructed linked lists are :a: 5->6->7b: 2->3->3 */var a = null;a = push(a, 7);a = push(a, 6);a = push(a, 5); var b = null;b = push(b, 3);b = push(b, 3);b = push(b, 2); document.write(compare(a, b)); </script>", "e": 39060, "s": 36837, "text": null }, { "code": null, "e": 39062, "s": 39060, "text": "1" }, { "code": null, "e": 39145, "s": 39064, "text": "Time Complexity: O(max(N, M)) where N and M are the lengths of the linked lists." }, { "code": null, "e": 39167, "s": 39145, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 39177, "s": 39167, "text": "Rajput-Ji" }, { "code": null, "e": 39189, "s": 39177, "text": "29AjayKumar" }, { "code": null, "e": 39199, "s": 39189, "text": "rutvik_56" }, { "code": null, "e": 39213, "s": 39199, "text": "jana_sayantan" }, { "code": null, "e": 39225, "s": 39213, "text": "anikakapoor" }, { "code": null, "e": 39240, "s": 39225, "text": "prachisoda1234" }, { "code": null, "e": 39257, "s": 39240, "text": "arorakashish0911" }, { "code": null, "e": 39274, "s": 39257, "text": "surinderdawra388" }, { "code": null, "e": 39290, "s": 39274, "text": "subhammahato348" }, { "code": null, "e": 39298, "s": 39290, "text": "Numbers" }, { "code": null, "e": 39310, "s": 39298, "text": "Linked List" }, { "code": null, "e": 39323, "s": 39310, "text": "Mathematical" }, { "code": null, "e": 39335, "s": 39323, "text": "Linked List" }, { "code": null, "e": 39348, "s": 39335, "text": "Mathematical" }, { "code": null, "e": 39356, "s": 39348, "text": "Numbers" }, { "code": null, "e": 39454, "s": 39356, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 39495, "s": 39454, "text": "Circular Linked List | Set 2 (Traversal)" }, { "code": null, "e": 39545, "s": 39495, "text": "Swap nodes in a linked list without swapping data" }, { "code": null, "e": 39604, "s": 39545, "text": "Program to implement Singly Linked List in C++ using class" }, { "code": null, "e": 39644, "s": 39604, "text": "Circular Singly Linked List | Insertion" }, { "code": null, "e": 39715, "s": 39644, "text": "Given a linked list which is sorted, how will you insert in sorted way" }, { "code": null, "e": 39745, "s": 39715, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 39805, "s": 39745, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 39820, "s": 39805, "text": "C++ Data Types" }, { "code": null, "e": 39863, "s": 39820, "text": "Set in C++ Standard Template Library (STL)" } ]
How to use Firestore Database in ReactJS ? - GeeksforGeeks
01 Aug, 2021 Firebase is a Google Product that helps us build, manage, and grow our app easily. In this article, we will see how you can use firebase firestore as a backend and use G-auth provided by firebase in our demo react project. When you design apps like mobile apps like iOS or Android apps or web apps, the database is kind of a big problem and not because it’s hard to design of course it’s a little bit tricky to design as well as sometimes it consumes a lot of bandwidth trafficking between your database and your applications front end is kind of a big issue on top of that host page is again a problem, imagine if your app is having photo sharing things and you want to access all the photos there so it’s not easy to maintain all of these things now on top of that managing your own authentication system is also tricky because everybody needs authentication from Facebook maybe Twitter maybe google or even a simple login system is not easy to design from scratch. Now here comes the firebase, firebase gives you a complete solution about how things can be taken down. Now it’s a very good complete back-end solution that you can use. Now with the firebase, you can do all sorts of authentication most common ones are username, email, and password but there are plenty of different ways you can log in, below is a snapshot of all possible ways. Also firebase solves a very good problem of database it gives you a real-time database and in this article, we will see how to use firebase for database. Creating React Application And Installing Module: Step 1: Create a React application using the following command: npx create-react-app foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command: cd foldername Step 3: After creating the ReactJS application, Install the required module using the following command: npm i firebase Project Structure: It will look like the following. Project Structure Step to Run Application: Run the application using the following command from the root directory of the project: npm start Let’s first create two input fields namely Name and Password and with a Submit Button. App.js import React, { useState } from "react";import "./App.css"; function App() { const [customerName, setCustomerName] = useState(""); const [customerPassword, setCustomerPassword] = useState(""); return ( <div className="App"> <div className="App__form"> <input type="text" placeholder="Name" value={customerName} onChange={(e) => setCustomerName(e.target.value)} /> <input type="text" placeholder="Password" value={customerPassword} onChange={(e) => setCustomerPassword(e.target.value)} /> <button>Submit</button> </div> </div> );} export default App; App.css .App { text-align: center; height: 100vh; display: grid; place-items: center;} .App__form { display: flex; flex-direction: column;} input { padding: 7px 11px; border-radius: 3px; border: none; border-bottom: 1px solid gray; margin: 20px; outline: none;} button { display: inline-block; margin-right: auto; margin-left: auto; padding: 7px 12px; border: none; border-radius: 4px;} Now we will create the firebase project and create the firebase config file. Steps to create a firebase project: Step 1: Login in the firebase dashboard and Click on Add Project Card. Step 2: Enter your project name click on continue. Step 3: In Configure Google Analytics select Default Account for Firebase and click on Create Project. Step 4: Wait for firebase to create your project. Step 5: Once the project is created go to the web icon as shown. Step 6: Give the app nick name and select the firebase hosting checkbox if you want to host your app using firebase, register your app. Step 7: Just install Firebase CLI if not installed yet using command given below on your VScode’s terminal npm install -g firebase-tools Step 8: Once done, just login into your firebase using the command given below using your command line or the terminal in VSCode. firebase login Step 9: Click on Continue to Console. Step 10: Next go to your app click on the settings icon and at the bottom select the config option copy the config data. Go to your local project and create a file named firebase.js in the src folder and paste the config data along with few more lines in it as shown below. firebase.js import firebase from "firebase"; const firebaseConfig = { apiKey: "AIzaSyATKyTSJVN7-Zx60WQ66kkHo3nBhuMhYDs", authDomain: "meteor-3fd94.firebaseapp.com", projectId: "meteor-3fd94", storageBucket: "meteor-3fd94.appspot.com", messagingSenderId: "391620415322", appId: "1:391620415322:web:6848292646d9e91e6e6d63", measurementId: "G-69J20TCH7X",}; const firebaseApp = firebase.initializeApp(firebaseConfig);const db = firebase.firestore(); export default db; Now we have the config file ready and we just need to add code for the CRUD operations : 1. Create collection: To create a collection we simply use the db object we created in the firebase.js above. We simply import it in our file and use the collection method to locate the collection in which our data is to be stored after creation. In case your collection is nested in other collection you’ll have to write it like, db.collection(<parent-collection>).doc(<doc-id>).collection(<child-collection>) and so on. Now once we are in our collection we just simply add our data as an object. App.js import React, { useState } from "react";import "./App.css";import db from "./firebase"; function App() { const [customerName, setCustomerName] = useState(""); const [customerPassword, setCustomerPassword] = useState(""); const submit = (e) => { e.preventDefault(); db.collection("customersData").add({ name: customerName, password: customerPassword, }); setCustomerName(""); setCustomerPassword(""); }; return ( <div className="App"> <div className="App__form"> <input type="text" placeholder="Name" value={customerName} onChange={(e) => setCustomerName(e.target.value)} /> <input type="text" placeholder="Password" value={customerPassword} onChange={(e) => setCustomerPassword(e.target.value)} /> <button onClick={submit}>Submit</button> </div> </div> );} export default App; Now we will test if our code works. Once we see this page then we are all set. Just go to the localhost and enter the details and press submit and then again open Firestore Database in Firebase and you’ll see something like shown below : So we can see our data as shown above 2. Read Operation: Now to read data, initial process is same i.e., importing db object. No we go to the collection where our data is stored that we want to read and then we use the onSnapshot method, which as the name suggests simply takes the snapshot every time any changes happen in the database. This function is responsible for the realtime feel that we get when we use firebase. App.js import React, { useState, useEffect } from "react";import "./App.css";import db from "./firebase"; function App() { const [customerName, setCustomerName] = useState(""); const [customerPassword, setCustomerPassword] = useState(""); const [customersData, setCustomersData] = useState([]); useEffect(() => { db.collection("customersData").onSnapshot((snapshot) => { setCustomersData( snapshot.docs.map((doc) => ({ id: doc.id, data: doc.data(), })) ); }); console.log({ customersData }); }, []); const submit = (e) => { e.preventDefault(); db.collection("customersData").add({ name: customerName, password: customerPassword, }); setCustomerName(""); setCustomerPassword(""); }; return ( <div className="App"> <div className="App__form"> <input type="text" placeholder="Name" value={customerName} onChange={(e) => setCustomerName(e.target.value)} /> <input type="text" placeholder="Password" value={customerPassword} onChange={(e) => setCustomerPassword(e.target.value)} /> <button onClick={submit}>Submit</button> </div> <div className="App__DataDisplay"> <table> <tr> <th>NAME</th> <th>PASSWORD</th> </tr> {customersData?.map(({ id, data }) => ( <tr key={id}> <td>{data.name}</td> <td>{data.password}</td> </tr> ))} </table> </div> </div> );} export default App; Step to Run Application: Run the application using the following command from the root directory of the project: npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output: 3. Update Operation: Let’s first a button that should update and the fields that should appear.Now after we have imported the db object from firebase.js we simply go to the collection where our data is stored that is to be updated and then we specify the doc we need to update as one collection has many documents so we have to specify that what doc is to be updated and then we simply use the update method and pass the updated object. App.js import React, { useState, useEffect } from "react";import "./App.css";import db from "./firebase"; function App() { const [customerName, setCustomerName] = useState(""); const [customerPassword, setCustomerPassword] = useState(""); const [customersData, setCustomersData] = useState([]); const [updatedCustomerName, setUpdatedCustomerName] = useState(""); const [updatedCustomerPassword, setUpdatedCustomerPassword] = useState(""); const [dataIdToBeUpdated, setDataIdToBeUpdated] = useState(""); useEffect(() => { db.collection("customersData").onSnapshot((snapshot) => { setCustomersData( snapshot.docs.map((doc) => ({ id: doc.id, data: doc.data(), })) ); }); }, []); const submit = (e) => { e.preventDefault(); db.collection("customersData").add({ name: customerName, password: customerPassword, }); setCustomerName(""); setCustomerPassword(""); }; const updateData = (e) => { e.preventDefault(); db.collection("customersData").doc(dataIdToBeUpdated).update({ name: updatedCustomerName, password: updatedCustomerPassword, }); setUpdatedCustomerPassword(""); setUpdatedCustomerName(""); setDataIdToBeUpdated(""); }; return ( <div className="App"> {!dataIdToBeUpdated ? ( <div className="App__form"> <input type="text" placeholder="Name" value={customerName} onChange={(e) => setCustomerName(e.target.value)} /> <input type="text" placeholder="Password" value={customerPassword} onChange={(e) => setCustomerPassword(e.target.value)} /> <button onClick={submit}>Submit</button> </div> ) : ( <div className="App__Updateform"> <input type="text" placeholder="Name" value={updatedCustomerName} onChange={(e) => setUpdatedCustomerName(e.target.value)} /> <input type="text" placeholder="Password" value={updatedCustomerPassword} onChange={(e) => setUpdatedCustomerPassword(e.target.value)} /> <button onClick={updateData}>Update</button> </div> )} <div className="App__DataDisplay"> <table> <tr> <th>NAME</th> <th>PASSWORD</th> <th>Update</th> </tr> {customersData?.map(({ id, data }) => ( <tr key={id}> <td>{data.name}</td> <td>{data.password}</td> <td> <button onClick={() => { setDataIdToBeUpdated(id); setUpdatedCustomerPassword(data.password); setUpdatedCustomerName(data.name); }} > Update </button> </td> </tr> ))} </table> </div> </div> );} export default App; Step to Run Application: Run the application using the following command from the root directory of the project: npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output. After updating the data you can check in your firebase dashboard if data get updated or not. 4. Delete Operation: Starting with the same thing, we import db object in our file then we simply go to the collection where our data is stored that is to be deleted and then we specify the doc we need to delete as one collection has many documents so we have to specify that what doc is to be deleted and then we simply call the delete method. App.js import React, { useState, useEffect } from "react";import "./App.css";import db from "./firebase"; function App() { const [customerName, setCustomerName] = useState(""); const [customerPassword, setCustomerPassword] = useState(""); const [customersData, setCustomersData] = useState([]); const [updatedCustomerName, setUpdatedCustomerName] = useState(""); const [updatedCustomerPassword, setUpdatedCustomerPassword] = useState(""); const [dataIdToBeUpdated, setDataIdToBeUpdated] = useState(""); useEffect(() => { db.collection("customersData").onSnapshot((snapshot) => { setCustomersData( snapshot.docs.map((doc) => ({ id: doc.id, data: doc.data(), })) ); }); }, []); const submit = (e) => { e.preventDefault(); db.collection("customersData").add({ name: customerName, password: customerPassword, }); setCustomerName(""); setCustomerPassword(""); }; const updateData = (e) => { e.preventDefault(); db.collection("customersData").doc(dataIdToBeUpdated).update({ name: updatedCustomerName, password: updatedCustomerPassword, }); setUpdatedCustomerPassword(""); setUpdatedCustomerName(""); setDataIdToBeUpdated(""); }; const deleteData = (id) => { db.collection("customersData").doc(id).delete(); }; return ( <div className="App"> {!dataIdToBeUpdated ? ( <div className="App__form"> <input type="text" placeholder="Name" value={customerName} onChange={(e) => setCustomerName(e.target.value)} /> <input type="text" placeholder="Password" value={customerPassword} onChange={(e) => setCustomerPassword(e.target.value)} /> <button onClick={submit}>Submit</button> </div> ) : ( <div className="App__Updateform"> <input type="text" placeholder="Name" value={updatedCustomerName} onChange={(e) => setUpdatedCustomerName(e.target.value)} /> <input type="text" placeholder="Password" value={updatedCustomerPassword} onChange={(e) => setUpdatedCustomerPassword(e.target.value)} /> <button onClick={updateData}>Update</button> </div> )} <div className="App__DataDisplay"> <table> <tr> <th>NAME</th> <th>PASSWORD</th> <th>Update</th> <th>Delete</th> </tr> {customersData?.map(({ id, data }) => ( <tr key={id}> <td>{data.name}</td> <td>{data.password}</td> <td> <button onClick={() => { setDataIdToBeUpdated(id); setUpdatedCustomerPassword(data.password); setUpdatedCustomerName(data.name); }} > Update </button> </td> <td> <button onClick={() => { deleteData(id); }} > Delete </button> </td> </tr> ))} </table> </div> </div> );} export default App; Step to Run Application: Run the application using the following command from the root directory of the project: npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output. After deleting the data you can check in your firebase dashboard if data get deleted or not. Firebase React-Questions ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ReactJS useNavigate() Hook How to set background images in ReactJS ? Axios in React: A Guide for Beginners How to create a table in ReactJS ? How to navigate on path by button click in react router ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26071, "s": 26043, "text": "\n01 Aug, 2021" }, { "code": null, "e": 27419, "s": 26071, "text": "Firebase is a Google Product that helps us build, manage, and grow our app easily. In this article, we will see how you can use firebase firestore as a backend and use G-auth provided by firebase in our demo react project. When you design apps like mobile apps like iOS or Android apps or web apps, the database is kind of a big problem and not because it’s hard to design of course it’s a little bit tricky to design as well as sometimes it consumes a lot of bandwidth trafficking between your database and your applications front end is kind of a big issue on top of that host page is again a problem, imagine if your app is having photo sharing things and you want to access all the photos there so it’s not easy to maintain all of these things now on top of that managing your own authentication system is also tricky because everybody needs authentication from Facebook maybe Twitter maybe google or even a simple login system is not easy to design from scratch. Now here comes the firebase, firebase gives you a complete solution about how things can be taken down. Now it’s a very good complete back-end solution that you can use. Now with the firebase, you can do all sorts of authentication most common ones are username, email, and password but there are plenty of different ways you can log in, below is a snapshot of all possible ways." }, { "code": null, "e": 27573, "s": 27419, "text": "Also firebase solves a very good problem of database it gives you a real-time database and in this article, we will see how to use firebase for database." }, { "code": null, "e": 27625, "s": 27575, "text": "Creating React Application And Installing Module:" }, { "code": null, "e": 27689, "s": 27625, "text": "Step 1: Create a React application using the following command:" }, { "code": null, "e": 27721, "s": 27689, "text": "npx create-react-app foldername" }, { "code": null, "e": 27821, "s": 27721, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:" }, { "code": null, "e": 27835, "s": 27821, "text": "cd foldername" }, { "code": null, "e": 27940, "s": 27835, "text": "Step 3: After creating the ReactJS application, Install the required module using the following command:" }, { "code": null, "e": 27955, "s": 27940, "text": "npm i firebase" }, { "code": null, "e": 28007, "s": 27955, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 28025, "s": 28007, "text": "Project Structure" }, { "code": null, "e": 28138, "s": 28025, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 28148, "s": 28138, "text": "npm start" }, { "code": null, "e": 28237, "s": 28150, "text": "Let’s first create two input fields namely Name and Password and with a Submit Button." }, { "code": null, "e": 28244, "s": 28237, "text": "App.js" }, { "code": "import React, { useState } from \"react\";import \"./App.css\"; function App() { const [customerName, setCustomerName] = useState(\"\"); const [customerPassword, setCustomerPassword] = useState(\"\"); return ( <div className=\"App\"> <div className=\"App__form\"> <input type=\"text\" placeholder=\"Name\" value={customerName} onChange={(e) => setCustomerName(e.target.value)} /> <input type=\"text\" placeholder=\"Password\" value={customerPassword} onChange={(e) => setCustomerPassword(e.target.value)} /> <button>Submit</button> </div> </div> );} export default App;", "e": 28925, "s": 28244, "text": null }, { "code": null, "e": 28933, "s": 28925, "text": "App.css" }, { "code": ".App { text-align: center; height: 100vh; display: grid; place-items: center;} .App__form { display: flex; flex-direction: column;} input { padding: 7px 11px; border-radius: 3px; border: none; border-bottom: 1px solid gray; margin: 20px; outline: none;} button { display: inline-block; margin-right: auto; margin-left: auto; padding: 7px 12px; border: none; border-radius: 4px;}", "e": 29333, "s": 28933, "text": null }, { "code": null, "e": 29410, "s": 29333, "text": "Now we will create the firebase project and create the firebase config file." }, { "code": null, "e": 29446, "s": 29410, "text": "Steps to create a firebase project:" }, { "code": null, "e": 29518, "s": 29446, "text": "Step 1: Login in the firebase dashboard and Click on Add Project Card." }, { "code": null, "e": 29569, "s": 29518, "text": "Step 2: Enter your project name click on continue." }, { "code": null, "e": 29672, "s": 29569, "text": "Step 3: In Configure Google Analytics select Default Account for Firebase and click on Create Project." }, { "code": null, "e": 29724, "s": 29674, "text": "Step 4: Wait for firebase to create your project." }, { "code": null, "e": 29789, "s": 29724, "text": "Step 5: Once the project is created go to the web icon as shown." }, { "code": null, "e": 29925, "s": 29789, "text": "Step 6: Give the app nick name and select the firebase hosting checkbox if you want to host your app using firebase, register your app." }, { "code": null, "e": 30032, "s": 29925, "text": "Step 7: Just install Firebase CLI if not installed yet using command given below on your VScode’s terminal" }, { "code": null, "e": 30062, "s": 30032, "text": "npm install -g firebase-tools" }, { "code": null, "e": 30192, "s": 30062, "text": "Step 8: Once done, just login into your firebase using the command given below using your command line or the terminal in VSCode." }, { "code": null, "e": 30207, "s": 30192, "text": "firebase login" }, { "code": null, "e": 30245, "s": 30207, "text": "Step 9: Click on Continue to Console." }, { "code": null, "e": 30519, "s": 30245, "text": "Step 10: Next go to your app click on the settings icon and at the bottom select the config option copy the config data. Go to your local project and create a file named firebase.js in the src folder and paste the config data along with few more lines in it as shown below." }, { "code": null, "e": 30531, "s": 30519, "text": "firebase.js" }, { "code": "import firebase from \"firebase\"; const firebaseConfig = { apiKey: \"AIzaSyATKyTSJVN7-Zx60WQ66kkHo3nBhuMhYDs\", authDomain: \"meteor-3fd94.firebaseapp.com\", projectId: \"meteor-3fd94\", storageBucket: \"meteor-3fd94.appspot.com\", messagingSenderId: \"391620415322\", appId: \"1:391620415322:web:6848292646d9e91e6e6d63\", measurementId: \"G-69J20TCH7X\",}; const firebaseApp = firebase.initializeApp(firebaseConfig);const db = firebase.firestore(); export default db;", "e": 30995, "s": 30531, "text": null }, { "code": null, "e": 31084, "s": 30995, "text": "Now we have the config file ready and we just need to add code for the CRUD operations :" }, { "code": null, "e": 31583, "s": 31084, "text": "1. Create collection: To create a collection we simply use the db object we created in the firebase.js above. We simply import it in our file and use the collection method to locate the collection in which our data is to be stored after creation. In case your collection is nested in other collection you’ll have to write it like, db.collection(<parent-collection>).doc(<doc-id>).collection(<child-collection>) and so on. Now once we are in our collection we just simply add our data as an object." }, { "code": null, "e": 31590, "s": 31583, "text": "App.js" }, { "code": "import React, { useState } from \"react\";import \"./App.css\";import db from \"./firebase\"; function App() { const [customerName, setCustomerName] = useState(\"\"); const [customerPassword, setCustomerPassword] = useState(\"\"); const submit = (e) => { e.preventDefault(); db.collection(\"customersData\").add({ name: customerName, password: customerPassword, }); setCustomerName(\"\"); setCustomerPassword(\"\"); }; return ( <div className=\"App\"> <div className=\"App__form\"> <input type=\"text\" placeholder=\"Name\" value={customerName} onChange={(e) => setCustomerName(e.target.value)} /> <input type=\"text\" placeholder=\"Password\" value={customerPassword} onChange={(e) => setCustomerPassword(e.target.value)} /> <button onClick={submit}>Submit</button> </div> </div> );} export default App;", "e": 32529, "s": 31590, "text": null }, { "code": null, "e": 32565, "s": 32529, "text": "Now we will test if our code works." }, { "code": null, "e": 32767, "s": 32565, "text": "Once we see this page then we are all set. Just go to the localhost and enter the details and press submit and then again open Firestore Database in Firebase and you’ll see something like shown below :" }, { "code": null, "e": 32805, "s": 32767, "text": "So we can see our data as shown above" }, { "code": null, "e": 33190, "s": 32805, "text": "2. Read Operation: Now to read data, initial process is same i.e., importing db object. No we go to the collection where our data is stored that we want to read and then we use the onSnapshot method, which as the name suggests simply takes the snapshot every time any changes happen in the database. This function is responsible for the realtime feel that we get when we use firebase." }, { "code": null, "e": 33197, "s": 33190, "text": "App.js" }, { "code": "import React, { useState, useEffect } from \"react\";import \"./App.css\";import db from \"./firebase\"; function App() { const [customerName, setCustomerName] = useState(\"\"); const [customerPassword, setCustomerPassword] = useState(\"\"); const [customersData, setCustomersData] = useState([]); useEffect(() => { db.collection(\"customersData\").onSnapshot((snapshot) => { setCustomersData( snapshot.docs.map((doc) => ({ id: doc.id, data: doc.data(), })) ); }); console.log({ customersData }); }, []); const submit = (e) => { e.preventDefault(); db.collection(\"customersData\").add({ name: customerName, password: customerPassword, }); setCustomerName(\"\"); setCustomerPassword(\"\"); }; return ( <div className=\"App\"> <div className=\"App__form\"> <input type=\"text\" placeholder=\"Name\" value={customerName} onChange={(e) => setCustomerName(e.target.value)} /> <input type=\"text\" placeholder=\"Password\" value={customerPassword} onChange={(e) => setCustomerPassword(e.target.value)} /> <button onClick={submit}>Submit</button> </div> <div className=\"App__DataDisplay\"> <table> <tr> <th>NAME</th> <th>PASSWORD</th> </tr> {customersData?.map(({ id, data }) => ( <tr key={id}> <td>{data.name}</td> <td>{data.password}</td> </tr> ))} </table> </div> </div> );} export default App;", "e": 34808, "s": 33197, "text": null }, { "code": null, "e": 34921, "s": 34808, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 34931, "s": 34921, "text": "npm start" }, { "code": null, "e": 35030, "s": 34931, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 35467, "s": 35030, "text": "3. Update Operation: Let’s first a button that should update and the fields that should appear.Now after we have imported the db object from firebase.js we simply go to the collection where our data is stored that is to be updated and then we specify the doc we need to update as one collection has many documents so we have to specify that what doc is to be updated and then we simply use the update method and pass the updated object." }, { "code": null, "e": 35474, "s": 35467, "text": "App.js" }, { "code": "import React, { useState, useEffect } from \"react\";import \"./App.css\";import db from \"./firebase\"; function App() { const [customerName, setCustomerName] = useState(\"\"); const [customerPassword, setCustomerPassword] = useState(\"\"); const [customersData, setCustomersData] = useState([]); const [updatedCustomerName, setUpdatedCustomerName] = useState(\"\"); const [updatedCustomerPassword, setUpdatedCustomerPassword] = useState(\"\"); const [dataIdToBeUpdated, setDataIdToBeUpdated] = useState(\"\"); useEffect(() => { db.collection(\"customersData\").onSnapshot((snapshot) => { setCustomersData( snapshot.docs.map((doc) => ({ id: doc.id, data: doc.data(), })) ); }); }, []); const submit = (e) => { e.preventDefault(); db.collection(\"customersData\").add({ name: customerName, password: customerPassword, }); setCustomerName(\"\"); setCustomerPassword(\"\"); }; const updateData = (e) => { e.preventDefault(); db.collection(\"customersData\").doc(dataIdToBeUpdated).update({ name: updatedCustomerName, password: updatedCustomerPassword, }); setUpdatedCustomerPassword(\"\"); setUpdatedCustomerName(\"\"); setDataIdToBeUpdated(\"\"); }; return ( <div className=\"App\"> {!dataIdToBeUpdated ? ( <div className=\"App__form\"> <input type=\"text\" placeholder=\"Name\" value={customerName} onChange={(e) => setCustomerName(e.target.value)} /> <input type=\"text\" placeholder=\"Password\" value={customerPassword} onChange={(e) => setCustomerPassword(e.target.value)} /> <button onClick={submit}>Submit</button> </div> ) : ( <div className=\"App__Updateform\"> <input type=\"text\" placeholder=\"Name\" value={updatedCustomerName} onChange={(e) => setUpdatedCustomerName(e.target.value)} /> <input type=\"text\" placeholder=\"Password\" value={updatedCustomerPassword} onChange={(e) => setUpdatedCustomerPassword(e.target.value)} /> <button onClick={updateData}>Update</button> </div> )} <div className=\"App__DataDisplay\"> <table> <tr> <th>NAME</th> <th>PASSWORD</th> <th>Update</th> </tr> {customersData?.map(({ id, data }) => ( <tr key={id}> <td>{data.name}</td> <td>{data.password}</td> <td> <button onClick={() => { setDataIdToBeUpdated(id); setUpdatedCustomerPassword(data.password); setUpdatedCustomerName(data.name); }} > Update </button> </td> </tr> ))} </table> </div> </div> );} export default App;", "e": 38506, "s": 35474, "text": null }, { "code": null, "e": 38619, "s": 38506, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 38629, "s": 38619, "text": "npm start" }, { "code": null, "e": 38821, "s": 38629, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output. After updating the data you can check in your firebase dashboard if data get updated or not." }, { "code": null, "e": 39166, "s": 38821, "text": "4. Delete Operation: Starting with the same thing, we import db object in our file then we simply go to the collection where our data is stored that is to be deleted and then we specify the doc we need to delete as one collection has many documents so we have to specify that what doc is to be deleted and then we simply call the delete method." }, { "code": null, "e": 39173, "s": 39166, "text": "App.js" }, { "code": "import React, { useState, useEffect } from \"react\";import \"./App.css\";import db from \"./firebase\"; function App() { const [customerName, setCustomerName] = useState(\"\"); const [customerPassword, setCustomerPassword] = useState(\"\"); const [customersData, setCustomersData] = useState([]); const [updatedCustomerName, setUpdatedCustomerName] = useState(\"\"); const [updatedCustomerPassword, setUpdatedCustomerPassword] = useState(\"\"); const [dataIdToBeUpdated, setDataIdToBeUpdated] = useState(\"\"); useEffect(() => { db.collection(\"customersData\").onSnapshot((snapshot) => { setCustomersData( snapshot.docs.map((doc) => ({ id: doc.id, data: doc.data(), })) ); }); }, []); const submit = (e) => { e.preventDefault(); db.collection(\"customersData\").add({ name: customerName, password: customerPassword, }); setCustomerName(\"\"); setCustomerPassword(\"\"); }; const updateData = (e) => { e.preventDefault(); db.collection(\"customersData\").doc(dataIdToBeUpdated).update({ name: updatedCustomerName, password: updatedCustomerPassword, }); setUpdatedCustomerPassword(\"\"); setUpdatedCustomerName(\"\"); setDataIdToBeUpdated(\"\"); }; const deleteData = (id) => { db.collection(\"customersData\").doc(id).delete(); }; return ( <div className=\"App\"> {!dataIdToBeUpdated ? ( <div className=\"App__form\"> <input type=\"text\" placeholder=\"Name\" value={customerName} onChange={(e) => setCustomerName(e.target.value)} /> <input type=\"text\" placeholder=\"Password\" value={customerPassword} onChange={(e) => setCustomerPassword(e.target.value)} /> <button onClick={submit}>Submit</button> </div> ) : ( <div className=\"App__Updateform\"> <input type=\"text\" placeholder=\"Name\" value={updatedCustomerName} onChange={(e) => setUpdatedCustomerName(e.target.value)} /> <input type=\"text\" placeholder=\"Password\" value={updatedCustomerPassword} onChange={(e) => setUpdatedCustomerPassword(e.target.value)} /> <button onClick={updateData}>Update</button> </div> )} <div className=\"App__DataDisplay\"> <table> <tr> <th>NAME</th> <th>PASSWORD</th> <th>Update</th> <th>Delete</th> </tr> {customersData?.map(({ id, data }) => ( <tr key={id}> <td>{data.name}</td> <td>{data.password}</td> <td> <button onClick={() => { setDataIdToBeUpdated(id); setUpdatedCustomerPassword(data.password); setUpdatedCustomerName(data.name); }} > Update </button> </td> <td> <button onClick={() => { deleteData(id); }} > Delete </button> </td> </tr> ))} </table> </div> </div> );} export default App;", "e": 42535, "s": 39173, "text": null }, { "code": null, "e": 42648, "s": 42535, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 42658, "s": 42648, "text": "npm start" }, { "code": null, "e": 42850, "s": 42658, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output. After deleting the data you can check in your firebase dashboard if data get deleted or not." }, { "code": null, "e": 42859, "s": 42850, "text": "Firebase" }, { "code": null, "e": 42875, "s": 42859, "text": "React-Questions" }, { "code": null, "e": 42883, "s": 42875, "text": "ReactJS" }, { "code": null, "e": 42900, "s": 42883, "text": "Web Technologies" }, { "code": null, "e": 42998, "s": 42900, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 43025, "s": 42998, "text": "ReactJS useNavigate() Hook" }, { "code": null, "e": 43067, "s": 43025, "text": "How to set background images in ReactJS ?" }, { "code": null, "e": 43105, "s": 43067, "text": "Axios in React: A Guide for Beginners" }, { "code": null, "e": 43140, "s": 43105, "text": "How to create a table in ReactJS ?" }, { "code": null, "e": 43198, "s": 43140, "text": "How to navigate on path by button click in react router ?" }, { "code": null, "e": 43238, "s": 43198, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 43271, "s": 43238, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 43316, "s": 43271, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 43378, "s": 43316, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
How to dynamically create '@-Keyframe' CSS animations? - GeeksforGeeks
31 Aug, 2020 In order to dynamically allocate keyframe animations to our HTML web-page, we are going to use the CSS stylesheets insertRule() method. We are going to take keyframes animation from a text area and then we will apply those rules to our web-page. insertRule() method: This method is use to insert some new CSS rule into the current CSS style sheet(bound with some restriction). Syntax: stylesheet.insertRule(rule [, index]) Parameter: The method accepts two parameters as mentioned above and described below: Rule: A DOMstring which is essentially the CSS rule to be inserted. Rule: A DOMstring which is essentially the CSS rule to be inserted. index(optional): The index at which the rule is inserted in CSSStyleSheet.cssRules index(optional): The index at which the rule is inserted in CSSStyleSheet.cssRules Example: HTML: First, let’s make the layout structure of our page using HTML and CSS.htmlhtml<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"></head><body> <h2 style="color: green;">GeeksforGeeks</h2> <div id="element"></div> <form id="input"> <textarea id="text" rows="10" cols="40"></textarea><br> <button type="submit">ADD ANIMATION</button> </form> <style> #element{ width: 200px; height: 200px; background-color: green; margin-bottom: 5px; } </style></body> html <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"></head><body> <h2 style="color: green;">GeeksforGeeks</h2> <div id="element"></div> <form id="input"> <textarea id="text" rows="10" cols="40"></textarea><br> <button type="submit">ADD ANIMATION</button> </form> <style> #element{ width: 200px; height: 200px; background-color: green; margin-bottom: 5px; } </style></body> Output: The structure will look like. JavaScript: Now, We are going to input a keyframe animation in the text area above and add it to the element that we have created.javascriptjavascript// Javascript code to add keyframeslet styleSheet = null;dynamicAnimation = (name,styles) => {// Creating a style element// To add the keyframesif (!styleSheet){ styleSheet = document.createElement('style'); styleSheet.type = 'text/css'; document.head.appendChild(styleSheet);}// Adding The KeyframesstyleSheet.sheet.insertRule(`@keyframes ${name} {${styles}}`,styleSheet.length);} const form = document.getElementById("input");const text = document.getElementById("text");form.addEventListener('submit', (e)=>{ e.preventDefault() // Adding an animation // NewAnimation, with the // Keyframes to the Stylesheet dynamicAnimation('newAnimation', text.value); // Timing and duration can be altered // As per user requirements document.getElementById("element").style.animation = 'newAnimation 3s infinite';}); javascript // Javascript code to add keyframeslet styleSheet = null;dynamicAnimation = (name,styles) => {// Creating a style element// To add the keyframesif (!styleSheet){ styleSheet = document.createElement('style'); styleSheet.type = 'text/css'; document.head.appendChild(styleSheet);}// Adding The KeyframesstyleSheet.sheet.insertRule(`@keyframes ${name} {${styles}}`,styleSheet.length);} const form = document.getElementById("input");const text = document.getElementById("text");form.addEventListener('submit', (e)=>{ e.preventDefault() // Adding an animation // NewAnimation, with the // Keyframes to the Stylesheet dynamicAnimation('newAnimation', text.value); // Timing and duration can be altered // As per user requirements document.getElementById("element").style.animation = 'newAnimation 3s infinite';}); Implementation Code: html <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"></head><body> <h2 style="color: green;">GeeksforGeeks</h2> <div id="element"></div> <form id="input"> <textarea id="text" rows="10" cols="40"></textarea><br> <button type="submit">ADD ANIMATION</button> </form> <style> #element{ width: 200px; height: 200px; background-color: green; margin-bottom: 5px; } </style> <script> let styleSheet = null; dynamicAnimation = (name,styles) => { if (!styleSheet){ styleSheet = document.createElement('style'); styleSheet.type = 'text/css'; document.head.appendChild(styleSheet); } styleSheet.sheet.insertRule(`@keyframes ${name} {${styles}}`, styleSheet.length ); } const form = document.getElementById("input"); const text = document.getElementById("text"); form.addEventListener('submit', (e)=>{ e.preventDefault(); console.log("submitted"); console.log(text.value); dynamicAnimation('newAnimation', text.value); document.getElementById("element").style.animation = 'newAnimation 3s infinite'; }); </script></body></html> CSS:Now, We are going to add the following Keyframe Rule Set to the text box element. CSS 25%{ transform : translateX(25%); border-radius : 25%; }50%{ transform : translateX(50%); border-radius : 50%; }75%{ transform : translateX(25%); border-radius : 25%;}100%{ transform : translateX(0%); border-radius : 0%;} Output: Before Submitting Keyframes: Before Submitting Keyframes: After Submitting Keyframes: After Submitting Keyframes: Picked CSS Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to apply style to parent if it has child with CSS? Types of CSS (Cascading Style Sheet) How to position a div at the bottom of its container using CSS? Design a web page using HTML and CSS How to Upload Image into Database and Display it using PHP ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 25723, "s": 25695, "text": "\n31 Aug, 2020" }, { "code": null, "e": 25969, "s": 25723, "text": "In order to dynamically allocate keyframe animations to our HTML web-page, we are going to use the CSS stylesheets insertRule() method. We are going to take keyframes animation from a text area and then we will apply those rules to our web-page." }, { "code": null, "e": 26100, "s": 25969, "text": "insertRule() method: This method is use to insert some new CSS rule into the current CSS style sheet(bound with some restriction)." }, { "code": null, "e": 26108, "s": 26100, "text": "Syntax:" }, { "code": null, "e": 26146, "s": 26108, "text": "stylesheet.insertRule(rule [, index])" }, { "code": null, "e": 26231, "s": 26146, "text": "Parameter: The method accepts two parameters as mentioned above and described below:" }, { "code": null, "e": 26299, "s": 26231, "text": "Rule: A DOMstring which is essentially the CSS rule to be inserted." }, { "code": null, "e": 26367, "s": 26299, "text": "Rule: A DOMstring which is essentially the CSS rule to be inserted." }, { "code": null, "e": 26450, "s": 26367, "text": "index(optional): The index at which the rule is inserted in CSSStyleSheet.cssRules" }, { "code": null, "e": 26533, "s": 26450, "text": "index(optional): The index at which the rule is inserted in CSSStyleSheet.cssRules" }, { "code": null, "e": 26542, "s": 26533, "text": "Example:" }, { "code": null, "e": 27143, "s": 26542, "text": "HTML: First, let’s make the layout structure of our page using HTML and CSS.htmlhtml<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"></head><body> <h2 style=\"color: green;\">GeeksforGeeks</h2> <div id=\"element\"></div> <form id=\"input\"> <textarea id=\"text\" rows=\"10\" cols=\"40\"></textarea><br> <button type=\"submit\">ADD ANIMATION</button> </form> <style> #element{ width: 200px; height: 200px; background-color: green; margin-bottom: 5px; } </style></body>" }, { "code": null, "e": 27148, "s": 27143, "text": "html" }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"></head><body> <h2 style=\"color: green;\">GeeksforGeeks</h2> <div id=\"element\"></div> <form id=\"input\"> <textarea id=\"text\" rows=\"10\" cols=\"40\"></textarea><br> <button type=\"submit\">ADD ANIMATION</button> </form> <style> #element{ width: 200px; height: 200px; background-color: green; margin-bottom: 5px; } </style></body>", "e": 27665, "s": 27148, "text": null }, { "code": null, "e": 27703, "s": 27665, "text": "Output: The structure will look like." }, { "code": null, "e": 28676, "s": 27703, "text": "JavaScript: Now, We are going to input a keyframe animation in the text area above and add it to the element that we have created.javascriptjavascript// Javascript code to add keyframeslet styleSheet = null;dynamicAnimation = (name,styles) => {// Creating a style element// To add the keyframesif (!styleSheet){ styleSheet = document.createElement('style'); styleSheet.type = 'text/css'; document.head.appendChild(styleSheet);}// Adding The KeyframesstyleSheet.sheet.insertRule(`@keyframes ${name} {${styles}}`,styleSheet.length);} const form = document.getElementById(\"input\");const text = document.getElementById(\"text\");form.addEventListener('submit', (e)=>{ e.preventDefault() // Adding an animation // NewAnimation, with the // Keyframes to the Stylesheet dynamicAnimation('newAnimation', text.value); // Timing and duration can be altered // As per user requirements document.getElementById(\"element\").style.animation = 'newAnimation 3s infinite';});" }, { "code": null, "e": 28687, "s": 28676, "text": "javascript" }, { "code": "// Javascript code to add keyframeslet styleSheet = null;dynamicAnimation = (name,styles) => {// Creating a style element// To add the keyframesif (!styleSheet){ styleSheet = document.createElement('style'); styleSheet.type = 'text/css'; document.head.appendChild(styleSheet);}// Adding The KeyframesstyleSheet.sheet.insertRule(`@keyframes ${name} {${styles}}`,styleSheet.length);} const form = document.getElementById(\"input\");const text = document.getElementById(\"text\");form.addEventListener('submit', (e)=>{ e.preventDefault() // Adding an animation // NewAnimation, with the // Keyframes to the Stylesheet dynamicAnimation('newAnimation', text.value); // Timing and duration can be altered // As per user requirements document.getElementById(\"element\").style.animation = 'newAnimation 3s infinite';});", "e": 29510, "s": 28687, "text": null }, { "code": null, "e": 29531, "s": 29510, "text": "Implementation Code:" }, { "code": null, "e": 29536, "s": 29531, "text": "html" }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"></head><body> <h2 style=\"color: green;\">GeeksforGeeks</h2> <div id=\"element\"></div> <form id=\"input\"> <textarea id=\"text\" rows=\"10\" cols=\"40\"></textarea><br> <button type=\"submit\">ADD ANIMATION</button> </form> <style> #element{ width: 200px; height: 200px; background-color: green; margin-bottom: 5px; } </style> <script> let styleSheet = null; dynamicAnimation = (name,styles) => { if (!styleSheet){ styleSheet = document.createElement('style'); styleSheet.type = 'text/css'; document.head.appendChild(styleSheet); } styleSheet.sheet.insertRule(`@keyframes ${name} {${styles}}`, styleSheet.length ); } const form = document.getElementById(\"input\"); const text = document.getElementById(\"text\"); form.addEventListener('submit', (e)=>{ e.preventDefault(); console.log(\"submitted\"); console.log(text.value); dynamicAnimation('newAnimation', text.value); document.getElementById(\"element\").style.animation = 'newAnimation 3s infinite'; }); </script></body></html>", "e": 30801, "s": 29536, "text": null }, { "code": null, "e": 30887, "s": 30801, "text": "CSS:Now, We are going to add the following Keyframe Rule Set to the text box element." }, { "code": null, "e": 30891, "s": 30887, "text": "CSS" }, { "code": "25%{ transform : translateX(25%); border-radius : 25%; }50%{ transform : translateX(50%); border-radius : 50%; }75%{ transform : translateX(25%); border-radius : 25%;}100%{ transform : translateX(0%); border-radius : 0%;}", "e": 31141, "s": 30891, "text": null }, { "code": null, "e": 31149, "s": 31141, "text": "Output:" }, { "code": null, "e": 31178, "s": 31149, "text": "Before Submitting Keyframes:" }, { "code": null, "e": 31207, "s": 31178, "text": "Before Submitting Keyframes:" }, { "code": null, "e": 31235, "s": 31207, "text": "After Submitting Keyframes:" }, { "code": null, "e": 31263, "s": 31235, "text": "After Submitting Keyframes:" }, { "code": null, "e": 31270, "s": 31263, "text": "Picked" }, { "code": null, "e": 31274, "s": 31270, "text": "CSS" }, { "code": null, "e": 31291, "s": 31274, "text": "Web Technologies" }, { "code": null, "e": 31318, "s": 31291, "text": "Web technologies Questions" }, { "code": null, "e": 31416, "s": 31318, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31471, "s": 31416, "text": "How to apply style to parent if it has child with CSS?" }, { "code": null, "e": 31508, "s": 31471, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 31572, "s": 31508, "text": "How to position a div at the bottom of its container using CSS?" }, { "code": null, "e": 31609, "s": 31572, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 31670, "s": 31609, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 31710, "s": 31670, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 31743, "s": 31710, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 31788, "s": 31743, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 31831, "s": 31788, "text": "How to fetch data from an API in ReactJS ?" } ]
Python program to print an array of bytes representing an integer - GeeksforGeeks
24 Jan, 2021 Given an integer N, the task is to write a Python program to represent the bytes of this number as an array. A byte is a group of 8 bits. Any integer can be represented in the form of bytes and bits. We generally use hexadecimal codes to represent a byte. A single hexadecimal character can represent 4 bits so a pair of hexadecimal characters are used to represent a byte. Example: Input: N = 543 Output: [‘0x2’, ‘0x1f’] Explanation: 543 can be represented as 1000011111 in binary which can be grouped as (10)(00011111), each group representing a byte. In hexadecimal form, this number will be (0x02)(0x1F). Input: N = 17292567 Output: [‘0x1’, ‘0x7’, ‘0xdd’, ‘0x17’] Explanation: 17292567 can be represented as 1000001111101110100010111 in binary which can be grouped as (1)(00000111)(11011101)(00010111), each group representing a byte. In hexadecimal form, this number will be (0x1), (0x7), (0xdd), (0x17). Method 1 (Manual conversion): Just like we convert decimal numbers to binary numbers, we can convert it into a base-256 number which will give us 8-bit numbers that represent bytes for the given number. Below is the code to implement the above-discussed method: Python3 n = 17292567 # Initialize the empty arrayarray = [] # Get the hexadecimal formwhile(n): r = n % 256 n = n//256 array.append(hex(r)) # Reverse the array to get the MSB to leftarray.reverse()print(array) ['0x1', '0x7', '0xdd', '0x17'] Method 2 (Using to_bytes() method): We can also use the to_bytes(length,byteorder) method to convert the number into a hexadecimal string. But the problem with this function is that while printing, the hex codes can convert to their corresponding characters in ASCII coding scheme. To overcome this, we can use hex() method over this method. It takes two arguments, ‘length‘ is the size of the array and ‘byteorder’ is the ordering of bytes where “big” means MSB will be on left and “little” means MSB will be on right. Below is the code to implement the above-discussed method: Python3 import math n = 543 # Calculate the length of arraysize = int(math.log(n, 256))+1 # Use the method to_bytes() with "big" # or "little" property We need to apply# hex() method to avoid the conversion # into ASCII lettershexForm = n.to_bytes(size, "big").hex() # Append 8 bits together ie pair of 4 bits to get a bytearray = []for i in range(0, len(hexForm), 2): array.append('0x'+hexForm[i]+hexForm[i+1])print(array) ['0x02', '0x1f'] Method 3 (Using string formatting commands): In Python, there is a string command “%x” that can convert the given integer into hexadecimal format. We can use this to get the desired output. Below is the code to implement the above-discussed method: Python3 n = 8745 # Get string representation of hex codehexcode = "%x" % n # Pad an extra 0 is length is oddif len(hexcode) & 1: hexcode = "0"+hexcode array = []for i in range(0, len(hexcode), 2): array.append('0x'+hexcode[i]+hexcode[i+1])print(array) ['0x22', '0x29'] binary-representation Picked Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary How to print without newline in Python?
[ { "code": null, "e": 25537, "s": 25509, "text": "\n24 Jan, 2021" }, { "code": null, "e": 25647, "s": 25537, "text": "Given an integer N, the task is to write a Python program to represent the bytes of this number as an array. " }, { "code": null, "e": 25913, "s": 25647, "text": "A byte is a group of 8 bits. Any integer can be represented in the form of bytes and bits. We generally use hexadecimal codes to represent a byte. A single hexadecimal character can represent 4 bits so a pair of hexadecimal characters are used to represent a byte. " }, { "code": null, "e": 25922, "s": 25913, "text": "Example:" }, { "code": null, "e": 25937, "s": 25922, "text": "Input: N = 543" }, { "code": null, "e": 25961, "s": 25937, "text": "Output: [‘0x2’, ‘0x1f’]" }, { "code": null, "e": 26148, "s": 25961, "text": "Explanation: 543 can be represented as 1000011111 in binary which can be grouped as (10)(00011111), each group representing a byte. In hexadecimal form, this number will be (0x02)(0x1F)." }, { "code": null, "e": 26168, "s": 26148, "text": "Input: N = 17292567" }, { "code": null, "e": 26207, "s": 26168, "text": "Output: [‘0x1’, ‘0x7’, ‘0xdd’, ‘0x17’]" }, { "code": null, "e": 26449, "s": 26207, "text": "Explanation: 17292567 can be represented as 1000001111101110100010111 in binary which can be grouped as (1)(00000111)(11011101)(00010111), each group representing a byte. In hexadecimal form, this number will be (0x1), (0x7), (0xdd), (0x17)." }, { "code": null, "e": 26479, "s": 26449, "text": "Method 1 (Manual conversion):" }, { "code": null, "e": 26653, "s": 26479, "text": "Just like we convert decimal numbers to binary numbers, we can convert it into a base-256 number which will give us 8-bit numbers that represent bytes for the given number. " }, { "code": null, "e": 26712, "s": 26653, "text": "Below is the code to implement the above-discussed method:" }, { "code": null, "e": 26720, "s": 26712, "text": "Python3" }, { "code": "n = 17292567 # Initialize the empty arrayarray = [] # Get the hexadecimal formwhile(n): r = n % 256 n = n//256 array.append(hex(r)) # Reverse the array to get the MSB to leftarray.reverse()print(array)", "e": 26938, "s": 26720, "text": null }, { "code": null, "e": 26969, "s": 26938, "text": "['0x1', '0x7', '0xdd', '0x17']" }, { "code": null, "e": 27005, "s": 26969, "text": "Method 2 (Using to_bytes() method):" }, { "code": null, "e": 27489, "s": 27005, "text": "We can also use the to_bytes(length,byteorder) method to convert the number into a hexadecimal string. But the problem with this function is that while printing, the hex codes can convert to their corresponding characters in ASCII coding scheme. To overcome this, we can use hex() method over this method. It takes two arguments, ‘length‘ is the size of the array and ‘byteorder’ is the ordering of bytes where “big” means MSB will be on left and “little” means MSB will be on right." }, { "code": null, "e": 27548, "s": 27489, "text": "Below is the code to implement the above-discussed method:" }, { "code": null, "e": 27556, "s": 27548, "text": "Python3" }, { "code": "import math n = 543 # Calculate the length of arraysize = int(math.log(n, 256))+1 # Use the method to_bytes() with \"big\" # or \"little\" property We need to apply# hex() method to avoid the conversion # into ASCII lettershexForm = n.to_bytes(size, \"big\").hex() # Append 8 bits together ie pair of 4 bits to get a bytearray = []for i in range(0, len(hexForm), 2): array.append('0x'+hexForm[i]+hexForm[i+1])print(array)", "e": 27981, "s": 27556, "text": null }, { "code": null, "e": 27998, "s": 27981, "text": "['0x02', '0x1f']" }, { "code": null, "e": 28043, "s": 27998, "text": "Method 3 (Using string formatting commands):" }, { "code": null, "e": 28188, "s": 28043, "text": "In Python, there is a string command “%x” that can convert the given integer into hexadecimal format. We can use this to get the desired output." }, { "code": null, "e": 28247, "s": 28188, "text": "Below is the code to implement the above-discussed method:" }, { "code": null, "e": 28255, "s": 28247, "text": "Python3" }, { "code": "n = 8745 # Get string representation of hex codehexcode = \"%x\" % n # Pad an extra 0 is length is oddif len(hexcode) & 1: hexcode = \"0\"+hexcode array = []for i in range(0, len(hexcode), 2): array.append('0x'+hexcode[i]+hexcode[i+1])print(array)", "e": 28508, "s": 28255, "text": null }, { "code": null, "e": 28525, "s": 28508, "text": "['0x22', '0x29']" }, { "code": null, "e": 28547, "s": 28525, "text": "binary-representation" }, { "code": null, "e": 28554, "s": 28547, "text": "Picked" }, { "code": null, "e": 28561, "s": 28554, "text": "Python" }, { "code": null, "e": 28577, "s": 28561, "text": "Python Programs" }, { "code": null, "e": 28675, "s": 28577, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28707, "s": 28675, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28749, "s": 28707, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28791, "s": 28749, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28818, "s": 28791, "text": "Python Classes and Objects" }, { "code": null, "e": 28874, "s": 28818, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28896, "s": 28874, "text": "Defaultdict in Python" }, { "code": null, "e": 28935, "s": 28896, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 28981, "s": 28935, "text": "Python | Split string into list of characters" }, { "code": null, "e": 29019, "s": 28981, "text": "Python | Convert a list to dictionary" } ]
Create a Telegram Bot using Python - GeeksforGeeks
11 Oct, 2021 In this article, we are going to see how to create a telegram bot using Python. In recent times Telegram has become one of the most used messaging and content sharing platforms, it has no file sharing limit like Whatsapp and it comes with some preinstalled bots one can use in any channels (groups in case of whatsapp) to control the behavior or filter the spam messages sent by users. A Telegram Account: If you don’t have the Telegram app installed just download it from the play store. After downloading create an account using your mobile number just like WhatsApp. .python-telegram-bot module: Here we will need a module called python-telegram-bot, This library provides a pure Python interface for the Telegram Bot API. It’s compatible with Python versions 3.6.8+. In addition to the pure API implementation, this library features a number of high-level classes to make the development of bots easy and straightforward. These classes are contained in the “telegram.ext” submodule. For more information, you can check their official GitHub repo. We can install this module via pip and conda with the below command. # installing via pip pip install python-telegram-bot # installing via conda conda install -c conda-forge python-telegram-bot Step 1: After opening an account on Telegram, in the search bar at the top search for “BotFather” Step 2: Click on the ‘BotFather’ (first result) and type /newbot Step 3: Give a unique name to your bot. After naming it, Botfather will ask for its username. Then also give a unique name BUT remember the username of your bot must end with the bot, like my_bot, hellobot etc. Step 4: After giving a unique name and if it gets accepted you will get a message something like this – Here the token value will be different for you, we will use this token in our python code to make changes in our bot and make it just like we want, and add some commands in it. Python3 from telegram.ext.updater import Updaterfrom telegram.update import Updatefrom telegram.ext.callbackcontext import CallbackContextfrom telegram.ext.commandhandler import CommandHandlerfrom telegram.ext.messagehandler import MessageHandlerfrom telegram.ext.filters import Filters Brief usage of the functions we are importing: Updater: This will contain the API key we got from BotFather to specify in which bot we are adding functionalities to using our python code. Update: This will invoke every time a bot receives an update i.e. message or command and will send the user a message. CallbackContext: We will not use its functionality directly in our code but when we will be adding the dispatcher it is required (and it will work internally) CommandHandler: This Handler class is used to handle any command sent by the user to the bot, a command always starts with “/” i.e “/start”,”/help” etc. MessageHandler: This Handler class is used to handle any normal message sent by the user to the bot, FIlters: This will filter normal text, commands, images, etc from a sent message. Start function: It will display the first conversation, you may name it something else but the message inside it will be sent to the user whenever they press ‘start’ at the very beginning. Python3 updater = Updater("your_own_API_Token got from BotFather", use_context=True) def start(update: Update, context: CallbackContext): update.message.reply_text( "Enter the text you want to show to the user whenever they start the bot") Basically, in the start message, you should add something like “Hello Welcome to the Bot” etc. Help function: It is basically in this function you should add any kind of help the user might need, i.e. All the commands your bot understands, The information related to the bot, etc) Python3 def help(update: Update, context: CallbackContext): update.message.reply_text("Your Message") Adding some more functionalities to the Bot. Python3 def gmail_url(update: Update, context: CallbackContext): update.message.reply_text("gmail link here") def youtube_url(update: Update, context: CallbackContext): update.message.reply_text("youtube link") def linkedIn_url(update: Update, context: CallbackContext): update.message.reply_text("Your linkedin profile url") def geeks_url(update: Update, context: CallbackContext): update.message.reply_text("GeeksforGeeks url here") def unknown_text(update: Update, context: CallbackContext): update.message.reply_text( "Sorry I can't recognize you , you said '%s'" % update.message.text) def unknown(update: Update, context: CallbackContext): update.message.reply_text( "Sorry '%s' is not a valid command" % update.message.text) Here we have added 4 functions one to open Gmail, one for youtube, one for LinkedIn, and the last one for GeeksforGeeks. These are not MANDATORY functions, you can add any kind of functions and their reply_text as you want, these are just for demonstration. Here the unknown_text function will send the message written inside it whenever it gets some unknown messages and the unknown function will Filter out all the unknown commands sent by the user and reply to the message written inside it. Python3 updater.dispatcher.add_handler(CommandHandler('start', start))updater.dispatcher.add_handler(CommandHandler('youtube', youtube_url))updater.dispatcher.add_handler(CommandHandler('help', help))updater.dispatcher.add_handler(CommandHandler('linkedin', linkedIn_url))updater.dispatcher.add_handler(CommandHandler('gmail', gmail_url))updater.dispatcher.add_handler(CommandHandler('geeks', geeks_url))updater.dispatcher.add_handler(MessageHandler(Filters.text, unknown))updater.dispatcher.add_handler(MessageHandler( # Filters out unknown commands Filters.command, unknown)) # Filters out unknown messages.updater.dispatcher.add_handler(MessageHandler(Filters.text, unknown_text)) Here each line suggests that whenever a user writes a command i.e. the first parameter of the CommandHandler in reply the user gets the message written inside the function mentioned in the next parameter. Python3 updater.start_polling() Here whenever we start polling the bot will be active and it will look for any new message sent by any of the users and if it matches the command specified there it will reply accordingly. Below is the full implementation: Python3 from telegram.ext.updater import Updaterfrom telegram.update import Updatefrom telegram.ext.callbackcontext import CallbackContextfrom telegram.ext.commandhandler import CommandHandlerfrom telegram.ext.messagehandler import MessageHandlerfrom telegram.ext.filters import Filters updater = Updater("your_own_API_Token got from BotFather", use_context=True) def start(update: Update, context: CallbackContext): update.message.reply_text( "Hello sir, Welcome to the Bot.Please write\ /help to see the commands available.") def help(update: Update, context: CallbackContext): update.message.reply_text("""Available Commands :- /youtube - To get the youtube URL /linkedin - To get the LinkedIn profile URL /gmail - To get gmail URL /geeks - To get the GeeksforGeeks URL""") def gmail_url(update: Update, context: CallbackContext): update.message.reply_text( "Your gmail link here (I am not\ giving mine one for security reasons)") def youtube_url(update: Update, context: CallbackContext): update.message.reply_text("Youtube Link =>\ https://www.youtube.com/") def linkedIn_url(update: Update, context: CallbackContext): update.message.reply_text( "LinkedIn URL => \ https://www.linkedin.com/in/dwaipayan-bandyopadhyay-007a/") def geeks_url(update: Update, context: CallbackContext): update.message.reply_text( "GeeksforGeeks URL => https://www.geeksforgeeks.org/") def unknown(update: Update, context: CallbackContext): update.message.reply_text( "Sorry '%s' is not a valid command" % update.message.text) def unknown_text(update: Update, context: CallbackContext): update.message.reply_text( "Sorry I can't recognize you , you said '%s'" % update.message.text) updater.dispatcher.add_handler(CommandHandler('start', start))updater.dispatcher.add_handler(CommandHandler('youtube', youtube_url))updater.dispatcher.add_handler(CommandHandler('help', help))updater.dispatcher.add_handler(CommandHandler('linkedin', linkedIn_url))updater.dispatcher.add_handler(CommandHandler('gmail', gmail_url))updater.dispatcher.add_handler(CommandHandler('geeks', geeks_url))updater.dispatcher.add_handler(MessageHandler(Filters.text, unknown))updater.dispatcher.add_handler(MessageHandler( Filters.command, unknown)) # Filters out unknown commands # Filters out unknown messages.updater.dispatcher.add_handler(MessageHandler(Filters.text, unknown_text)) updater.start_polling() Output: Media error: Format(s) not supported or source(s) not found Python-projects 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? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | os.path.join() method Python | Get unique values from a list Create a directory in Python Defaultdict in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25581, "s": 25553, "text": "\n11 Oct, 2021" }, { "code": null, "e": 25661, "s": 25581, "text": "In this article, we are going to see how to create a telegram bot using Python." }, { "code": null, "e": 25967, "s": 25661, "text": "In recent times Telegram has become one of the most used messaging and content sharing platforms, it has no file sharing limit like Whatsapp and it comes with some preinstalled bots one can use in any channels (groups in case of whatsapp) to control the behavior or filter the spam messages sent by users." }, { "code": null, "e": 26151, "s": 25967, "text": "A Telegram Account: If you don’t have the Telegram app installed just download it from the play store. After downloading create an account using your mobile number just like WhatsApp." }, { "code": null, "e": 26632, "s": 26151, "text": ".python-telegram-bot module: Here we will need a module called python-telegram-bot, This library provides a pure Python interface for the Telegram Bot API. It’s compatible with Python versions 3.6.8+. In addition to the pure API implementation, this library features a number of high-level classes to make the development of bots easy and straightforward. These classes are contained in the “telegram.ext” submodule. For more information, you can check their official GitHub repo." }, { "code": null, "e": 26701, "s": 26632, "text": "We can install this module via pip and conda with the below command." }, { "code": null, "e": 26827, "s": 26701, "text": "# installing via pip\npip install python-telegram-bot\n\n# installing via conda\nconda install -c conda-forge python-telegram-bot" }, { "code": null, "e": 26925, "s": 26827, "text": "Step 1: After opening an account on Telegram, in the search bar at the top search for “BotFather”" }, { "code": null, "e": 26990, "s": 26925, "text": "Step 2: Click on the ‘BotFather’ (first result) and type /newbot" }, { "code": null, "e": 27201, "s": 26990, "text": "Step 3: Give a unique name to your bot. After naming it, Botfather will ask for its username. Then also give a unique name BUT remember the username of your bot must end with the bot, like my_bot, hellobot etc." }, { "code": null, "e": 27305, "s": 27201, "text": "Step 4: After giving a unique name and if it gets accepted you will get a message something like this –" }, { "code": null, "e": 27482, "s": 27305, "text": "Here the token value will be different for you, we will use this token in our python code to make changes in our bot and make it just like we want, and add some commands in it." }, { "code": null, "e": 27490, "s": 27482, "text": "Python3" }, { "code": "from telegram.ext.updater import Updaterfrom telegram.update import Updatefrom telegram.ext.callbackcontext import CallbackContextfrom telegram.ext.commandhandler import CommandHandlerfrom telegram.ext.messagehandler import MessageHandlerfrom telegram.ext.filters import Filters", "e": 27769, "s": 27490, "text": null }, { "code": null, "e": 27816, "s": 27769, "text": "Brief usage of the functions we are importing:" }, { "code": null, "e": 27957, "s": 27816, "text": "Updater: This will contain the API key we got from BotFather to specify in which bot we are adding functionalities to using our python code." }, { "code": null, "e": 28076, "s": 27957, "text": "Update: This will invoke every time a bot receives an update i.e. message or command and will send the user a message." }, { "code": null, "e": 28235, "s": 28076, "text": "CallbackContext: We will not use its functionality directly in our code but when we will be adding the dispatcher it is required (and it will work internally)" }, { "code": null, "e": 28388, "s": 28235, "text": "CommandHandler: This Handler class is used to handle any command sent by the user to the bot, a command always starts with “/” i.e “/start”,”/help” etc." }, { "code": null, "e": 28489, "s": 28388, "text": "MessageHandler: This Handler class is used to handle any normal message sent by the user to the bot," }, { "code": null, "e": 28571, "s": 28489, "text": "FIlters: This will filter normal text, commands, images, etc from a sent message." }, { "code": null, "e": 28760, "s": 28571, "text": "Start function: It will display the first conversation, you may name it something else but the message inside it will be sent to the user whenever they press ‘start’ at the very beginning." }, { "code": null, "e": 28768, "s": 28760, "text": "Python3" }, { "code": "updater = Updater(\"your_own_API_Token got from BotFather\", use_context=True) def start(update: Update, context: CallbackContext): update.message.reply_text( \"Enter the text you want to show to the user whenever they start the bot\")", "e": 29030, "s": 28768, "text": null }, { "code": null, "e": 29125, "s": 29030, "text": "Basically, in the start message, you should add something like “Hello Welcome to the Bot” etc." }, { "code": null, "e": 29311, "s": 29125, "text": "Help function: It is basically in this function you should add any kind of help the user might need, i.e. All the commands your bot understands, The information related to the bot, etc)" }, { "code": null, "e": 29319, "s": 29311, "text": "Python3" }, { "code": "def help(update: Update, context: CallbackContext): update.message.reply_text(\"Your Message\")", "e": 29416, "s": 29319, "text": null }, { "code": null, "e": 29461, "s": 29416, "text": "Adding some more functionalities to the Bot." }, { "code": null, "e": 29469, "s": 29461, "text": "Python3" }, { "code": "def gmail_url(update: Update, context: CallbackContext): update.message.reply_text(\"gmail link here\") def youtube_url(update: Update, context: CallbackContext): update.message.reply_text(\"youtube link\") def linkedIn_url(update: Update, context: CallbackContext): update.message.reply_text(\"Your linkedin profile url\") def geeks_url(update: Update, context: CallbackContext): update.message.reply_text(\"GeeksforGeeks url here\") def unknown_text(update: Update, context: CallbackContext): update.message.reply_text( \"Sorry I can't recognize you , you said '%s'\" % update.message.text) def unknown(update: Update, context: CallbackContext): update.message.reply_text( \"Sorry '%s' is not a valid command\" % update.message.text)", "e": 30240, "s": 29469, "text": null }, { "code": null, "e": 30735, "s": 30240, "text": "Here we have added 4 functions one to open Gmail, one for youtube, one for LinkedIn, and the last one for GeeksforGeeks. These are not MANDATORY functions, you can add any kind of functions and their reply_text as you want, these are just for demonstration. Here the unknown_text function will send the message written inside it whenever it gets some unknown messages and the unknown function will Filter out all the unknown commands sent by the user and reply to the message written inside it." }, { "code": null, "e": 30743, "s": 30735, "text": "Python3" }, { "code": "updater.dispatcher.add_handler(CommandHandler('start', start))updater.dispatcher.add_handler(CommandHandler('youtube', youtube_url))updater.dispatcher.add_handler(CommandHandler('help', help))updater.dispatcher.add_handler(CommandHandler('linkedin', linkedIn_url))updater.dispatcher.add_handler(CommandHandler('gmail', gmail_url))updater.dispatcher.add_handler(CommandHandler('geeks', geeks_url))updater.dispatcher.add_handler(MessageHandler(Filters.text, unknown))updater.dispatcher.add_handler(MessageHandler( # Filters out unknown commands Filters.command, unknown)) # Filters out unknown messages.updater.dispatcher.add_handler(MessageHandler(Filters.text, unknown_text))", "e": 31426, "s": 30743, "text": null }, { "code": null, "e": 31631, "s": 31426, "text": "Here each line suggests that whenever a user writes a command i.e. the first parameter of the CommandHandler in reply the user gets the message written inside the function mentioned in the next parameter." }, { "code": null, "e": 31639, "s": 31631, "text": "Python3" }, { "code": "updater.start_polling()", "e": 31663, "s": 31639, "text": null }, { "code": null, "e": 31852, "s": 31663, "text": "Here whenever we start polling the bot will be active and it will look for any new message sent by any of the users and if it matches the command specified there it will reply accordingly." }, { "code": null, "e": 31886, "s": 31852, "text": "Below is the full implementation:" }, { "code": null, "e": 31894, "s": 31886, "text": "Python3" }, { "code": "from telegram.ext.updater import Updaterfrom telegram.update import Updatefrom telegram.ext.callbackcontext import CallbackContextfrom telegram.ext.commandhandler import CommandHandlerfrom telegram.ext.messagehandler import MessageHandlerfrom telegram.ext.filters import Filters updater = Updater(\"your_own_API_Token got from BotFather\", use_context=True) def start(update: Update, context: CallbackContext): update.message.reply_text( \"Hello sir, Welcome to the Bot.Please write\\ /help to see the commands available.\") def help(update: Update, context: CallbackContext): update.message.reply_text(\"\"\"Available Commands :- /youtube - To get the youtube URL /linkedin - To get the LinkedIn profile URL /gmail - To get gmail URL /geeks - To get the GeeksforGeeks URL\"\"\") def gmail_url(update: Update, context: CallbackContext): update.message.reply_text( \"Your gmail link here (I am not\\ giving mine one for security reasons)\") def youtube_url(update: Update, context: CallbackContext): update.message.reply_text(\"Youtube Link =>\\ https://www.youtube.com/\") def linkedIn_url(update: Update, context: CallbackContext): update.message.reply_text( \"LinkedIn URL => \\ https://www.linkedin.com/in/dwaipayan-bandyopadhyay-007a/\") def geeks_url(update: Update, context: CallbackContext): update.message.reply_text( \"GeeksforGeeks URL => https://www.geeksforgeeks.org/\") def unknown(update: Update, context: CallbackContext): update.message.reply_text( \"Sorry '%s' is not a valid command\" % update.message.text) def unknown_text(update: Update, context: CallbackContext): update.message.reply_text( \"Sorry I can't recognize you , you said '%s'\" % update.message.text) updater.dispatcher.add_handler(CommandHandler('start', start))updater.dispatcher.add_handler(CommandHandler('youtube', youtube_url))updater.dispatcher.add_handler(CommandHandler('help', help))updater.dispatcher.add_handler(CommandHandler('linkedin', linkedIn_url))updater.dispatcher.add_handler(CommandHandler('gmail', gmail_url))updater.dispatcher.add_handler(CommandHandler('geeks', geeks_url))updater.dispatcher.add_handler(MessageHandler(Filters.text, unknown))updater.dispatcher.add_handler(MessageHandler( Filters.command, unknown)) # Filters out unknown commands # Filters out unknown messages.updater.dispatcher.add_handler(MessageHandler(Filters.text, unknown_text)) updater.start_polling()", "e": 34403, "s": 31894, "text": null }, { "code": null, "e": 34411, "s": 34403, "text": "Output:" }, { "code": null, "e": 34471, "s": 34411, "text": "Media error: Format(s) not supported or source(s) not found" }, { "code": null, "e": 34487, "s": 34471, "text": "Python-projects" }, { "code": null, "e": 34502, "s": 34487, "text": "python-utility" }, { "code": null, "e": 34509, "s": 34502, "text": "Python" }, { "code": null, "e": 34607, "s": 34509, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34639, "s": 34607, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 34681, "s": 34639, "text": "Check if element exists in list in Python" }, { "code": null, "e": 34723, "s": 34681, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 34779, "s": 34723, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 34806, "s": 34779, "text": "Python Classes and Objects" }, { "code": null, "e": 34837, "s": 34806, "text": "Python | os.path.join() method" }, { "code": null, "e": 34876, "s": 34837, "text": "Python | Get unique values from a list" }, { "code": null, "e": 34905, "s": 34876, "text": "Create a directory in Python" }, { "code": null, "e": 34927, "s": 34905, "text": "Defaultdict in Python" } ]
HTML <textarea> tag - GeeksforGeeks
15 Dec, 2021 The <textarea> tag in HTML defines a multi-line plain-text editing control. A text space will hold an infinite range of characters, and therefore the text renders in a set-width font (usually Courier). The size of a text area is often such by the cols and rows attributes, or perhaps better; through CSS’ height and dimension properties. The textarea is generally used in a form, to collect user inputs like comments or reviews. The name attribute is needed for the reference in the form data after the form is submitted. By omitting the name attribute, data from the text area will not be submitted. The id attribute is required to link the text area with a label. Syntax: <textarea>....</textarea> Attribute values: autocomplete: It is used to specify whether the Textarea field has autocompleted on or off. autofocus: It is used to specify that the textarea field should get automatically focus when the page loads. cols: It is used to tell the browser how many average-width characters should fit on a single line i.e the number of columns to display. dirname: It is used to enable the text direction of the Textarea Field after submitting the form. disabled: It is used to specify that the text area element is disabled. form: It is used to specify the one or more forms that the <Textarea> element belongs to. maxlength: It is used to specify the maximum number of characters entered into the Textarea element. minlength: It is used to define the minimum number of characters (as UTF-16 code units) of a Textarea Element. name: It is used to specify the name of the <Textarea> element. placeholder: It is used to specify the expected value to be displayed before user input in textarea element. readonly: It is used to specify that the textarea element is read-only. If the textarea is read-only, then its content cannot be changed but can be copied and highlighted. required: It is a boolean attribute that is used to specify that the <textarea> element must be filled out before submitting the Form. rows: It is used to specify the number of visible text lines for the control i.e. the number of rows to display. wrap: It is used to specify that in which manner the text is to be wrapped in a text area when a form is submitted. Example 1: This simple example illustrates the use of the <textarea> tag in HTML that enables the multi-line text input control. HTML <!DOCTYPE html><html><head> <title>textarea tag</title></head> <body> <h1>GeeksForGeeks</h1> <h2>HTML Textarea tag </h2> <form action="#"> <textarea rows="10" cols="20" name="blog"> Share your knowledge by writing your own blog! </textarea> <br> <input type="submit" value="submit"> </form></body></html> Output: HTML <textarea> Tag Example 2: In this example, we have used the resize property whose value is set to none that will disable the resize option of the textarea. HTML <!DOCTYPE html><html><head> <title>HTML textarea tag</title> <style> textarea { resize: none; } </style></head> <body> <h1>GeeksforGeeks</h1> <h2>HTML Textarea tag </h2> <form action="#"> <textarea rows="7" cols="50" name="comment"> </textarea> <br> <input type="submit"> </form></body></html> Output: HTML <textarea> Tag Supported Browsers: Google Chrome 93.0 Internet Explorer 11.0 Microsoft Edge 93.0 Firefox 92.0 Safari 14.1 Opera 78.0 Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. bhaskargeeksforgeeks HTML-Tags 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": "\n15 Dec, 2021" }, { "code": null, "e": 26805, "s": 26139, "text": "The <textarea> tag in HTML defines a multi-line plain-text editing control. A text space will hold an infinite range of characters, and therefore the text renders in a set-width font (usually Courier). The size of a text area is often such by the cols and rows attributes, or perhaps better; through CSS’ height and dimension properties. The textarea is generally used in a form, to collect user inputs like comments or reviews. The name attribute is needed for the reference in the form data after the form is submitted. By omitting the name attribute, data from the text area will not be submitted. The id attribute is required to link the text area with a label." }, { "code": null, "e": 26813, "s": 26805, "text": "Syntax:" }, { "code": null, "e": 26839, "s": 26813, "text": "<textarea>....</textarea>" }, { "code": null, "e": 26857, "s": 26839, "text": "Attribute values:" }, { "code": null, "e": 26949, "s": 26857, "text": "autocomplete: It is used to specify whether the Textarea field has autocompleted on or off." }, { "code": null, "e": 27058, "s": 26949, "text": "autofocus: It is used to specify that the textarea field should get automatically focus when the page loads." }, { "code": null, "e": 27195, "s": 27058, "text": "cols: It is used to tell the browser how many average-width characters should fit on a single line i.e the number of columns to display." }, { "code": null, "e": 27293, "s": 27195, "text": "dirname: It is used to enable the text direction of the Textarea Field after submitting the form." }, { "code": null, "e": 27365, "s": 27293, "text": "disabled: It is used to specify that the text area element is disabled." }, { "code": null, "e": 27455, "s": 27365, "text": "form: It is used to specify the one or more forms that the <Textarea> element belongs to." }, { "code": null, "e": 27556, "s": 27455, "text": "maxlength: It is used to specify the maximum number of characters entered into the Textarea element." }, { "code": null, "e": 27667, "s": 27556, "text": "minlength: It is used to define the minimum number of characters (as UTF-16 code units) of a Textarea Element." }, { "code": null, "e": 27731, "s": 27667, "text": "name: It is used to specify the name of the <Textarea> element." }, { "code": null, "e": 27840, "s": 27731, "text": "placeholder: It is used to specify the expected value to be displayed before user input in textarea element." }, { "code": null, "e": 28012, "s": 27840, "text": "readonly: It is used to specify that the textarea element is read-only. If the textarea is read-only, then its content cannot be changed but can be copied and highlighted." }, { "code": null, "e": 28147, "s": 28012, "text": "required: It is a boolean attribute that is used to specify that the <textarea> element must be filled out before submitting the Form." }, { "code": null, "e": 28260, "s": 28147, "text": "rows: It is used to specify the number of visible text lines for the control i.e. the number of rows to display." }, { "code": null, "e": 28376, "s": 28260, "text": "wrap: It is used to specify that in which manner the text is to be wrapped in a text area when a form is submitted." }, { "code": null, "e": 28505, "s": 28376, "text": "Example 1: This simple example illustrates the use of the <textarea> tag in HTML that enables the multi-line text input control." }, { "code": null, "e": 28510, "s": 28505, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <title>textarea tag</title></head> <body> <h1>GeeksForGeeks</h1> <h2>HTML Textarea tag </h2> <form action=\"#\"> <textarea rows=\"10\" cols=\"20\" name=\"blog\"> Share your knowledge by writing your own blog! </textarea> <br> <input type=\"submit\" value=\"submit\"> </form></body></html>", "e": 28915, "s": 28510, "text": null }, { "code": null, "e": 28923, "s": 28915, "text": "Output:" }, { "code": null, "e": 28943, "s": 28923, "text": "HTML <textarea> Tag" }, { "code": null, "e": 29084, "s": 28943, "text": "Example 2: In this example, we have used the resize property whose value is set to none that will disable the resize option of the textarea." }, { "code": null, "e": 29089, "s": 29084, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <title>HTML textarea tag</title> <style> textarea { resize: none; } </style></head> <body> <h1>GeeksforGeeks</h1> <h2>HTML Textarea tag </h2> <form action=\"#\"> <textarea rows=\"7\" cols=\"50\" name=\"comment\"> </textarea> <br> <input type=\"submit\"> </form></body></html>", "e": 29493, "s": 29089, "text": null }, { "code": null, "e": 29502, "s": 29493, "text": "Output: " }, { "code": null, "e": 29522, "s": 29502, "text": "HTML <textarea> Tag" }, { "code": null, "e": 29542, "s": 29522, "text": "Supported Browsers:" }, { "code": null, "e": 29561, "s": 29542, "text": "Google Chrome 93.0" }, { "code": null, "e": 29584, "s": 29561, "text": "Internet Explorer 11.0" }, { "code": null, "e": 29604, "s": 29584, "text": "Microsoft Edge 93.0" }, { "code": null, "e": 29617, "s": 29604, "text": "Firefox 92.0" }, { "code": null, "e": 29629, "s": 29617, "text": "Safari 14.1" }, { "code": null, "e": 29640, "s": 29629, "text": "Opera 78.0" }, { "code": null, "e": 29777, "s": 29640, "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": 29798, "s": 29777, "text": "bhaskargeeksforgeeks" }, { "code": null, "e": 29808, "s": 29798, "text": "HTML-Tags" }, { "code": null, "e": 29813, "s": 29808, "text": "HTML" }, { "code": null, "e": 29830, "s": 29813, "text": "Web Technologies" }, { "code": null, "e": 29835, "s": 29830, "text": "HTML" }, { "code": null, "e": 29933, "s": 29835, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29957, "s": 29933, "text": "REST API (Introduction)" }, { "code": null, "e": 29998, "s": 29957, "text": "HTML Cheat Sheet - A Basic Guide to HTML" }, { "code": null, "e": 30035, "s": 29998, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 30064, "s": 30035, "text": "Form validation using jQuery" }, { "code": null, "e": 30084, "s": 30064, "text": "Angular File Upload" }, { "code": null, "e": 30124, "s": 30084, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 30157, "s": 30124, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 30202, "s": 30157, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 30245, "s": 30202, "text": "How to fetch data from an API in ReactJS ?" } ]
Lodash _.omit() Method - GeeksforGeeks
07 Sep, 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 _.omit() method is used to return a copy of the object that composed of the own and inherited enumerable property paths of the given object that are not omitted. It is the opposite of the _.pick() method. Syntax: _.omit( object, paths ) Parameters: This method accepts two parameters as mentioned above and described below: object: This parameter holds the source object. paths: This parameter holds the property paths to omit. Return Value: This method returns the new object. Example 1: Javascript // Requiring the lodash library const _ = require("lodash"); // The source objectvar obj = { Name: "GeeksforGeeks", password: "gfg@1234", username: "your_geeks" } // Using the _.omit() method console.log(_.omit(obj, ['password', 'username'])); Output: {Name: "GeeksforGeeks"} Example 2: Javascript // Requiring the lodash library const _ = require("lodash"); // The source objectvar obj = { 'x': 1, 'y': '2', 'z': 3 }; // Use the _.omit() method console.log(_.omit(obj, ['x', 'y'])); Output: {'z': 3} 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 Difference between var, let and const keywords in JavaScript Difference Between PUT and PATCH Request JavaScript | Promises How to get character array from string in JavaScript? Remove elements from a JavaScript Array Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26545, "s": 26517, "text": "\n07 Sep, 2020" }, { "code": null, "e": 26685, "s": 26545, "text": "Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, strings, objects, numbers, etc." }, { "code": null, "e": 26894, "s": 26685, "text": "The _.omit() method is used to return a copy of the object that composed of the own and inherited enumerable property paths of the given object that are not omitted. It is the opposite of the _.pick() method." }, { "code": null, "e": 26902, "s": 26894, "text": "Syntax:" }, { "code": null, "e": 26926, "s": 26902, "text": "_.omit( object, paths )" }, { "code": null, "e": 27013, "s": 26926, "text": "Parameters: This method accepts two parameters as mentioned above and described below:" }, { "code": null, "e": 27061, "s": 27013, "text": "object: This parameter holds the source object." }, { "code": null, "e": 27117, "s": 27061, "text": "paths: This parameter holds the property paths to omit." }, { "code": null, "e": 27167, "s": 27117, "text": "Return Value: This method returns the new object." }, { "code": null, "e": 27178, "s": 27167, "text": "Example 1:" }, { "code": null, "e": 27189, "s": 27178, "text": "Javascript" }, { "code": "// Requiring the lodash library const _ = require(\"lodash\"); // The source objectvar obj = { Name: \"GeeksforGeeks\", password: \"gfg@1234\", username: \"your_geeks\" } // Using the _.omit() method console.log(_.omit(obj, ['password', 'username']));", "e": 27481, "s": 27189, "text": null }, { "code": null, "e": 27489, "s": 27481, "text": "Output:" }, { "code": null, "e": 27513, "s": 27489, "text": "{Name: \"GeeksforGeeks\"}" }, { "code": null, "e": 27526, "s": 27513, "text": "Example 2: " }, { "code": null, "e": 27537, "s": 27526, "text": "Javascript" }, { "code": "// Requiring the lodash library const _ = require(\"lodash\"); // The source objectvar obj = { 'x': 1, 'y': '2', 'z': 3 }; // Use the _.omit() method console.log(_.omit(obj, ['x', 'y']));", "e": 27728, "s": 27537, "text": null }, { "code": null, "e": 27736, "s": 27728, "text": "Output:" }, { "code": null, "e": 27745, "s": 27736, "text": "{'z': 3}" }, { "code": null, "e": 27763, "s": 27745, "text": "JavaScript-Lodash" }, { "code": null, "e": 27774, "s": 27763, "text": "JavaScript" }, { "code": null, "e": 27791, "s": 27774, "text": "Web Technologies" }, { "code": null, "e": 27889, "s": 27791, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27929, "s": 27889, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 27990, "s": 27929, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 28031, "s": 27990, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 28053, "s": 28031, "text": "JavaScript | Promises" }, { "code": null, "e": 28107, "s": 28053, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 28147, "s": 28107, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28180, "s": 28147, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28223, "s": 28180, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 28285, "s": 28223, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
Django Formsets - GeeksforGeeks
09 Jan, 2020 Formsets in a Django is an advanced way of handling multiple forms on a single webpage. In other words, Formsets are a group of forms in Django. One might want to initialize multiple forms on a single page all of which may involve multiple POST requests, for example from django import forms class GeeksForm(forms.Form): title = forms.CharField() pub_date = forms.DateField() Now one might want to permit the user to create articles at once, so if thought in a conventional manner one uses multiple forms and different names for each form to handle data on a single page but this would complicate the code as well as functionality. A formset is a layer of abstraction to work with multiple forms on the same page. It can be best compared to a data grid.Now to create a formset of this GeeksForm, from django.forms import formset_factory GeeksFormSet = formset_factory(GeeksForm) Illustration of Rendering Django Forms Manually using an Example. Consider a project named geeksforgeeks having an app named geeks. Refer to the following articles to check how to create a project and an app in Django. How to Create a Basic Project using MVT in Django? How to Create an App in Django ? In your geeks app make a new file called forms.py where you would be making all your forms. To create a Django form you need to use Django Form Class. Let’s demonstrate how,In your forms.py Enter the following, from django import forms # create a formclass GeeksForm(forms.Form): title = forms.CharField() description = forms.CharField() Let’s explain what exactly is happening, left side denotes the name of the field and to right of it, you define various functionalities of an input field correspondingly. A field’s syntax is denoted asSyntax : Field_name = forms.FieldType(attributes) Now to create a simple formset of this form, move to views.py and create a formset_view as below. from django.shortcuts import render # relative import of formsfrom .forms import GeeksForm # importing formset_factoryfrom django.forms import formset_factory def formset_view(request): context ={} # creating a formset GeeksFormSet = formset_factory(GeeksForm) formset = GeeksFormSet() # Add the formset to context dictionary context['formset']= formset return render(request, "home.html", context) To render the formset through HTML, create a html file “home.html”. Now let’s edit templates > home.html <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ formset.as_p }} <input type="submit" value="Submit"></form> All set to check if our formset is working or not let’s visit http://localhost:8000/..Our formset is working completely. Let’s learn how to modify this formset to use extra features of this formset. Django formsets are used to handle multiple instances of a form. One can create multiple forms easily using extra attribute of Django Formsets. In geeks/views.py, from django.shortcuts import render # relative import of formsfrom .forms import GeeksForm # importing formset_factoryfrom django.forms import formset_factory def formset_view(request): context ={} # creating a formset and 5 instances of GeeksForm GeeksFormSet = formset_factory(GeeksForm, extra = 5) formset = GeeksFormSet() # Add the formset to context dictionary context['formset']= formset return render(request, "home.html", context) The keyword argument extra makes multiple copies of same form. If one wants to create 5 forms enter extra = 5 and similarly for others. Visit http://localhost:8000/ to check if 5 forms are created. Creating a form is much easier than handling the data entered into those fields at the back end. Let’s try to demonstrate how one can easily use the data of a formset in a view. When trying to handle formset, Django formsets required one extra argument {{ formset.management_data }}. To know more about Management data, visit Understanding the ManagementForm.In templates/home.html, <form method="POST" enctype="multipart/form-data"> <!-- Management data of formset --> {{ formset.management_data }} <!-- Security token --> {% csrf_token %} <!-- Using the formset --> {{ formset.as_p }} <input type="submit" value="Submit"></form> Now to check how and what type of data is being rendered edit formset_view to print the data. In geeks/view.py, from django.shortcuts import render # relative import of formsfrom .forms import GeeksForm # importing formset_factoryfrom django.forms import formset_factory def formset_view(request): context ={} # creating a formset and 5 instances of GeeksForm GeeksFormSet = formset_factory(GeeksForm, extra = 3) formset = GeeksFormSet(request.POST or None) # print formset data if it is valid if formset.is_valid(): for form in formset: print(form.cleaned_data) # Add the formset to context dictionary context['formset']= formset return render(request, "home.html", context) Now let’s try to enter data in the formset through http://localhost:8000/Hit submit and data will be display in command line where server is running. One can use this data in any manner conveniently now.Formset is advanced stuff which can be used to resolve a number of problems but should be used with correct syntax and field validations otherwise conflicts and errors will disrupt the normal functioning. To know more about Formsets, Visit Official Documentation for Formsets. Django-forms Python Django Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace()
[ { "code": null, "e": 42909, "s": 42881, "text": "\n09 Jan, 2020" }, { "code": null, "e": 43176, "s": 42909, "text": "Formsets in a Django is an advanced way of handling multiple forms on a single webpage. In other words, Formsets are a group of forms in Django. One might want to initialize multiple forms on a single page all of which may involve multiple POST requests, for example" }, { "code": null, "e": 43294, "s": 43176, "text": "from django import forms\nclass GeeksForm(forms.Form):\n title = forms.CharField()\n pub_date = forms.DateField()\n" }, { "code": null, "e": 43714, "s": 43294, "text": "Now one might want to permit the user to create articles at once, so if thought in a conventional manner one uses multiple forms and different names for each form to handle data on a single page but this would complicate the code as well as functionality. A formset is a layer of abstraction to work with multiple forms on the same page. It can be best compared to a data grid.Now to create a formset of this GeeksForm," }, { "code": null, "e": 43798, "s": 43714, "text": "from django.forms import formset_factory\nGeeksFormSet = formset_factory(GeeksForm)\n" }, { "code": null, "e": 43930, "s": 43798, "text": "Illustration of Rendering Django Forms Manually using an Example. Consider a project named geeksforgeeks having an app named geeks." }, { "code": null, "e": 44017, "s": 43930, "text": "Refer to the following articles to check how to create a project and an app in Django." }, { "code": null, "e": 44068, "s": 44017, "text": "How to Create a Basic Project using MVT in Django?" }, { "code": null, "e": 44101, "s": 44068, "text": "How to Create an App in Django ?" }, { "code": null, "e": 44312, "s": 44101, "text": "In your geeks app make a new file called forms.py where you would be making all your forms. To create a Django form you need to use Django Form Class. Let’s demonstrate how,In your forms.py Enter the following," }, { "code": "from django import forms # create a formclass GeeksForm(forms.Form): title = forms.CharField() description = forms.CharField()", "e": 44446, "s": 44312, "text": null }, { "code": null, "e": 44656, "s": 44446, "text": "Let’s explain what exactly is happening, left side denotes the name of the field and to right of it, you define various functionalities of an input field correspondingly. A field’s syntax is denoted asSyntax :" }, { "code": null, "e": 44697, "s": 44656, "text": "Field_name = forms.FieldType(attributes)" }, { "code": null, "e": 44795, "s": 44697, "text": "Now to create a simple formset of this form, move to views.py and create a formset_view as below." }, { "code": "from django.shortcuts import render # relative import of formsfrom .forms import GeeksForm # importing formset_factoryfrom django.forms import formset_factory def formset_view(request): context ={} # creating a formset GeeksFormSet = formset_factory(GeeksForm) formset = GeeksFormSet() # Add the formset to context dictionary context['formset']= formset return render(request, \"home.html\", context)", "e": 45226, "s": 44795, "text": null }, { "code": null, "e": 45331, "s": 45226, "text": "To render the formset through HTML, create a html file “home.html”. Now let’s edit templates > home.html" }, { "code": "<form method=\"POST\" enctype=\"multipart/form-data\"> {% csrf_token %} {{ formset.as_p }} <input type=\"submit\" value=\"Submit\"></form>", "e": 45471, "s": 45331, "text": null }, { "code": null, "e": 45670, "s": 45471, "text": "All set to check if our formset is working or not let’s visit http://localhost:8000/..Our formset is working completely. Let’s learn how to modify this formset to use extra features of this formset." }, { "code": null, "e": 45833, "s": 45670, "text": "Django formsets are used to handle multiple instances of a form. One can create multiple forms easily using extra attribute of Django Formsets. In geeks/views.py," }, { "code": "from django.shortcuts import render # relative import of formsfrom .forms import GeeksForm # importing formset_factoryfrom django.forms import formset_factory def formset_view(request): context ={} # creating a formset and 5 instances of GeeksForm GeeksFormSet = formset_factory(GeeksForm, extra = 5) formset = GeeksFormSet() # Add the formset to context dictionary context['formset']= formset return render(request, \"home.html\", context)", "e": 46304, "s": 45833, "text": null }, { "code": null, "e": 46502, "s": 46304, "text": "The keyword argument extra makes multiple copies of same form. If one wants to create 5 forms enter extra = 5 and similarly for others. Visit http://localhost:8000/ to check if 5 forms are created." }, { "code": null, "e": 46885, "s": 46502, "text": "Creating a form is much easier than handling the data entered into those fields at the back end. Let’s try to demonstrate how one can easily use the data of a formset in a view. When trying to handle formset, Django formsets required one extra argument {{ formset.management_data }}. To know more about Management data, visit Understanding the ManagementForm.In templates/home.html," }, { "code": "<form method=\"POST\" enctype=\"multipart/form-data\"> <!-- Management data of formset --> {{ formset.management_data }} <!-- Security token --> {% csrf_token %} <!-- Using the formset --> {{ formset.as_p }} <input type=\"submit\" value=\"Submit\"></form>", "e": 47170, "s": 46885, "text": null }, { "code": null, "e": 47282, "s": 47170, "text": "Now to check how and what type of data is being rendered edit formset_view to print the data. In geeks/view.py," }, { "code": "from django.shortcuts import render # relative import of formsfrom .forms import GeeksForm # importing formset_factoryfrom django.forms import formset_factory def formset_view(request): context ={} # creating a formset and 5 instances of GeeksForm GeeksFormSet = formset_factory(GeeksForm, extra = 3) formset = GeeksFormSet(request.POST or None) # print formset data if it is valid if formset.is_valid(): for form in formset: print(form.cleaned_data) # Add the formset to context dictionary context['formset']= formset return render(request, \"home.html\", context)", "e": 47916, "s": 47282, "text": null }, { "code": null, "e": 48396, "s": 47916, "text": "Now let’s try to enter data in the formset through http://localhost:8000/Hit submit and data will be display in command line where server is running. One can use this data in any manner conveniently now.Formset is advanced stuff which can be used to resolve a number of problems but should be used with correct syntax and field validations otherwise conflicts and errors will disrupt the normal functioning. To know more about Formsets, Visit Official Documentation for Formsets." }, { "code": null, "e": 48409, "s": 48396, "text": "Django-forms" }, { "code": null, "e": 48423, "s": 48409, "text": "Python Django" }, { "code": null, "e": 48430, "s": 48423, "text": "Python" }, { "code": null, "e": 48528, "s": 48430, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 48556, "s": 48528, "text": "Read JSON file using Python" }, { "code": null, "e": 48606, "s": 48556, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 48628, "s": 48606, "text": "Python map() function" }, { "code": null, "e": 48672, "s": 48628, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 48707, "s": 48672, "text": "Read a file line by line in Python" }, { "code": null, "e": 48739, "s": 48707, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 48761, "s": 48739, "text": "Enumerate() in Python" }, { "code": null, "e": 48803, "s": 48761, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 48833, "s": 48803, "text": "Iterate over a list in Python" } ]
Servlet Collaboration In Java Using RequestDispatcher and HttpServletResponse
15 Nov, 2021 What is Servlet Collaboration? The exchange of information among servlets of a particular Java web application is known as Servlet Collaboration. This enables passing/sharing information from one servlet to the other through method invocations. What are the principle ways provided by Java to achieve Servlet Collaboration?The servlet api provides two interfaces namely: javax.servlet.RequestDispatcherjavax.servlet.http.HttpServletResponse javax.servlet.RequestDispatcher javax.servlet.http.HttpServletResponse These two interfaces include the methods responsible for achieving the objective of sharing information between servlets. Using RequestDispatcher Interface The RequestDispatcher interface provides the option of dispatching the client’s request to another web resource, which could be an HTML page, another servlet, JSP etc. It provides the following two methods: public void forward(ServletRequest request, ServletResponse response)throws ServletException, java.io.IOException:The forward() method is used to transfer the client request to another resource (HTML file, servlet, jsp etc). When this method is called, the control is transferred to the next resource called. On the other hand, the include() method is used to include the content of the calling file into the called file. After calling this method, the control remains with the calling resource, but the processed output is included into the called resource.The following diagram explains the way it works: public void include(ServletRequest request, ServletResponse response)throws ServletException, java.io.IOException:The include() method is used to include the contents of the calling resource into the called one. When this method is called, the control still remains with the calling resource. It simply includes the processed output of the calling resource into the called one.The following diagram explains how it works: Example of using RequestDispatcher for Servlet CollaborationThe following example explains how to use RequestDispatcher interface to achieve Servlet Collaboration:index.html html <html><head><body><form action="login" method="post"> Name:<input type="text" name="userName"/><br/> Password:<input type="password" name="userPass"/><br/> <input type="submit" value="login"/> </form> </body></html> Login.java Java // First java servlet that calls another resourceimport java.io.*;import javax.servlet.*;import javax.servlet.http.*; public class Login extends HttpServlet { public void doPost(HttpServletRequest req, HttpServletResponse res)throws ServletException, IOException { // The method to receive client requests // which are sent using 'post' res.setContentType("text/html"); PrintWriter out = response.getWriter(); // fetches username String n = request.getParameter("userName"); // fetches password String p = request.getParameter("userPass"); if(p.equals("Thanos"){ RequestDispatcher rd = request.getRequestDispatcher("servlet2"); // Getting RequestDispatcher object // for collaborating with servlet2 // forwarding the request to servlet2 rd.forward(request, response); } else{ out.print("Password mismatch"); RequestDispatcher rd = request.getRequestDispatcher("/index.html"); rd.include(request, response); } } } Welcome.java Java // Called servlet in case password matchesimport java.io.*;import javax.servlet.*;import javax.servlet.http.*; public class Welcome extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); // fetches username String n = request.getParameter("userName"); // prints the message out.print("Welcome " + n); }} web.xml html <web-app> <servlet> <servlet-name>Login</servlet-name> <servlet-class>Login</servlet-class> </servlet> <servlet> <servlet-name>WelcomeServlet</servlet-name> <servlet-class>Welcome</servlet-class> </servlet> <servlet-mapping> <servlet-name>Login</servlet-name> <url-pattern>/servlet1</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>WelcomeServlet</servlet-name> <url-pattern>/servlet2</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.html</welcome-file> </welcome-file-list> </web-app> Output: index.html If password matches: If password doesn’t match: Using HttpServletResponse Interface The HttpServletResponse interface is entrusted with managing Http responses. To achieve servlet collaboration, it uses the following method: public void sendRedirect(String URL)throws IOException; This method is used redirect response to another resource, which may be a servlet, jsp or an html file. The argument accepted by it, is a URL which can be both, absolute and relative. It works on the client side and uses the browser’s URL bar to make a request. Example of using sendRedirect() for redirection The following example of a web application created using servlet takes the text written in the text field in the webpage, and directs it to the servlet. The servlet then redirects it to google, which then produces search results based on the text written.index.html html <html><head><body><form action="search" method="GET"><input type="text" name="name"><input type="submit" value="search"></form></body></html> Java // Servlet class to redirect the text keyword// in the 'name' field to google.com// using sendRedirect()import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse; public class MySearcher extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String name = request.getParameter("name"); response.sendRedirect("https://www.google.co.in/#q=" + name); // response redirected to google.com }} web.xml html <web-app><servlet><servlet-name>MySearcher</servlet-name><servlet-class>MySearcher</servlet-class></servlet> <servlet-mapping><servlet-name>MySearcher</servlet-name><url-pattern>/search</url-pattern></servlet-mapping> <welcome-file-list> <welcome-file>index.html</welcome-file> </welcome-file-list> </web-app> Output: index.html Search result What is the difference between forward() method of RequestDiispatcher and sendRedirect() of HttpServletResponse? Although the two methods appear to do the same thing, there are still differences between the two, which are as follows: akshaychopra96 sooda367 java-servlet Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n15 Nov, 2021" }, { "code": null, "e": 59, "s": 28, "text": "What is Servlet Collaboration?" }, { "code": null, "e": 274, "s": 59, "text": "The exchange of information among servlets of a particular Java web application is known as Servlet Collaboration. This enables passing/sharing information from one servlet to the other through method invocations. " }, { "code": null, "e": 401, "s": 274, "text": "What are the principle ways provided by Java to achieve Servlet Collaboration?The servlet api provides two interfaces namely: " }, { "code": null, "e": 471, "s": 401, "text": "javax.servlet.RequestDispatcherjavax.servlet.http.HttpServletResponse" }, { "code": null, "e": 503, "s": 471, "text": "javax.servlet.RequestDispatcher" }, { "code": null, "e": 542, "s": 503, "text": "javax.servlet.http.HttpServletResponse" }, { "code": null, "e": 665, "s": 542, "text": "These two interfaces include the methods responsible for achieving the objective of sharing information between servlets. " }, { "code": null, "e": 699, "s": 665, "text": "Using RequestDispatcher Interface" }, { "code": null, "e": 906, "s": 699, "text": "The RequestDispatcher interface provides the option of dispatching the client’s request to another web resource, which could be an HTML page, another servlet, JSP etc. It provides the following two methods:" }, { "code": null, "e": 1514, "s": 906, "text": "public void forward(ServletRequest request, ServletResponse response)throws ServletException, java.io.IOException:The forward() method is used to transfer the client request to another resource (HTML file, servlet, jsp etc). When this method is called, the control is transferred to the next resource called. On the other hand, the include() method is used to include the content of the calling file into the called file. After calling this method, the control remains with the calling resource, but the processed output is included into the called resource.The following diagram explains the way it works: " }, { "code": null, "e": 1937, "s": 1514, "text": "public void include(ServletRequest request, ServletResponse response)throws ServletException, java.io.IOException:The include() method is used to include the contents of the calling resource into the called one. When this method is called, the control still remains with the calling resource. It simply includes the processed output of the calling resource into the called one.The following diagram explains how it works: " }, { "code": null, "e": 2113, "s": 1937, "text": "Example of using RequestDispatcher for Servlet CollaborationThe following example explains how to use RequestDispatcher interface to achieve Servlet Collaboration:index.html " }, { "code": null, "e": 2118, "s": 2113, "text": "html" }, { "code": "<html><head><body><form action=\"login\" method=\"post\"> Name:<input type=\"text\" name=\"userName\"/><br/> Password:<input type=\"password\" name=\"userPass\"/><br/> <input type=\"submit\" value=\"login\"/> </form> </body></html>", "e": 2334, "s": 2118, "text": null }, { "code": null, "e": 2346, "s": 2334, "text": "Login.java " }, { "code": null, "e": 2351, "s": 2346, "text": "Java" }, { "code": "// First java servlet that calls another resourceimport java.io.*;import javax.servlet.*;import javax.servlet.http.*; public class Login extends HttpServlet { public void doPost(HttpServletRequest req, HttpServletResponse res)throws ServletException, IOException { // The method to receive client requests // which are sent using 'post' res.setContentType(\"text/html\"); PrintWriter out = response.getWriter(); // fetches username String n = request.getParameter(\"userName\"); // fetches password String p = request.getParameter(\"userPass\"); if(p.equals(\"Thanos\"){ RequestDispatcher rd = request.getRequestDispatcher(\"servlet2\"); // Getting RequestDispatcher object // for collaborating with servlet2 // forwarding the request to servlet2 rd.forward(request, response); } else{ out.print(\"Password mismatch\"); RequestDispatcher rd = request.getRequestDispatcher(\"/index.html\"); rd.include(request, response); } } } ", "e": 3494, "s": 2351, "text": null }, { "code": null, "e": 3508, "s": 3494, "text": "Welcome.java " }, { "code": null, "e": 3513, "s": 3508, "text": "Java" }, { "code": "// Called servlet in case password matchesimport java.io.*;import javax.servlet.*;import javax.servlet.http.*; public class Welcome extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType(\"text/html\"); PrintWriter out = response.getWriter(); // fetches username String n = request.getParameter(\"userName\"); // prints the message out.print(\"Welcome \" + n); }}", "e": 4062, "s": 3513, "text": null }, { "code": null, "e": 4071, "s": 4062, "text": "web.xml " }, { "code": null, "e": 4076, "s": 4071, "text": "html" }, { "code": "<web-app> <servlet> <servlet-name>Login</servlet-name> <servlet-class>Login</servlet-class> </servlet> <servlet> <servlet-name>WelcomeServlet</servlet-name> <servlet-class>Welcome</servlet-class> </servlet> <servlet-mapping> <servlet-name>Login</servlet-name> <url-pattern>/servlet1</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>WelcomeServlet</servlet-name> <url-pattern>/servlet2</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.html</welcome-file> </welcome-file-list> </web-app> ", "e": 4666, "s": 4076, "text": null }, { "code": null, "e": 4674, "s": 4666, "text": "Output:" }, { "code": null, "e": 4686, "s": 4674, "text": "index.html " }, { "code": null, "e": 4708, "s": 4686, "text": "If password matches: " }, { "code": null, "e": 4736, "s": 4708, "text": "If password doesn’t match: " }, { "code": null, "e": 4772, "s": 4736, "text": "Using HttpServletResponse Interface" }, { "code": null, "e": 4913, "s": 4772, "text": "The HttpServletResponse interface is entrusted with managing Http responses. To achieve servlet collaboration, it uses the following method:" }, { "code": null, "e": 4971, "s": 4913, "text": "public void sendRedirect(String URL)throws IOException; " }, { "code": null, "e": 5234, "s": 4971, "text": "This method is used redirect response to another resource, which may be a servlet, jsp or an html file. The argument accepted by it, is a URL which can be both, absolute and relative. It works on the client side and uses the browser’s URL bar to make a request. " }, { "code": null, "e": 5282, "s": 5234, "text": "Example of using sendRedirect() for redirection" }, { "code": null, "e": 5549, "s": 5282, "text": "The following example of a web application created using servlet takes the text written in the text field in the webpage, and directs it to the servlet. The servlet then redirects it to google, which then produces search results based on the text written.index.html " }, { "code": null, "e": 5554, "s": 5549, "text": "html" }, { "code": "<html><head><body><form action=\"search\" method=\"GET\"><input type=\"text\" name=\"name\"><input type=\"submit\" value=\"search\"></form></body></html>", "e": 5696, "s": 5554, "text": null }, { "code": null, "e": 5701, "s": 5696, "text": "Java" }, { "code": "// Servlet class to redirect the text keyword// in the 'name' field to google.com// using sendRedirect()import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse; public class MySearcher extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String name = request.getParameter(\"name\"); response.sendRedirect(\"https://www.google.co.in/#q=\" + name); // response redirected to google.com }}", "e": 6400, "s": 5701, "text": null }, { "code": null, "e": 6409, "s": 6400, "text": "web.xml " }, { "code": null, "e": 6414, "s": 6409, "text": "html" }, { "code": "<web-app><servlet><servlet-name>MySearcher</servlet-name><servlet-class>MySearcher</servlet-class></servlet> <servlet-mapping><servlet-name>MySearcher</servlet-name><url-pattern>/search</url-pattern></servlet-mapping> <welcome-file-list> <welcome-file>index.html</welcome-file> </welcome-file-list> </web-app> ", "e": 6730, "s": 6414, "text": null }, { "code": null, "e": 6738, "s": 6730, "text": "Output:" }, { "code": null, "e": 6750, "s": 6738, "text": "index.html " }, { "code": null, "e": 6765, "s": 6750, "text": "Search result " }, { "code": null, "e": 6878, "s": 6765, "text": "What is the difference between forward() method of RequestDiispatcher and sendRedirect() of HttpServletResponse?" }, { "code": null, "e": 6999, "s": 6878, "text": "Although the two methods appear to do the same thing, there are still differences between the two, which are as follows:" }, { "code": null, "e": 7014, "s": 6999, "text": "akshaychopra96" }, { "code": null, "e": 7023, "s": 7014, "text": "sooda367" }, { "code": null, "e": 7036, "s": 7023, "text": "java-servlet" }, { "code": null, "e": 7041, "s": 7036, "text": "Java" }, { "code": null, "e": 7046, "s": 7041, "text": "Java" } ]
Legendre’s formula (Given p and n, find the largest x such that p^x divides n!)
05 Nov, 2021 Given an integer n and a prime number p, find the largest x such that px (p raised to power x) divides n! (factorial) Examples: Input: n = 7, p = 3 Output: x = 2 32 divides 7! and 2 is the largest such power of 3. Input: n = 10, p = 3 Output: x = 4 34 divides 10! and 4 is the largest such power of 3. n! is multiplication of {1, 2, 3, 4, ...n}.How many numbers in {1, 2, 3, 4, ..... n} are divisible by p? Every p’th number is divisible by p in {1, 2, 3, 4, ..... n}. Therefore in n!, there are ⌊n/p⌋ numbers divisible by p. So we know that the value of x (largest power of p that divides n!) is at-least ⌊n/p⌋. Can x be larger than ⌊n/p⌋ ? Yes, there may be numbers which are divisible by p2, p3, ... How many numbers in {1, 2, 3, 4, ..... n} are divisible by p2, p3, ...? There are ⌊n/(p2)⌋ numbers divisible by p2 (Every p2‘th number would be divisible). Similarly, there are ⌊n/(p3)⌋ numbers divisible by p3 and so on.What is the largest possible value of x? So the largest possible power is ⌊n/p⌋ + ⌊n/(p2)⌋ + ⌊n/(p3)⌋ + ...... Note that we add only ⌊n/(p2)⌋ only once (not twice) as one p is already considered by expression ⌊n/p⌋. Similarly, we consider ⌊n/(p3)⌋ (not thrice). Below is implementation of above idea. C++ C Java Python3 C# PHP Javascript // C++ program to find largest x such that p*x divides n!#include <iostream>using namespace std; // Returns largest power of p that divides n!int largestPower(int n, int p){ // Initialize result int x = 0; // Calculate x = n/p + n/(p^2) + n/(p^3) + .... while (n) { n /= p; x += n; } return x;} // Driver codeint main(){ int n = 10, p = 3; cout << "The largest power of "<< p << " that divides " << n << "! is "<< largestPower(n, p) << endl; return 0;} // This code is contributed by shubhamsingh10 // C program to find largest x such that p*x divides n!#include <stdio.h> // Returns largest power of p that divides n!int largestPower(int n, int p){ // Initialize result int x = 0; // Calculate x = n/p + n/(p^2) + n/(p^3) + .... while (n) { n /= p; x += n; } return x;} // Driver programint main(){ int n = 10, p = 3; printf("The largest power of %d that divides %d! is %d\n", p, n, largestPower(n, p)); return 0;} // Java program to find largest x such that p*x divides n!import java.io.*; class GFG{ // Function that returns largest power of p // that divides n! static int Largestpower(int n, int p) { // Initialize result int ans = 0; // Calculate x = n/p + n/(p^2) + n/(p^3) + .... while (n > 0) { n /= p; ans += n; } return ans; } // Driver program public static void main (String[] args) { int n = 10; int p = 3; System.out.println(" The largest power of " + p + " that divides " + n + "! is " + Largestpower(n, p)); }} # Python3 program to find largest# x such that p*x divides n! # Returns largest power of p that divides n!def largestPower(n, p): # Initialize result x = 0 # Calculate x = n/p + n/(p^2) + n/(p^3) + .... while n: n /= p x += n return x # Driver programn = 10; p = 3print ("The largest power of %d that divides %d! is %d\n"% (p, n, largestPower(n, p))) # This code is contributed by Shreyanshi Arun. // C# program to find largest x// such that p * x divides n!using System; public class GFG{ // Function that returns largest // power of p that divides n! static int Largestpower(int n, int p) { // Initialize result int ans = 0; // Calculate x = n / p + n / (p ^ 2) + // n / (p ^ 3) + .... while (n > 0) { n /= p; ans += n; } return ans; } // Driver Code public static void Main () { int n = 10; int p = 3; Console.Write(" The largest power of " + p + " that divides " + n + "! is " + Largestpower(n, p)); }} // This code is contributed by Sam007 <?php// PHP program to find largest// x such that p*x divides n! // Returns largest power// of p that divides n!function largestPower($n, $p){ // Initialize result $x = 0; // Calculate x = n/p + // n/(p^2) + n/(p^3) + .... while ($n) { $n = (int)$n / $p; $x += $n; } return floor($x);} // Driver Code$n = 10;$p = 3;echo "The largest power of ", $p ;echo " that divides ",$n , "! is ";echo largestPower($n, $p); // This code is contributed by ajit?> <script>// Javascript program to find largest// x such that p*x divides n! // Returns largest power// of p that divides n!function largestPower(n, p){ // Initialize result let x = 0; // Calculate x = n/p + // n/(p^2) + n/(p^3) + .... while (n) { n = parseInt(n / p); x += n; } return Math.floor(x);} // Driver Codelet n = 10;let p = 3;document.write("The largest power of " + p);document.write(" that divides " + n + "! is ");document.write(largestPower(n, p)); // This code is contributed by _saurabh_jaiswal</script> Output: The largest power of 3 that divides 10! is 4 Time complexity: O(logpn) Auxiliary Space: O(1)What to do if p is not prime? We can find all prime factors of p and compute result for every prime factor. Refer Largest power of k in n! (factorial) where k may not be prime for details.Source: http://e-maxx.ru/algo/factorial_divisorsThis article is contributed by Ankur. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Sam007 jit_t SHUBHAMSINGH10 _saurabh_jaiswal subham348 factorial number-theory Mathematical number-theory Mathematical factorial 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 Find minimum number of coins that make a given value Minimum number of jumps to reach end The Knight's tour problem | Backtracking-1 Algorithm to solve Rubik's Cube Program for Decimal to Binary Conversion Modulo 10^9+7 (1000000007) Modulo Operator (%) in C/C++ with Examples
[ { "code": null, "e": 54, "s": 26, "text": "\n05 Nov, 2021" }, { "code": null, "e": 184, "s": 54, "text": "Given an integer n and a prime number p, find the largest x such that px (p raised to power x) divides n! (factorial) Examples: " }, { "code": null, "e": 361, "s": 184, "text": "Input: n = 7, p = 3\nOutput: x = 2\n32 divides 7! and 2 is the largest such power of 3.\n\nInput: n = 10, p = 3\nOutput: x = 4\n34 divides 10! and 4 is the largest such power of 3." }, { "code": null, "e": 1287, "s": 363, "text": "n! is multiplication of {1, 2, 3, 4, ...n}.How many numbers in {1, 2, 3, 4, ..... n} are divisible by p? Every p’th number is divisible by p in {1, 2, 3, 4, ..... n}. Therefore in n!, there are ⌊n/p⌋ numbers divisible by p. So we know that the value of x (largest power of p that divides n!) is at-least ⌊n/p⌋. Can x be larger than ⌊n/p⌋ ? Yes, there may be numbers which are divisible by p2, p3, ... How many numbers in {1, 2, 3, 4, ..... n} are divisible by p2, p3, ...? There are ⌊n/(p2)⌋ numbers divisible by p2 (Every p2‘th number would be divisible). Similarly, there are ⌊n/(p3)⌋ numbers divisible by p3 and so on.What is the largest possible value of x? So the largest possible power is ⌊n/p⌋ + ⌊n/(p2)⌋ + ⌊n/(p3)⌋ + ...... Note that we add only ⌊n/(p2)⌋ only once (not twice) as one p is already considered by expression ⌊n/p⌋. Similarly, we consider ⌊n/(p3)⌋ (not thrice). Below is implementation of above idea. " }, { "code": null, "e": 1291, "s": 1287, "text": "C++" }, { "code": null, "e": 1293, "s": 1291, "text": "C" }, { "code": null, "e": 1298, "s": 1293, "text": "Java" }, { "code": null, "e": 1306, "s": 1298, "text": "Python3" }, { "code": null, "e": 1309, "s": 1306, "text": "C#" }, { "code": null, "e": 1313, "s": 1309, "text": "PHP" }, { "code": null, "e": 1324, "s": 1313, "text": "Javascript" }, { "code": "// C++ program to find largest x such that p*x divides n!#include <iostream>using namespace std; // Returns largest power of p that divides n!int largestPower(int n, int p){ // Initialize result int x = 0; // Calculate x = n/p + n/(p^2) + n/(p^3) + .... while (n) { n /= p; x += n; } return x;} // Driver codeint main(){ int n = 10, p = 3; cout << \"The largest power of \"<< p << \" that divides \" << n << \"! is \"<< largestPower(n, p) << endl; return 0;} // This code is contributed by shubhamsingh10", "e": 1890, "s": 1324, "text": null }, { "code": "// C program to find largest x such that p*x divides n!#include <stdio.h> // Returns largest power of p that divides n!int largestPower(int n, int p){ // Initialize result int x = 0; // Calculate x = n/p + n/(p^2) + n/(p^3) + .... while (n) { n /= p; x += n; } return x;} // Driver programint main(){ int n = 10, p = 3; printf(\"The largest power of %d that divides %d! is %d\\n\", p, n, largestPower(n, p)); return 0;}", "e": 2362, "s": 1890, "text": null }, { "code": "// Java program to find largest x such that p*x divides n!import java.io.*; class GFG{ // Function that returns largest power of p // that divides n! static int Largestpower(int n, int p) { // Initialize result int ans = 0; // Calculate x = n/p + n/(p^2) + n/(p^3) + .... while (n > 0) { n /= p; ans += n; } return ans; } // Driver program public static void main (String[] args) { int n = 10; int p = 3; System.out.println(\" The largest power of \" + p + \" that divides \" + n + \"! is \" + Largestpower(n, p)); }}", "e": 3028, "s": 2362, "text": null }, { "code": "# Python3 program to find largest# x such that p*x divides n! # Returns largest power of p that divides n!def largestPower(n, p): # Initialize result x = 0 # Calculate x = n/p + n/(p^2) + n/(p^3) + .... while n: n /= p x += n return x # Driver programn = 10; p = 3print (\"The largest power of %d that divides %d! is %d\\n\"% (p, n, largestPower(n, p))) # This code is contributed by Shreyanshi Arun.", "e": 3500, "s": 3028, "text": null }, { "code": "// C# program to find largest x// such that p * x divides n!using System; public class GFG{ // Function that returns largest // power of p that divides n! static int Largestpower(int n, int p) { // Initialize result int ans = 0; // Calculate x = n / p + n / (p ^ 2) + // n / (p ^ 3) + .... while (n > 0) { n /= p; ans += n; } return ans; } // Driver Code public static void Main () { int n = 10; int p = 3; Console.Write(\" The largest power of \" + p + \" that divides \" + n + \"! is \" + Largestpower(n, p)); }} // This code is contributed by Sam007", "e": 4214, "s": 3500, "text": null }, { "code": "<?php// PHP program to find largest// x such that p*x divides n! // Returns largest power// of p that divides n!function largestPower($n, $p){ // Initialize result $x = 0; // Calculate x = n/p + // n/(p^2) + n/(p^3) + .... while ($n) { $n = (int)$n / $p; $x += $n; } return floor($x);} // Driver Code$n = 10;$p = 3;echo \"The largest power of \", $p ;echo \" that divides \",$n , \"! is \";echo largestPower($n, $p); // This code is contributed by ajit?>", "e": 4706, "s": 4214, "text": null }, { "code": "<script>// Javascript program to find largest// x such that p*x divides n! // Returns largest power// of p that divides n!function largestPower(n, p){ // Initialize result let x = 0; // Calculate x = n/p + // n/(p^2) + n/(p^3) + .... while (n) { n = parseInt(n / p); x += n; } return Math.floor(x);} // Driver Codelet n = 10;let p = 3;document.write(\"The largest power of \" + p);document.write(\" that divides \" + n + \"! is \");document.write(largestPower(n, p)); // This code is contributed by _saurabh_jaiswal</script>", "e": 5268, "s": 4706, "text": null }, { "code": null, "e": 5278, "s": 5268, "text": "Output: " }, { "code": null, "e": 5323, "s": 5278, "text": "The largest power of 3 that divides 10! is 4" }, { "code": null, "e": 5349, "s": 5323, "text": "Time complexity: O(logpn)" }, { "code": null, "e": 5770, "s": 5349, "text": "Auxiliary Space: O(1)What to do if p is not prime? We can find all prime factors of p and compute result for every prime factor. Refer Largest power of k in n! (factorial) where k may not be prime for details.Source: http://e-maxx.ru/algo/factorial_divisorsThis article is contributed by Ankur. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 5777, "s": 5770, "text": "Sam007" }, { "code": null, "e": 5783, "s": 5777, "text": "jit_t" }, { "code": null, "e": 5798, "s": 5783, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 5815, "s": 5798, "text": "_saurabh_jaiswal" }, { "code": null, "e": 5825, "s": 5815, "text": "subham348" }, { "code": null, "e": 5835, "s": 5825, "text": "factorial" }, { "code": null, "e": 5849, "s": 5835, "text": "number-theory" }, { "code": null, "e": 5862, "s": 5849, "text": "Mathematical" }, { "code": null, "e": 5876, "s": 5862, "text": "number-theory" }, { "code": null, "e": 5889, "s": 5876, "text": "Mathematical" }, { "code": null, "e": 5899, "s": 5889, "text": "factorial" }, { "code": null, "e": 5997, "s": 5899, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6021, "s": 5997, "text": "Merge two sorted arrays" }, { "code": null, "e": 6042, "s": 6021, "text": "Operators in C / C++" }, { "code": null, "e": 6056, "s": 6042, "text": "Prime Numbers" }, { "code": null, "e": 6109, "s": 6056, "text": "Find minimum number of coins that make a given value" }, { "code": null, "e": 6146, "s": 6109, "text": "Minimum number of jumps to reach end" }, { "code": null, "e": 6189, "s": 6146, "text": "The Knight's tour problem | Backtracking-1" }, { "code": null, "e": 6221, "s": 6189, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 6262, "s": 6221, "text": "Program for Decimal to Binary Conversion" }, { "code": null, "e": 6289, "s": 6262, "text": "Modulo 10^9+7 (1000000007)" } ]
Different Methods to Read a Character in C#
26 May, 2020 In C#, we know that Console.Read() method is used to read a single character from the standard output device. And also there are different methods available to read the single character. Following methods can be used for this purpose: Console.ReadLine()[0] Method Console.ReadKey().KeyChar Method Char.TryParse() Method Convert.ToChar() Method Since, the Console.ReadLine() method is used to reads a string and string is the set of characters. So the first character can be extract using 0th Index. Thus Console.ReadLine()[0] can be used to read a single/first character. Syntax: char_variable = Console.ReadLine()[0]; Example: Read a character using Console.ReadLine()[0] C# // C# program to Read a character// using Console.ReadLine()[0] using System; public class GFG{ // Main Method static void Main(string[] args) { char chr; // use of Console.ReadLine()[0] method chr = Console.ReadLine()[0]; // printing the input character Console.Write(chr); }} Console Input: Geeks Output: G Since, the Console.ReadKey() method is used to obtain the next character or function key pressed by the user. And the KeyChar is used to get the Unicode character represented by the current System.ConsoleKeyInfo object. Thus Console.ReadKey().KeyChar can be used to read a single/first character. Basically, it will read a character or a function and show it on the console but without waiting for the Enter key to press. As soon as you will enter a character output will display on the console. Syntax: char_variable = Console.ReadKey().KeyChar; Example: Read a character using Console.ReadKey().KeyChar C# // C# program to Input a character// using Console.ReadKey().KeyChar using System;using System.IO;using System.Text; public class GFG{ // Main Method static void Main(string[] args) { char chr; // use of Console.ReadKey().KeyChar method chr = Console.ReadKey().KeyChar; // printing the input character Console.WriteLine(chr); }} Console Input: G Output: GG Char.TryParse() method is used to read a character and it also handles the exception. It will throw an error if any input value not a character. It also returns the input status as true for valid character and false for invalid characters. Syntax: bool result = Char.TryParse(String s, out char char_variable); Example: Read a character using Char.TryParse() C# // C# program to Read a character// using Char.TryParse() using System;using System.IO;using System.Text; public class GFG{ // Main Method static void Main(string[] args) { char chr; bool val; // use of Char.TryParse() method val = Char.TryParse(Console.ReadLine(), out chr); //printing the input character Console.WriteLine("Result: " + val); Console.WriteLine("Input character: " + chr); }} Console Input: G Output: Result: True Input character: G Convert.ToChar() method is used to convert the specified string’s value to the character. The string must be of length 1 otherwise it will throw an error. Syntax: char_variable = Convert.ToChar(string s); Example: Read a character using Convert.ToChar() C# // C# program to Read a character// using Convert.ToChar() using System;using System.IO;using System.Text; public class GFG{ // Main Method static void Main(string[] args) { char chr; // use of Convert.ToChar() method chr = Convert.ToChar(Console.ReadLine()); // printing the input character Console.WriteLine(chr); }} Console Input: G Output: G C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n26 May, 2020" }, { "code": null, "e": 264, "s": 28, "text": "In C#, we know that Console.Read() method is used to read a single character from the standard output device. And also there are different methods available to read the single character. Following methods can be used for this purpose:" }, { "code": null, "e": 293, "s": 264, "text": "Console.ReadLine()[0] Method" }, { "code": null, "e": 326, "s": 293, "text": "Console.ReadKey().KeyChar Method" }, { "code": null, "e": 349, "s": 326, "text": "Char.TryParse() Method" }, { "code": null, "e": 373, "s": 349, "text": "Convert.ToChar() Method" }, { "code": null, "e": 601, "s": 373, "text": "Since, the Console.ReadLine() method is used to reads a string and string is the set of characters. So the first character can be extract using 0th Index. Thus Console.ReadLine()[0] can be used to read a single/first character." }, { "code": null, "e": 609, "s": 601, "text": "Syntax:" }, { "code": null, "e": 649, "s": 609, "text": "char_variable = Console.ReadLine()[0];\n" }, { "code": null, "e": 703, "s": 649, "text": "Example: Read a character using Console.ReadLine()[0]" }, { "code": null, "e": 706, "s": 703, "text": "C#" }, { "code": "// C# program to Read a character// using Console.ReadLine()[0] using System; public class GFG{ // Main Method static void Main(string[] args) { char chr; // use of Console.ReadLine()[0] method chr = Console.ReadLine()[0]; // printing the input character Console.Write(chr); }}", "e": 1071, "s": 706, "text": null }, { "code": null, "e": 1088, "s": 1073, "text": "Console Input:" }, { "code": null, "e": 1095, "s": 1088, "text": "Geeks\n" }, { "code": null, "e": 1103, "s": 1095, "text": "Output:" }, { "code": null, "e": 1106, "s": 1103, "text": "G\n" }, { "code": null, "e": 1602, "s": 1106, "text": "Since, the Console.ReadKey() method is used to obtain the next character or function key pressed by the user. And the KeyChar is used to get the Unicode character represented by the current System.ConsoleKeyInfo object. Thus Console.ReadKey().KeyChar can be used to read a single/first character. Basically, it will read a character or a function and show it on the console but without waiting for the Enter key to press. As soon as you will enter a character output will display on the console." }, { "code": null, "e": 1610, "s": 1602, "text": "Syntax:" }, { "code": null, "e": 1654, "s": 1610, "text": "char_variable = Console.ReadKey().KeyChar;\n" }, { "code": null, "e": 1712, "s": 1654, "text": "Example: Read a character using Console.ReadKey().KeyChar" }, { "code": null, "e": 1715, "s": 1712, "text": "C#" }, { "code": "// C# program to Input a character// using Console.ReadKey().KeyChar using System;using System.IO;using System.Text; public class GFG{ // Main Method static void Main(string[] args) { char chr; // use of Console.ReadKey().KeyChar method chr = Console.ReadKey().KeyChar; // printing the input character Console.WriteLine(chr); }}", "e": 2131, "s": 1715, "text": null }, { "code": null, "e": 2148, "s": 2133, "text": "Console Input:" }, { "code": null, "e": 2150, "s": 2148, "text": "G" }, { "code": null, "e": 2158, "s": 2150, "text": "Output:" }, { "code": null, "e": 2161, "s": 2158, "text": "GG" }, { "code": null, "e": 2401, "s": 2161, "text": "Char.TryParse() method is used to read a character and it also handles the exception. It will throw an error if any input value not a character. It also returns the input status as true for valid character and false for invalid characters." }, { "code": null, "e": 2409, "s": 2401, "text": "Syntax:" }, { "code": null, "e": 2473, "s": 2409, "text": "bool result = Char.TryParse(String s, out char char_variable);\n" }, { "code": null, "e": 2521, "s": 2473, "text": "Example: Read a character using Char.TryParse()" }, { "code": null, "e": 2524, "s": 2521, "text": "C#" }, { "code": "// C# program to Read a character// using Char.TryParse() using System;using System.IO;using System.Text; public class GFG{ // Main Method static void Main(string[] args) { char chr; bool val; // use of Char.TryParse() method val = Char.TryParse(Console.ReadLine(), out chr); //printing the input character Console.WriteLine(\"Result: \" + val); Console.WriteLine(\"Input character: \" + chr); }}", "e": 3018, "s": 2524, "text": null }, { "code": null, "e": 3035, "s": 3020, "text": "Console Input:" }, { "code": null, "e": 3038, "s": 3035, "text": "G\n" }, { "code": null, "e": 3046, "s": 3038, "text": "Output:" }, { "code": null, "e": 3079, "s": 3046, "text": "Result: True\nInput character: G\n" }, { "code": null, "e": 3234, "s": 3079, "text": "Convert.ToChar() method is used to convert the specified string’s value to the character. The string must be of length 1 otherwise it will throw an error." }, { "code": null, "e": 3242, "s": 3234, "text": "Syntax:" }, { "code": null, "e": 3285, "s": 3242, "text": "char_variable = Convert.ToChar(string s);\n" }, { "code": null, "e": 3334, "s": 3285, "text": "Example: Read a character using Convert.ToChar()" }, { "code": null, "e": 3337, "s": 3334, "text": "C#" }, { "code": "// C# program to Read a character// using Convert.ToChar() using System;using System.IO;using System.Text; public class GFG{ // Main Method static void Main(string[] args) { char chr; // use of Convert.ToChar() method chr = Convert.ToChar(Console.ReadLine()); // printing the input character Console.WriteLine(chr); }}", "e": 3741, "s": 3337, "text": null }, { "code": null, "e": 3758, "s": 3743, "text": "Console Input:" }, { "code": null, "e": 3761, "s": 3758, "text": "G\n" }, { "code": null, "e": 3769, "s": 3761, "text": "Output:" }, { "code": null, "e": 3772, "s": 3769, "text": "G\n" }, { "code": null, "e": 3775, "s": 3772, "text": "C#" } ]
Python | Print all the common elements of two lists
21 Feb, 2022 Given two lists, print all the common elements of two lists. Examples: Input : list1 = [1, 2, 3, 4, 5] list2 = [5, 6, 7, 8, 9] Output : {5} Explanation: The common elements of both the lists are 3 and 4 Input : list1 = [1, 2, 3, 4, 5] list2 = [6, 7, 8, 9] Output : No common elements Explanation: They do not have any elements in common in between them Convert the lists to sets and then print set1&set2. set1&set2 returns the common elements set, where set1 is the list1 and set2 is the list2. Below is the Python3 implementation of the above approach: Python3 # Python program to find the common elements# in two listsdef common_member(a, b): a_set = set(a) b_set = set(b) if (a_set & b_set): print(a_set & b_set) else: print("No common elements") a = [1, 2, 3, 4, 5]b = [5, 6, 7, 8, 9]common_member(a, b) a = [1, 2, 3, 4, 5]b = [6, 7, 8, 9]common_member(a, b) Output: {5} No common elements Convert the list to set by conversion. Use the intersection function to check if both sets have any elements in common. If they have many elements in common, then print the intersection of both sets. Below is the Python3 implementation of the above approach: Python3 # Python program to find common elements in# both sets using intersection function in# sets # functiondef common_member(a, b): a_set = set(a) b_set = set(b) # check length if len(a_set.intersection(b_set)) > 0: return(a_set.intersection(b_set)) else: return("no common elements") a = [1, 2, 3, 4, 5]b = [5, 6, 7, 8, 9]print(common_member(a, b)) a =[1, 2, 3, 4, 5]b =[6, 7, 8, 9]print(common_member(a, b)) Output: {5} No common elements Method 3 : Using for loop def common_member(a, b): result = [i for i in a if i in b] return result a = [1, 2, 3, 4, 5] b = [5, 6, 7, 8, 9] print("The common elements in the two lists are: ") print(common_member(a, b)) Akanksha_Rai bhairavimec aryangarg248 smiti139 Python list-programs python-list Python python-list Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Python OOPs Concepts
[ { "code": null, "e": 53, "s": 25, "text": "\n21 Feb, 2022" }, { "code": null, "e": 116, "s": 53, "text": "Given two lists, print all the common elements of two lists. " }, { "code": null, "e": 126, "s": 116, "text": "Examples:" }, { "code": null, "e": 431, "s": 126, "text": "Input : list1 = [1, 2, 3, 4, 5] \n list2 = [5, 6, 7, 8, 9]\nOutput : {5}\nExplanation: The common elements of \nboth the lists are 3 and 4 \n\nInput : list1 = [1, 2, 3, 4, 5] \n list2 = [6, 7, 8, 9]\nOutput : No common elements \nExplanation: They do not have any \nelements in common in between them" }, { "code": null, "e": 638, "s": 435, "text": "Convert the lists to sets and then print set1&set2. set1&set2 returns the common elements set, where set1 is the list1 and set2 is the list2. Below is the Python3 implementation of the above approach: " }, { "code": null, "e": 646, "s": 638, "text": "Python3" }, { "code": "# Python program to find the common elements# in two listsdef common_member(a, b): a_set = set(a) b_set = set(b) if (a_set & b_set): print(a_set & b_set) else: print(\"No common elements\") a = [1, 2, 3, 4, 5]b = [5, 6, 7, 8, 9]common_member(a, b) a = [1, 2, 3, 4, 5]b = [6, 7, 8, 9]common_member(a, b)", "e": 986, "s": 646, "text": null }, { "code": null, "e": 995, "s": 986, "text": "Output: " }, { "code": null, "e": 1018, "s": 995, "text": "{5}\nNo common elements" }, { "code": null, "e": 1281, "s": 1020, "text": "Convert the list to set by conversion. Use the intersection function to check if both sets have any elements in common. If they have many elements in common, then print the intersection of both sets. Below is the Python3 implementation of the above approach: " }, { "code": null, "e": 1289, "s": 1281, "text": "Python3" }, { "code": "# Python program to find common elements in# both sets using intersection function in# sets # functiondef common_member(a, b): a_set = set(a) b_set = set(b) # check length if len(a_set.intersection(b_set)) > 0: return(a_set.intersection(b_set)) else: return(\"no common elements\") a = [1, 2, 3, 4, 5]b = [5, 6, 7, 8, 9]print(common_member(a, b)) a =[1, 2, 3, 4, 5]b =[6, 7, 8, 9]print(common_member(a, b))", "e": 1740, "s": 1289, "text": null }, { "code": null, "e": 1749, "s": 1740, "text": "Output: " }, { "code": null, "e": 1772, "s": 1749, "text": "{5}\nNo common elements" }, { "code": null, "e": 1798, "s": 1772, "text": "Method 3 : Using for loop" }, { "code": null, "e": 2000, "s": 1798, "text": "def common_member(a, b):\n result = [i for i in a if i in b]\n return result\n\na = [1, 2, 3, 4, 5]\nb = [5, 6, 7, 8, 9]\n\nprint(\"The common elements in the two lists are: \")\nprint(common_member(a, b))" }, { "code": null, "e": 2013, "s": 2000, "text": "Akanksha_Rai" }, { "code": null, "e": 2025, "s": 2013, "text": "bhairavimec" }, { "code": null, "e": 2038, "s": 2025, "text": "aryangarg248" }, { "code": null, "e": 2047, "s": 2038, "text": "smiti139" }, { "code": null, "e": 2068, "s": 2047, "text": "Python list-programs" }, { "code": null, "e": 2080, "s": 2068, "text": "python-list" }, { "code": null, "e": 2087, "s": 2080, "text": "Python" }, { "code": null, "e": 2099, "s": 2087, "text": "python-list" }, { "code": null, "e": 2197, "s": 2099, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2215, "s": 2197, "text": "Python Dictionary" }, { "code": null, "e": 2257, "s": 2215, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2279, "s": 2257, "text": "Enumerate() in Python" }, { "code": null, "e": 2314, "s": 2279, "text": "Read a file line by line in Python" }, { "code": null, "e": 2340, "s": 2314, "text": "Python String | replace()" }, { "code": null, "e": 2372, "s": 2340, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2401, "s": 2372, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2428, "s": 2401, "text": "Python Classes and Objects" }, { "code": null, "e": 2458, "s": 2428, "text": "Iterate over a list in Python" } ]
Convert files from jpg to png and vice versa using Python
21 Sep, 2021 Prerequisite: Pillow Library Sometime it is required to attach the Image where we required image file with the specified extension. And we have the image with the different extension which needs to be converted with specified extension like in this we will convert the image having Extension of PNG to JPG and Vice-Versa And Also we will be creating the GUI interface to the Code so we will require the Library tkinter Tkinter is a Python binding to the Tk GUI toolkit. It is the standard Python interface to the Tk GUI toolkit, and is Python’s de facto standard GUI. Follow the below Steps: Step 1: Import the library. from PIL import Image Step 2: JPG to PNG To convert the image From JPG to PNG : {Syntax} img = Image.open("Image.jpg") img.save("Image.png") Step 3: PNG → JPG To convert the Image From PNG to JPG img = Image.open("Image.png") img.save("Image.jpg") Adding the GUI interface from tkinter import * Approach: In Function jpg_to_png we first Check whether The Selecting the image is in the same Format (.jpg) which to convert to .png if not then return Error.Else Convert the image the to .pngTo open the Image we use the Function in tkinter called the FileDialog which helps to open the image from the folderfrom tkinter import filedialog as fdSame Approach for the PNG to JPG In Function jpg_to_png we first Check whether The Selecting the image is in the same Format (.jpg) which to convert to .png if not then return Error. Else Convert the image the to .png To open the Image we use the Function in tkinter called the FileDialog which helps to open the image from the folderfrom tkinter import filedialog as fd Same Approach for the PNG to JPG Below is the Implementation: Python3 # import all prerequisitefrom tkinter import *from tkinter import filedialog as fdimport osfrom PIL import Imagefrom tkinter import messagebox root = Tk() # naming the GUI interface to image_conversion_APProot.title("Image_Conversion_App") # creating the Function which converts the jpg_to_pngdef jpg_to_png(): global im1 # import the image from the folder import_filename = fd.askopenfilename() if import_filename.endswith(".jpg"): im1 = Image.open(import_filename) # after converting the image save to desired # location with the Extersion .png export_filename = fd.asksaveasfilename(defaultextension=".png") im1.save(export_filename) # displaying the Messaging box with the Success messagebox.showinfo("success ", "your Image converted to Png") else: # if Image select is not with the Format of .jpg # then display the Error Label_2 = Label(root, text="Error!", width=20, fg="red", font=("bold", 15)) Label_2.place(x=80, y=280) messagebox.showerror("Fail!!", "Something Went Wrong...") def png_to_jpg(): global im1 import_filename = fd.askopenfilename() if import_filename.endswith(".png"): im1 = Image.open(import_filename) export_filename = fd.asksaveasfilename(defaultextension=".jpg") im1.save(export_filename) messagebox.showinfo("success ", "your Image converted to jpg ") else: Label_2 = Label(root, text="Error!", width=20, fg="red", font=("bold", 15)) Label_2.place(x=80, y=280) messagebox.showerror("Fail!!", "Something Went Wrong...") button1 = Button(root, text="JPG_to_PNG", width=20, height=2, bg="green", fg="white", font=("helvetica", 12, "bold"), command=jpg_to_png) button1.place(x=120, y=120) button2 = Button(root, text="PNG_to_JPEG", width=20, height=2, bg="green", fg="white", font=("helvetica", 12, "bold"), command=png_to_jpg) button2.place(x=120, y=220)root.geometry("500x500+400+200")root.mainloop() Output: sooda367 sweetyty Python-pil 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": "\n21 Sep, 2021" }, { "code": null, "e": 84, "s": 54, "text": "Prerequisite: Pillow Library " }, { "code": null, "e": 376, "s": 84, "text": "Sometime it is required to attach the Image where we required image file with the specified extension. And we have the image with the different extension which needs to be converted with specified extension like in this we will convert the image having Extension of PNG to JPG and Vice-Versa" }, { "code": null, "e": 625, "s": 376, "text": "And Also we will be creating the GUI interface to the Code so we will require the Library tkinter Tkinter is a Python binding to the Tk GUI toolkit. It is the standard Python interface to the Tk GUI toolkit, and is Python’s de facto standard GUI. " }, { "code": null, "e": 649, "s": 625, "text": "Follow the below Steps:" }, { "code": null, "e": 677, "s": 649, "text": "Step 1: Import the library." }, { "code": null, "e": 699, "s": 677, "text": "from PIL import Image" }, { "code": null, "e": 718, "s": 699, "text": "Step 2: JPG to PNG" }, { "code": null, "e": 819, "s": 718, "text": "To convert the image From JPG to PNG : {Syntax}\n\nimg = Image.open(\"Image.jpg\")\nimg.save(\"Image.png\")" }, { "code": null, "e": 837, "s": 819, "text": "Step 3: PNG → JPG" }, { "code": null, "e": 927, "s": 837, "text": "To convert the Image From PNG to JPG\n\nimg = Image.open(\"Image.png\")\nimg.save(\"Image.jpg\")" }, { "code": null, "e": 952, "s": 927, "text": "Adding the GUI interface" }, { "code": null, "e": 974, "s": 952, "text": "from tkinter import *" }, { "code": null, "e": 984, "s": 974, "text": "Approach:" }, { "code": null, "e": 1352, "s": 984, "text": "In Function jpg_to_png we first Check whether The Selecting the image is in the same Format (.jpg) which to convert to .png if not then return Error.Else Convert the image the to .pngTo open the Image we use the Function in tkinter called the FileDialog which helps to open the image from the folderfrom tkinter import filedialog as fdSame Approach for the PNG to JPG" }, { "code": null, "e": 1502, "s": 1352, "text": "In Function jpg_to_png we first Check whether The Selecting the image is in the same Format (.jpg) which to convert to .png if not then return Error." }, { "code": null, "e": 1537, "s": 1502, "text": "Else Convert the image the to .png" }, { "code": null, "e": 1690, "s": 1537, "text": "To open the Image we use the Function in tkinter called the FileDialog which helps to open the image from the folderfrom tkinter import filedialog as fd" }, { "code": null, "e": 1723, "s": 1690, "text": "Same Approach for the PNG to JPG" }, { "code": null, "e": 1752, "s": 1723, "text": "Below is the Implementation:" }, { "code": null, "e": 1760, "s": 1752, "text": "Python3" }, { "code": "# import all prerequisitefrom tkinter import *from tkinter import filedialog as fdimport osfrom PIL import Imagefrom tkinter import messagebox root = Tk() # naming the GUI interface to image_conversion_APProot.title(\"Image_Conversion_App\") # creating the Function which converts the jpg_to_pngdef jpg_to_png(): global im1 # import the image from the folder import_filename = fd.askopenfilename() if import_filename.endswith(\".jpg\"): im1 = Image.open(import_filename) # after converting the image save to desired # location with the Extersion .png export_filename = fd.asksaveasfilename(defaultextension=\".png\") im1.save(export_filename) # displaying the Messaging box with the Success messagebox.showinfo(\"success \", \"your Image converted to Png\") else: # if Image select is not with the Format of .jpg # then display the Error Label_2 = Label(root, text=\"Error!\", width=20, fg=\"red\", font=(\"bold\", 15)) Label_2.place(x=80, y=280) messagebox.showerror(\"Fail!!\", \"Something Went Wrong...\") def png_to_jpg(): global im1 import_filename = fd.askopenfilename() if import_filename.endswith(\".png\"): im1 = Image.open(import_filename) export_filename = fd.asksaveasfilename(defaultextension=\".jpg\") im1.save(export_filename) messagebox.showinfo(\"success \", \"your Image converted to jpg \") else: Label_2 = Label(root, text=\"Error!\", width=20, fg=\"red\", font=(\"bold\", 15)) Label_2.place(x=80, y=280) messagebox.showerror(\"Fail!!\", \"Something Went Wrong...\") button1 = Button(root, text=\"JPG_to_PNG\", width=20, height=2, bg=\"green\", fg=\"white\", font=(\"helvetica\", 12, \"bold\"), command=jpg_to_png) button1.place(x=120, y=120) button2 = Button(root, text=\"PNG_to_JPEG\", width=20, height=2, bg=\"green\", fg=\"white\", font=(\"helvetica\", 12, \"bold\"), command=png_to_jpg) button2.place(x=120, y=220)root.geometry(\"500x500+400+200\")root.mainloop()", "e": 3837, "s": 1760, "text": null }, { "code": null, "e": 3845, "s": 3837, "text": "Output:" }, { "code": null, "e": 3854, "s": 3845, "text": "sooda367" }, { "code": null, "e": 3863, "s": 3854, "text": "sweetyty" }, { "code": null, "e": 3874, "s": 3863, "text": "Python-pil" }, { "code": null, "e": 3898, "s": 3874, "text": "Technical Scripter 2020" }, { "code": null, "e": 3905, "s": 3898, "text": "Python" }, { "code": null, "e": 3924, "s": 3905, "text": "Technical Scripter" }, { "code": null, "e": 4022, "s": 3924, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4067, "s": 4022, "text": "How to iterate through Excel rows in Python?" }, { "code": null, "e": 4117, "s": 4067, "text": "Rotate axis tick labels in Seaborn and Matplotlib" }, { "code": null, "e": 4133, "s": 4117, "text": "Deque in Python" }, { "code": null, "e": 4149, "s": 4133, "text": "Queue in Python" }, { "code": null, "e": 4171, "s": 4149, "text": "Defaultdict in Python" }, { "code": null, "e": 4213, "s": 4171, "text": "Check if element exists in list in Python" }, { "code": null, "e": 4240, "s": 4213, "text": "Python Classes and Objects" }, { "code": null, "e": 4263, "s": 4240, "text": "Bar Plot in Matplotlib" }, { "code": null, "e": 4282, "s": 4263, "text": "reduce() in Python" } ]
Hike Interview Experience
02 Sep, 2019 First Round Written Test3 sections in all. To be done in 90 minutesSection A: – 10 aptitude questions (you can find almost every question on indiabix).Section B: – 13 questions based on C skills.Section C: – 2 programming questions which were easy. 1) Reverse every K nodes in a singly linked list. 2) Find out the next greater element having same digits. 1432 -> 2134 5432 -> no greater number First Technical InterviewThe interviewer was quite cool and composed.1 He started with simple question and asked me to write the code of Quick sort but before I could start he said leave it and tell me how you will find out 3rd smallest element from an array. 2. Based on first Question, rather than an array you have a large file containing billions of number and from it you have to print Kth minimum element.3. A file containing billion of numbers in unsorted manner is given to you. At run time you will be given two integers ‘m’ and ‘n’. Now print all the numbers from file which lies in this range. He said u can use extra space, no problem with memory but time complexity should be minimum. 4. This question was new to me. He told me let’s play a game. I said okay sir :). In this game we will be given even number of cards. Each card will be having some digit written over it. Now both player will play optimally and can only choose card from either corner. He asked me to devise a strategy which would help me winning the game always.Later he asked me to prove my strategy for the general case Second Technical InterviewInterviewer asked me about chess, rules of chess and all1. He started with Knight Tour problem in which I have to print the path. Conditions wereI have to cover all the blocks in chess. I can use only 63 moves and solution must be other than backtracking.(most optimal solution). He wanted me to tell him the strategy required to prune the recursion tree. 2. Given a file which contains large number of strings.e.g.:my name is XYZ. My emansi XYZi.e. it has words and reverse of words. There can be the case where no reverse word is present He told me to print all those pair whose reverse is also present in the file. For above example output will be: {name,eman}, {is, si} Constraints were Minimum space should be used and time complexity should be minimum further he added don’t compute reverse of string at all.(He was interested in function which I will use to calculate the hash value of string). 3. He asked me what my weak point in coding is. I said finding out the corner test cases. At this he caught me and said let see how you will face your fear and give me a code and asked me to generate all the test cases for the program. Later he asked me to write code for printing a helix (spiral matrix)and write all corner test cases for it.I wrote solution for NxN but he asked me to write for NxMand do dry run for several test cases.That is how second round went ? Third Technical InterviewThe interviewer was a bit strict. In this round only single Question was asked but it took almost 1 hour.He asked do you know spell checker in micro soft word. I said yes. He said, you have newspapers of last 20 years. Use these newspapers and suggest most probable words. He gave me exampleInput: fonfor this input printOutput: foe, for, fork, fond Question seemed easy but when I started he kept adding constraints on data structures used and complexity. I used lexicographical dictionary for this but later he added two more examplehe asked me to suggest ‘con’ and ‘ion’ as most probable word for fon. Later he added another exampleBrowserBsowerr He said suggest browser for ‘Bsowerr’. He kept adding examples and constraints.My solution started from lexicographical dictionary moved to Trie Tree then to Edit Distance problem then Hashing He said why I gave you newspapers rather than Dictionary. From this I got smell of Machine learningHe wanted me to suggest on the basis of currently most frequently used words. And the Question got more complexand it ended on SUFFIX TREE. HR roundIt was telephonic round taken by the CEO of the company and asked me all HR related Questions It was a good experience. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help. Hike Interview Experiences Hike Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Google SWE Interview Experience (Google Online Coding Challenge) 2022 Samsung Interview Experience Research & Institute SRIB (Off-Campus) 2022 Amazon Interview Experience for SDE 1 Amazon Interview Experience SDE-2 (3 Years Experienced) TCS Ninja Interview Experience (2020 batch) Write It Up: Share Your Interview Experiences Samsung RnD Coding Round Questions Nagarro Interview Experience Amazon Interview Experience for SDE-1 Nagarro Interview Experience | On-Campus 2021
[ { "code": null, "e": 54, "s": 26, "text": "\n02 Sep, 2019" }, { "code": null, "e": 303, "s": 54, "text": "First Round Written Test3 sections in all. To be done in 90 minutesSection A: – 10 aptitude questions (you can find almost every question on indiabix).Section B: – 13 questions based on C skills.Section C: – 2 programming questions which were easy." }, { "code": null, "e": 353, "s": 303, "text": "1) Reverse every K nodes in a singly linked list." }, { "code": null, "e": 410, "s": 353, "text": "2) Find out the next greater element having same digits." }, { "code": null, "e": 457, "s": 410, "text": " 1432 -> 2134\n 5432 -> no greater number" }, { "code": null, "e": 717, "s": 457, "text": "First Technical InterviewThe interviewer was quite cool and composed.1 He started with simple question and asked me to write the code of Quick sort but before I could start he said leave it and tell me how you will find out 3rd smallest element from an array." }, { "code": null, "e": 1155, "s": 717, "text": "2. Based on first Question, rather than an array you have a large file containing billions of number and from it you have to print Kth minimum element.3. A file containing billion of numbers in unsorted manner is given to you. At run time you will be given two integers ‘m’ and ‘n’. Now print all the numbers from file which lies in this range. He said u can use extra space, no problem with memory but time complexity should be minimum." }, { "code": null, "e": 1561, "s": 1155, "text": "4. This question was new to me. He told me let’s play a game. I said okay sir :). In this game we will be given even number of cards. Each card will be having some digit written over it. Now both player will play optimally and can only choose card from either corner. He asked me to devise a strategy which would help me winning the game always.Later he asked me to prove my strategy for the general case " }, { "code": null, "e": 1943, "s": 1561, "text": "Second Technical InterviewInterviewer asked me about chess, rules of chess and all1. He started with Knight Tour problem in which I have to print the path. Conditions wereI have to cover all the blocks in chess. I can use only 63 moves and solution must be other than backtracking.(most optimal solution). He wanted me to tell him the strategy required to prune the recursion tree." }, { "code": null, "e": 2519, "s": 1943, "text": "2. Given a file which contains large number of strings.e.g.:my name is XYZ. My emansi XYZi.e. it has words and reverse of words. There can be the case where no reverse word is present He told me to print all those pair whose reverse is also present in the file. For above example output will be: {name,eman}, {is, si} Constraints were Minimum space should be used and time complexity should be minimum further he added don’t compute reverse of string at all.(He was interested in function which I will use to calculate the hash value of string)." }, { "code": null, "e": 2755, "s": 2519, "text": "3. He asked me what my weak point in coding is. I said finding out the corner test cases. At this he caught me and said let see how you will face your fear and give me a code and asked me to generate all the test cases for the program." }, { "code": null, "e": 2989, "s": 2755, "text": "Later he asked me to write code for printing a helix (spiral matrix)and write all corner test cases for it.I wrote solution for NxN but he asked me to write for NxMand do dry run for several test cases.That is how second round went ?" }, { "code": null, "e": 3048, "s": 2989, "text": "Third Technical InterviewThe interviewer was a bit strict." }, { "code": null, "e": 3186, "s": 3048, "text": "In this round only single Question was asked but it took almost 1 hour.He asked do you know spell checker in micro soft word. I said yes." }, { "code": null, "e": 3287, "s": 3186, "text": "He said, you have newspapers of last 20 years. Use these newspapers and suggest most probable words." }, { "code": null, "e": 3364, "s": 3287, "text": "He gave me exampleInput: fonfor this input printOutput: foe, for, fork, fond" }, { "code": null, "e": 3471, "s": 3364, "text": "Question seemed easy but when I started he kept adding constraints on data structures used and complexity." }, { "code": null, "e": 3619, "s": 3471, "text": "I used lexicographical dictionary for this but later he added two more examplehe asked me to suggest ‘con’ and ‘ion’ as most probable word for fon." }, { "code": null, "e": 3664, "s": 3619, "text": "Later he added another exampleBrowserBsowerr" }, { "code": null, "e": 3703, "s": 3664, "text": "He said suggest browser for ‘Bsowerr’." }, { "code": null, "e": 3857, "s": 3703, "text": "He kept adding examples and constraints.My solution started from lexicographical dictionary moved to Trie Tree then to Edit Distance problem then Hashing" }, { "code": null, "e": 4034, "s": 3857, "text": "He said why I gave you newspapers rather than Dictionary. From this I got smell of Machine learningHe wanted me to suggest on the basis of currently most frequently used words." }, { "code": null, "e": 4096, "s": 4034, "text": "And the Question got more complexand it ended on SUFFIX TREE." }, { "code": null, "e": 4198, "s": 4096, "text": "HR roundIt was telephonic round taken by the CEO of the company and asked me all HR related Questions" }, { "code": null, "e": 4224, "s": 4198, "text": "It was a good experience." }, { "code": null, "e": 4433, "s": 4224, "text": "If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help." }, { "code": null, "e": 4438, "s": 4433, "text": "Hike" }, { "code": null, "e": 4460, "s": 4438, "text": "Interview Experiences" }, { "code": null, "e": 4465, "s": 4460, "text": "Hike" }, { "code": null, "e": 4563, "s": 4465, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4633, "s": 4563, "text": "Google SWE Interview Experience (Google Online Coding Challenge) 2022" }, { "code": null, "e": 4706, "s": 4633, "text": "Samsung Interview Experience Research & Institute SRIB (Off-Campus) 2022" }, { "code": null, "e": 4744, "s": 4706, "text": "Amazon Interview Experience for SDE 1" }, { "code": null, "e": 4800, "s": 4744, "text": "Amazon Interview Experience SDE-2 (3 Years Experienced)" }, { "code": null, "e": 4844, "s": 4800, "text": "TCS Ninja Interview Experience (2020 batch)" }, { "code": null, "e": 4890, "s": 4844, "text": "Write It Up: Share Your Interview Experiences" }, { "code": null, "e": 4925, "s": 4890, "text": "Samsung RnD Coding Round Questions" }, { "code": null, "e": 4954, "s": 4925, "text": "Nagarro Interview Experience" }, { "code": null, "e": 4992, "s": 4954, "text": "Amazon Interview Experience for SDE-1" } ]
Loop Statements in COBOL
21 Sep, 2021 Every programming language not only has a selection construct but also one that involves iteration. With this construct, it is possible for a block of code to run repeatedly. In fact, the programmer himself can code it in by selecting a specific type of loop. Speaking of types of loops, modern programming languages offer both for and while loops while some others provide a repeat construct. While the former runs for a certain number of times as specified by the programmer, the latter can run indefinitely if the set condition is not satisfied. Here’s the Python 3 ‘for’ loop: Python3 for i in range(0,5,1): print(i) As you can tell, the numbers 0 to 4 are printed with this for-loop, as shown in the output below: 0 1 2 3 4 Now, let’s look at the ‘while’ loop in Java: Java int x = 0;while (x < 5) {System.out.println(x);x++;} You get the same output with this while loop in Java too, as shown in the output below: 0 1 2 3 4 As simple as these iterative constructs are, COBOL also provides such loop constructs. Even if the syntax might seem very different from the examples shown above. Simply put, loops in COBOL are carried out using the PERFORM verb but it has other functions that are worth mentioning here. In its simplest form, PERFORM merely transfers control to a block of code that will be executed just once. This could either be a paragraph or a section. Alternatively, it could execute several blocks of code contained in a number of consecutive paragraphs by using the PERFORM THRU construct. As for iteration constructs that are the focus of this discussion, you can use the PERFORM verb to execute a block of code, a set number of times by using the PERFORM TIMES loop. You can also set the PERFORM verb to execute blocks of code until a particular condition is satisfied by using the PERFORM UNTIL loop. Lastly, the PERFORM VARYING loop works a certain number of times and depends on the FROM BY values that we use. Let’s begin with the syntax of the simple PERFORM statement. As mentioned earlier, the PERFORM statement will execute a block of code just once in its simplest form. For this example, we have used the PERFORM statement to run the code within the AddTwoNumbers and SubtractTwoNumbers paragraphs. Cobol IDENTIFICATION DIVISION. PROGRAM-ID. ADD-SUBTRACT-NUMBERS. DATA DIVISION. WORKING-STORAGE SECTION. 01 my-var PIC 99 VALUE 12. 01 my-var2 PIC 99 VALUE 23. 01 resultAdd PIC 999. 01 resultSub PIC 99. PROCEDURE DIVISION. MAIN-PROCEDURE. PERFORM AddTwoNumbers PERFORM SubtractTwoNumbers PERFORM DisplayResult STOP RUN. AddTwoNumbers. COMPUTE resultAdd = my-var + my-var2. SubtractTwoNumbers. COMPUTE resultSub = my-var2 - my-var. DisplayResult. DISPLAY "Total: " resultAdd DISPLAY "Difference: " resultSub. END PROGRAM ADD-SUBTRACT-NUMBERS. Once the results for the operations are complete, the DisplayResult paragraph then prints the results as shown below: Total: 035 Difference: 11 Next, we will look at the syntax of the PERFORM THRU statement and how it differs from using the PERFORM statement just once. When we use the PERFORM-THRU statement, the objective is to run several paragraphs in one go. Of course, the statement has to provide the starting and the final paragraph, as shown in the code below: Cobol IDENTIFICATION DIVISION. PROGRAM-ID. ADD-SUBTRACT-NUMBERS. DATA DIVISION. WORKING-STORAGE SECTION. 01 my-var PIC 99 VALUE 12. 01 my-var2 PIC 99 VALUE 23. 01 resultAdd PIC 999. 01 resultSub PIC 99. PROCEDURE DIVISION. MAIN-PROCEDURE. PERFORM AddTwoNumbers THRU DisplayResult STOP RUN. AddTwoNumbers. COMPUTE resultAdd = my-var + my-var2. SubtractTwoNumbers. COMPUTE resultSub = my-var2 - my-var. DisplayResult. DISPLAY "Total: " resultAdd DISPLAY "Difference: " resultSub. END PROGRAM ADD-SUBTRACT-NUMBERS. As you can see, the PERFORM statement above begins by executing the code in AddTwoNumbers until it reaches the DisplayResult paragraph. Make no mistake: it follows the natural order of the paragraphs from start to finish. Not surprisingly, we obtain the same output since we used the same inputs: Total: 035 Difference: 11 This brings us to the third way by which the PERFORM verb is used in COBOL. This statement is the first way in COBOL by which we can repeat a block of code as many times as we choose to. As you can tell, we can specify the number of times – 3 times – that the block of code has to run, as shown below: Cobol IDENTIFICATION DIVISION.PROGRAM-ID. DISPLAY-HELLO.DATA DIVISION.WORKING-STORAGE SECTION. 01 my-var PIC X(6) VALUE "Hello!".PROCEDURE DIVISION.MAIN-PROCEDURE. PERFORM DisplayHello 3 TIMES STOP RUN.DisplayHello. DISPLAY my-var.END PROGRAM DISPLAY-HELLO. When you run the code, you’ll find that the string “Hello!” is displayed thrice, as shown below. That’s it. This is all there is to the PERFORM TIMES statement. Hello! Hello! Hello! Of course, the next PERFORM statement includes a pre-test or post-test to decide whether the loop should terminate or not. Now, the PERFORM UNTIL statement acts like a while loop where the statements within the loop are executed repeatedly until a value is reached. In other words, the loop terminates as soon as a certain value is reached or condition is satisfied: Cobol IDENTIFICATION DIVISION.PROGRAM-ID. DISPLAY-NUMBERS.DATA DIVISION.WORKING-STORAGE SECTION. 01 MyCounter PIC 9 VALUE 1.PROCEDURE DIVISION.MAIN-PROCEDURE. PERFORM DisplayNumbers UNTIL MyCounter > 5 STOP RUN.DisplayNumbers. DISPLAY MyCounter. COMPUTE MyCounter = MyCounter + 1.END PROGRAM DISPLAY-NUMBERS. In the example above, when the MyCounter value reaches the value of 6, the loop terminates. So, for output, what you will obtain is a list of numbers from 1 to 5, as shown below: 1 2 3 4 5 In addition to this statement, you can add the WITH TEST BEFORE and WITH TEST AFTER clauses before the UNTIL word. The former acts like a regular while loop and the latter resemble that of a do-while loop in modern languages. If you must know, the WITH TEST BEFORE clause is the default and does not need to be explicitly stated. Having said that, let us look at the PERFORM VARYING statement next. The PERFORM VARYING statement is what modern languages refer to as a for a loop. As you know, a for loop usually has a start and an end value. With each iteration, the value is incremented by a certain number until it reaches the end value. As you can see below, the PERFORM VARYING statement attempts to do just that: Cobol IDENTIFICATION DIVISION.PROGRAM-ID. DISPLAY-NUMBERS.DATA DIVISION.WORKING-STORAGE SECTION. 01 MyCounter PIC 9 VALUE 1.PROCEDURE DIVISION.MAIN-PROCEDURE. PERFORM DisplayNumbers VARYING MyCounter FROM 1 BY 1 UNTIL MyCounter > 5 STOP RUN.DisplayNumbers. DISPLAY MyCounter. END PROGRAM DISPLAY-NUMBERS. The MyCounter value begins from 1 and increments by 1 until it reaches a value that is greater than 5. So, your output displays all the numbers from 1 to 5, as shown below: 1 2 3 4 5 As you can tell, this statement is similar to the PERFORM TIMES statement but does not require us to update the MyCounter value. Finally, we will look at the GO TO statement and how it is used in COBOL. There’s a good reason why the GO TO statement has taken a lot of criticism over the past 50 years. It was the famed Dutch computer scientist Djikstra who led the debate about whether this statement is actually worth using when it comes to program control flow. Take a look at this example below: Cobol IDENTIFICATION DIVISION.PROGRAM-ID. DISPLAY-HELLO.DATA DIVISION.WORKING-STORAGE SECTION. 01 Greeting PIC A(5) VALUE "Hello".PROCEDURE DIVISION.MAIN-PROCEDURE. PERFORM DisplayHello STOP RUN.DisplayHello. DISPLAY Greeting GO TO DisplayHello. END PROGRAM DISPLAY-HELLO. The program gets caught in a never-ending loop because of the ill-placed GO TO statement in the DisplayHello paragraph and where the output prints “Hello!” an infinite number of times. At all costs, this unconditional GO TO statement is to be avoided. Of course, if you absolutely must use a GO TO statement, use one that is conditional. Here’s an example of such a GO TO statement: Cobol IDENTIFICATION DIVISION.PROGRAM-ID. DISPLAY-HELLO.DATA DIVISION.WORKING-STORAGE SECTION. 01 Greeting PIC A(5) VALUE "Hello". 01 Answer PIC A(1) VALUE "N".PROCEDURE DIVISION.MAIN-PROCEDURE. PERFORM DisplayHello STOP RUN.DisplayHello. DISPLAY Greeting DISPLAY "Terminate Greeting? (Y/N): " ACCEPT Answer IF Answer = "N" GO TO DisplayHello.END PROGRAM DISPLAY-HELLO. As you can tell, you can terminate this loop set up by the GO TO statement if you change the value of Answer to “Y” by input, as shown in the output below: Yet most experts think that it is best to avoid GO TO statements altogether and in the case of COBOL, using the PERFORM verb for loops is best. Now, that we’ve covered loops in COBOL, it shouldn’t be hard to note that the language has options for the popular repeat, while, for, and do-while loops that we see in modern languages. This is achieved by using the all-powerful PERFORM verb. Alternatively, the GO TO verb is not used much due to the issues that crop up when it is used without a condition. So, is there anything else you’d like to add when it comes to loops in COBOL? Please feel free to share your thoughts in the comments section below. Blogathon-2021 COBOL-Basics Picked Blogathon COBOL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Consensus Problem of Distributed Systems Scraping Reddit using Python Python program to convert XML to Dictionary Difference between ‘function declaration’ and ‘function expression' in JavaScript Machine Independent Code optimization in Compiler Design Difference Between Sequential, Indexed, and Relative Files in COBOL Difference Between Search and Search All in COBOL Coding Sheet in COBOL Difference between COMP and COMP3 Program Structure of COBOL
[ { "code": null, "e": 28, "s": 0, "text": "\n21 Sep, 2021" }, { "code": null, "e": 128, "s": 28, "text": "Every programming language not only has a selection construct but also one that involves iteration." }, { "code": null, "e": 289, "s": 128, "text": "With this construct, it is possible for a block of code to run repeatedly. In fact, the programmer himself can code it in by selecting a specific type of loop. " }, { "code": null, "e": 610, "s": 289, "text": "Speaking of types of loops, modern programming languages offer both for and while loops while some others provide a repeat construct. While the former runs for a certain number of times as specified by the programmer, the latter can run indefinitely if the set condition is not satisfied. Here’s the Python 3 ‘for’ loop:" }, { "code": null, "e": 618, "s": 610, "text": "Python3" }, { "code": "for i in range(0,5,1): print(i)", "e": 653, "s": 618, "text": null }, { "code": null, "e": 751, "s": 653, "text": "As you can tell, the numbers 0 to 4 are printed with this for-loop, as shown in the output below:" }, { "code": null, "e": 761, "s": 751, "text": "0\n1\n2\n3\n4" }, { "code": null, "e": 806, "s": 761, "text": "Now, let’s look at the ‘while’ loop in Java:" }, { "code": null, "e": 811, "s": 806, "text": "Java" }, { "code": "int x = 0;while (x < 5) {System.out.println(x);x++;}", "e": 864, "s": 811, "text": null }, { "code": null, "e": 952, "s": 864, "text": "You get the same output with this while loop in Java too, as shown in the output below:" }, { "code": null, "e": 962, "s": 952, "text": "0\n1\n2\n3\n4" }, { "code": null, "e": 1125, "s": 962, "text": "As simple as these iterative constructs are, COBOL also provides such loop constructs. Even if the syntax might seem very different from the examples shown above." }, { "code": null, "e": 1250, "s": 1125, "text": "Simply put, loops in COBOL are carried out using the PERFORM verb but it has other functions that are worth mentioning here." }, { "code": null, "e": 1544, "s": 1250, "text": "In its simplest form, PERFORM merely transfers control to a block of code that will be executed just once. This could either be a paragraph or a section. Alternatively, it could execute several blocks of code contained in a number of consecutive paragraphs by using the PERFORM THRU construct." }, { "code": null, "e": 1723, "s": 1544, "text": "As for iteration constructs that are the focus of this discussion, you can use the PERFORM verb to execute a block of code, a set number of times by using the PERFORM TIMES loop." }, { "code": null, "e": 1858, "s": 1723, "text": "You can also set the PERFORM verb to execute blocks of code until a particular condition is satisfied by using the PERFORM UNTIL loop." }, { "code": null, "e": 1970, "s": 1858, "text": "Lastly, the PERFORM VARYING loop works a certain number of times and depends on the FROM BY values that we use." }, { "code": null, "e": 2031, "s": 1970, "text": "Let’s begin with the syntax of the simple PERFORM statement." }, { "code": null, "e": 2265, "s": 2031, "text": "As mentioned earlier, the PERFORM statement will execute a block of code just once in its simplest form. For this example, we have used the PERFORM statement to run the code within the AddTwoNumbers and SubtractTwoNumbers paragraphs." }, { "code": null, "e": 2271, "s": 2265, "text": "Cobol" }, { "code": "IDENTIFICATION DIVISION. PROGRAM-ID. ADD-SUBTRACT-NUMBERS. DATA DIVISION. WORKING-STORAGE SECTION. 01 my-var PIC 99 VALUE 12. 01 my-var2 PIC 99 VALUE 23. 01 resultAdd PIC 999. 01 resultSub PIC 99. PROCEDURE DIVISION. MAIN-PROCEDURE. PERFORM AddTwoNumbers PERFORM SubtractTwoNumbers PERFORM DisplayResult STOP RUN. AddTwoNumbers. COMPUTE resultAdd = my-var + my-var2. SubtractTwoNumbers. COMPUTE resultSub = my-var2 - my-var. DisplayResult. DISPLAY \"Total: \" resultAdd DISPLAY \"Difference: \" resultSub. END PROGRAM ADD-SUBTRACT-NUMBERS.", "e": 2981, "s": 2271, "text": null }, { "code": null, "e": 3100, "s": 2981, "text": " Once the results for the operations are complete, the DisplayResult paragraph then prints the results as shown below:" }, { "code": null, "e": 3126, "s": 3100, "text": "Total: 035\nDifference: 11" }, { "code": null, "e": 3252, "s": 3126, "text": "Next, we will look at the syntax of the PERFORM THRU statement and how it differs from using the PERFORM statement just once." }, { "code": null, "e": 3452, "s": 3252, "text": "When we use the PERFORM-THRU statement, the objective is to run several paragraphs in one go. Of course, the statement has to provide the starting and the final paragraph, as shown in the code below:" }, { "code": null, "e": 3458, "s": 3452, "text": "Cobol" }, { "code": "IDENTIFICATION DIVISION. PROGRAM-ID. ADD-SUBTRACT-NUMBERS. DATA DIVISION. WORKING-STORAGE SECTION. 01 my-var PIC 99 VALUE 12. 01 my-var2 PIC 99 VALUE 23. 01 resultAdd PIC 999. 01 resultSub PIC 99. PROCEDURE DIVISION. MAIN-PROCEDURE. PERFORM AddTwoNumbers THRU DisplayResult STOP RUN. AddTwoNumbers. COMPUTE resultAdd = my-var + my-var2. SubtractTwoNumbers. COMPUTE resultSub = my-var2 - my-var. DisplayResult. DISPLAY \"Total: \" resultAdd DISPLAY \"Difference: \" resultSub. END PROGRAM ADD-SUBTRACT-NUMBERS.", "e": 4118, "s": 3458, "text": null }, { "code": null, "e": 4340, "s": 4118, "text": "As you can see, the PERFORM statement above begins by executing the code in AddTwoNumbers until it reaches the DisplayResult paragraph. Make no mistake: it follows the natural order of the paragraphs from start to finish." }, { "code": null, "e": 4415, "s": 4340, "text": "Not surprisingly, we obtain the same output since we used the same inputs:" }, { "code": null, "e": 4441, "s": 4415, "text": "Total: 035\nDifference: 11" }, { "code": null, "e": 4517, "s": 4441, "text": "This brings us to the third way by which the PERFORM verb is used in COBOL." }, { "code": null, "e": 4743, "s": 4517, "text": "This statement is the first way in COBOL by which we can repeat a block of code as many times as we choose to. As you can tell, we can specify the number of times – 3 times – that the block of code has to run, as shown below:" }, { "code": null, "e": 4749, "s": 4743, "text": "Cobol" }, { "code": "IDENTIFICATION DIVISION.PROGRAM-ID. DISPLAY-HELLO.DATA DIVISION.WORKING-STORAGE SECTION. 01 my-var PIC X(6) VALUE \"Hello!\".PROCEDURE DIVISION.MAIN-PROCEDURE. PERFORM DisplayHello 3 TIMES STOP RUN.DisplayHello. DISPLAY my-var.END PROGRAM DISPLAY-HELLO.", "e": 5013, "s": 4749, "text": null }, { "code": null, "e": 5174, "s": 5013, "text": "When you run the code, you’ll find that the string “Hello!” is displayed thrice, as shown below. That’s it. This is all there is to the PERFORM TIMES statement." }, { "code": null, "e": 5195, "s": 5174, "text": "Hello!\nHello!\nHello!" }, { "code": null, "e": 5318, "s": 5195, "text": "Of course, the next PERFORM statement includes a pre-test or post-test to decide whether the loop should terminate or not." }, { "code": null, "e": 5562, "s": 5318, "text": "Now, the PERFORM UNTIL statement acts like a while loop where the statements within the loop are executed repeatedly until a value is reached. In other words, the loop terminates as soon as a certain value is reached or condition is satisfied:" }, { "code": null, "e": 5568, "s": 5562, "text": "Cobol" }, { "code": "IDENTIFICATION DIVISION.PROGRAM-ID. DISPLAY-NUMBERS.DATA DIVISION.WORKING-STORAGE SECTION. 01 MyCounter PIC 9 VALUE 1.PROCEDURE DIVISION.MAIN-PROCEDURE. PERFORM DisplayNumbers UNTIL MyCounter > 5 STOP RUN.DisplayNumbers. DISPLAY MyCounter. COMPUTE MyCounter = MyCounter + 1.END PROGRAM DISPLAY-NUMBERS.", "e": 5886, "s": 5568, "text": null }, { "code": null, "e": 6065, "s": 5886, "text": "In the example above, when the MyCounter value reaches the value of 6, the loop terminates. So, for output, what you will obtain is a list of numbers from 1 to 5, as shown below:" }, { "code": null, "e": 6075, "s": 6065, "text": "1\n2\n3\n4\n5" }, { "code": null, "e": 6405, "s": 6075, "text": "In addition to this statement, you can add the WITH TEST BEFORE and WITH TEST AFTER clauses before the UNTIL word. The former acts like a regular while loop and the latter resemble that of a do-while loop in modern languages. If you must know, the WITH TEST BEFORE clause is the default and does not need to be explicitly stated." }, { "code": null, "e": 6474, "s": 6405, "text": "Having said that, let us look at the PERFORM VARYING statement next." }, { "code": null, "e": 6793, "s": 6474, "text": "The PERFORM VARYING statement is what modern languages refer to as a for a loop. As you know, a for loop usually has a start and an end value. With each iteration, the value is incremented by a certain number until it reaches the end value. As you can see below, the PERFORM VARYING statement attempts to do just that:" }, { "code": null, "e": 6799, "s": 6793, "text": "Cobol" }, { "code": "IDENTIFICATION DIVISION.PROGRAM-ID. DISPLAY-NUMBERS.DATA DIVISION.WORKING-STORAGE SECTION. 01 MyCounter PIC 9 VALUE 1.PROCEDURE DIVISION.MAIN-PROCEDURE. PERFORM DisplayNumbers VARYING MyCounter FROM 1 BY 1 UNTIL MyCounter > 5 STOP RUN.DisplayNumbers. DISPLAY MyCounter. END PROGRAM DISPLAY-NUMBERS.", "e": 7114, "s": 6799, "text": null }, { "code": null, "e": 7287, "s": 7114, "text": "The MyCounter value begins from 1 and increments by 1 until it reaches a value that is greater than 5. So, your output displays all the numbers from 1 to 5, as shown below:" }, { "code": null, "e": 7297, "s": 7287, "text": "1\n2\n3\n4\n5" }, { "code": null, "e": 7426, "s": 7297, "text": "As you can tell, this statement is similar to the PERFORM TIMES statement but does not require us to update the MyCounter value." }, { "code": null, "e": 7500, "s": 7426, "text": "Finally, we will look at the GO TO statement and how it is used in COBOL." }, { "code": null, "e": 7796, "s": 7500, "text": "There’s a good reason why the GO TO statement has taken a lot of criticism over the past 50 years. It was the famed Dutch computer scientist Djikstra who led the debate about whether this statement is actually worth using when it comes to program control flow. Take a look at this example below:" }, { "code": null, "e": 7802, "s": 7796, "text": "Cobol" }, { "code": "IDENTIFICATION DIVISION.PROGRAM-ID. DISPLAY-HELLO.DATA DIVISION.WORKING-STORAGE SECTION. 01 Greeting PIC A(5) VALUE \"Hello\".PROCEDURE DIVISION.MAIN-PROCEDURE. PERFORM DisplayHello STOP RUN.DisplayHello. DISPLAY Greeting GO TO DisplayHello. END PROGRAM DISPLAY-HELLO.", "e": 8087, "s": 7802, "text": null }, { "code": null, "e": 8339, "s": 8087, "text": "The program gets caught in a never-ending loop because of the ill-placed GO TO statement in the DisplayHello paragraph and where the output prints “Hello!” an infinite number of times. At all costs, this unconditional GO TO statement is to be avoided." }, { "code": null, "e": 8470, "s": 8339, "text": "Of course, if you absolutely must use a GO TO statement, use one that is conditional. Here’s an example of such a GO TO statement:" }, { "code": null, "e": 8476, "s": 8470, "text": "Cobol" }, { "code": "IDENTIFICATION DIVISION.PROGRAM-ID. DISPLAY-HELLO.DATA DIVISION.WORKING-STORAGE SECTION. 01 Greeting PIC A(5) VALUE \"Hello\". 01 Answer PIC A(1) VALUE \"N\".PROCEDURE DIVISION.MAIN-PROCEDURE. PERFORM DisplayHello STOP RUN.DisplayHello. DISPLAY Greeting DISPLAY \"Terminate Greeting? (Y/N): \" ACCEPT Answer IF Answer = \"N\" GO TO DisplayHello.END PROGRAM DISPLAY-HELLO.", "e": 8871, "s": 8476, "text": null }, { "code": null, "e": 9027, "s": 8871, "text": "As you can tell, you can terminate this loop set up by the GO TO statement if you change the value of Answer to “Y” by input, as shown in the output below:" }, { "code": null, "e": 9171, "s": 9027, "text": "Yet most experts think that it is best to avoid GO TO statements altogether and in the case of COBOL, using the PERFORM verb for loops is best." }, { "code": null, "e": 9530, "s": 9171, "text": "Now, that we’ve covered loops in COBOL, it shouldn’t be hard to note that the language has options for the popular repeat, while, for, and do-while loops that we see in modern languages. This is achieved by using the all-powerful PERFORM verb. Alternatively, the GO TO verb is not used much due to the issues that crop up when it is used without a condition." }, { "code": null, "e": 9679, "s": 9530, "text": "So, is there anything else you’d like to add when it comes to loops in COBOL? Please feel free to share your thoughts in the comments section below." }, { "code": null, "e": 9694, "s": 9679, "text": "Blogathon-2021" }, { "code": null, "e": 9707, "s": 9694, "text": "COBOL-Basics" }, { "code": null, "e": 9714, "s": 9707, "text": "Picked" }, { "code": null, "e": 9724, "s": 9714, "text": "Blogathon" }, { "code": null, "e": 9730, "s": 9724, "text": "COBOL" }, { "code": null, "e": 9828, "s": 9730, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 9869, "s": 9828, "text": "Consensus Problem of Distributed Systems" }, { "code": null, "e": 9898, "s": 9869, "text": "Scraping Reddit using Python" }, { "code": null, "e": 9942, "s": 9898, "text": "Python program to convert XML to Dictionary" }, { "code": null, "e": 10024, "s": 9942, "text": "Difference between ‘function declaration’ and ‘function expression' in JavaScript" }, { "code": null, "e": 10081, "s": 10024, "text": "Machine Independent Code optimization in Compiler Design" }, { "code": null, "e": 10149, "s": 10081, "text": "Difference Between Sequential, Indexed, and Relative Files in COBOL" }, { "code": null, "e": 10199, "s": 10149, "text": "Difference Between Search and Search All in COBOL" }, { "code": null, "e": 10221, "s": 10199, "text": "Coding Sheet in COBOL" }, { "code": null, "e": 10255, "s": 10221, "text": "Difference between COMP and COMP3" } ]
Sieve of Eratosthenes
07 Jun, 2022 Given a number n, print all primes smaller than or equal to n. It is also given that n is a small number. Example: Input : n =10Output : 2 3 5 7 Input : n = 20 Output: 2 3 5 7 11 13 17 19 The sieve of Eratosthenes is one of the most efficient ways to find all primes smaller than n when n is smaller than 10 million or so (Ref Wiki). Following is the algorithm to find all the prime numbers less than or equal to a given integer n by the Eratosthene’s method: When the algorithm terminates, all the numbers in the list that are not marked are prime. Explanation with Example: Let us take an example when n = 50. So we need to print all prime numbers smaller than or equal to 50. We create a list of all numbers from 2 to 50. According to the algorithm we will mark all the numbers which are divisible by 2 and are greater than or equal to the square of it. Now we move to our next unmarked number 3 and mark all the numbers which are multiples of 3 and are greater than or equal to the square of it. We move to our next unmarked number 5 and mark all multiples of 5 and are greater than or equal to the square of it. We continue this process and our final table will look like below: So the prime numbers are the unmarked ones: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47. Thanks to Krishan Kumar for providing the above explanation. Implementation: Following is the implementation of the above algorithm. In the following implementation, a boolean array arr[] of size n is used to mark multiples of prime numbers. C++ C Java Python3 C# PHP Javascript // C++ program to print all primes smaller than or equal to// n using Sieve of Eratosthenes#include <bits/stdc++.h>using namespace std; void SieveOfEratosthenes(int n){ // Create a boolean array "prime[0..n]" and initialize // all entries it as true. A value in prime[i] will // finally be false if i is Not a prime, else true. bool prime[n + 1]; memset(prime, true, sizeof(prime)); for (int p = 2; p * p <= n; p++) { // If prime[p] is not changed, then it is a prime if (prime[p] == true) { // Update all multiples of p greater than or // equal to the square of it numbers which are // multiple of p and are less than p^2 are // already been marked. for (int i = p * p; i <= n; i += p) prime[i] = false; } } // Print all prime numbers for (int p = 2; p <= n; p++) if (prime[p]) cout << p << " ";} // Driver Codeint main(){ int n = 30; cout << "Following are the prime numbers smaller " << " than or equal to " << n << endl; SieveOfEratosthenes(n); return 0;} // C program to print all primes smaller than or equal to// n using Sieve of Eratosthenes#include <stdio.h>#include <stdbool.h>#include <string.h> void SieveOfEratosthenes(int n){ // Create a boolean array "prime[0..n]" and initialize // all entries it as true. A value in prime[i] will // finally be false if i is Not a prime, else true. bool prime[n + 1]; memset(prime, true, sizeof(prime)); for (int p = 2; p * p <= n; p++) { // If prime[p] is not changed, then it is a prime if (prime[p] == true) { // Update all multiples of p greater than or // equal to the square of it numbers which are // multiple of p and are less than p^2 are // already been marked. for (int i = p * p; i <= n; i += p) prime[i] = false; } } // Print all prime numbers for (int p = 2; p <= n; p++) if (prime[p]) printf("%d ",p);} // Driver Codeint main(){ int n = 30; printf("Following are the prime numbers smaller than or equal to %d \n", n); SieveOfEratosthenes(n); return 0;} // This code is contributed by Aditya Kumar (adityakumar129) // Java program to print all primes smaller than or equal to// n using Sieve of Eratosthenes class SieveOfEratosthenes { void sieveOfEratosthenes(int n) { // Create a boolean array "prime[0..n]" and // initialize all entries it as true. A value in // prime[i] will finally be false if i is Not a // prime, else true. boolean prime[] = new boolean[n + 1]; for (int i = 0; i <= n; i++) prime[i] = true; for (int p = 2; p * p <= n; p++) { // If prime[p] is not changed, then it is a // prime if (prime[p] == true) { // Update all multiples of p greater than or // equal to the square of it numbers which // are multiple of p and are less than p^2 // are already been marked. for (int i = p * p; i <= n; i += p) prime[i] = false; } } // Print all prime numbers for (int i = 2; i <= n; i++) { if (prime[i] == true) System.out.print(i + " "); } } // Driver Code public static void main(String args[]) { int n = 30; System.out.print("Following are the prime numbers "); System.out.println("smaller than or equal to " + n); SieveOfEratosthenes g = new SieveOfEratosthenes(); g.sieveOfEratosthenes(n); }} // This code is contributed by Aditya Kumar (adityakumar129) # Python program to print all# primes smaller than or equal to# n using Sieve of Eratosthenes def SieveOfEratosthenes(n): # Create a boolean array # "prime[0..n]" and initialize # all entries it as true. # A value in prime[i] will # finally be false if i is # Not a prime, else true. prime = [True for i in range(n+1)] p = 2 while (p * p <= n): # If prime[p] is not # changed, then it is a prime if (prime[p] == True): # Update all multiples of p for i in range(p * p, n+1, p): prime[i] = False p += 1 # Print all prime numbers for p in range(2, n+1): if prime[p]: print(p) # Driver codeif __name__ == '__main__': n = 20 print("Following are the prime numbers smaller"), print("than or equal to", n) SieveOfEratosthenes(n) // C# program to print all primes// smaller than or equal to n// using Sieve of Eratosthenesusing System; namespace prime {public class GFG { public static void SieveOfEratosthenes(int n) { // Create a boolean array // "prime[0..n]" and // initialize all entries // it as true. A value in // prime[i] will finally be // false if i is Not a // prime, else true. bool[] prime = new bool[n + 1]; for (int i = 0; i <= n; i++) prime[i] = true; for (int p = 2; p * p <= n; p++) { // If prime[p] is not changed, // then it is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p * p; i <= n; i += p) prime[i] = false; } } // Print all prime numbers for (int i = 2; i <= n; i++) { if (prime[i] == true) Console.Write(i + " "); } } // Driver Code public static void Main() { int n = 30; Console.WriteLine( "Following are the prime numbers"); Console.WriteLine("smaller than or equal to " + n); SieveOfEratosthenes(n); }}} // This code is contributed by Sam007. <?php// php program to print all primes smaller// than or equal to n using Sieve of// Eratosthenes function SieveOfEratosthenes($n){ // Create a boolean array "prime[0..n]" // and initialize all entries it as true. // A value in prime[i] will finally be // false if i is Not a prime, else true. $prime = array_fill(0, $n+1, true); for ($p = 2; $p*$p <= $n; $p++) { // If prime[p] is not changed, // then it is a prime if ($prime[$p] == true) { // Update all multiples of p for ($i = $p*$p; $i <= $n; $i += $p) $prime[$i] = false; } } // Print all prime numbers for ($p = 2; $p <= $n; $p++) if ($prime[$p]) echo $p." ";} // Driver Code $n = 30; echo "Following are the prime numbers " ."smaller than or equal to " .$n."\n" ; SieveOfEratosthenes($n); // This code is contributed by mits?> <script> // javascript program to print all// primes smaller than or equal to// n using Sieve of Eratosthenes function sieveOfEratosthenes(n){ // Create a boolean array // "prime[0..n]" and // initialize all entries // it as true. A value in // prime[i] will finally be // false if i is Not a // prime, else true. prime = Array.from({length: n+1}, (_, i) => true); for (p = 2; p * p <= n; p++) { // If prime[p] is not changed, then it is a // prime if (prime[p] == true) { // Update all multiples of p for (i = p * p; i <= n; i += p) prime[i] = false; } } // Print all prime numbers for (i = 2; i <= n; i++) { if (prime[i] == true) document.write(i + " "); }} // Driver Codevar n = 30;document.write( "Following are the prime numbers ");document.write("smaller than or equal to " + n+"<br>");sieveOfEratosthenes(n); // This code is contributed by 29AjayKumar </script> Time Complexity: O(n*log(log(n))) Auxiliary Space: O(n) C++ Java Python3 C# Javascript // the following implementation// stores only halves of odd numbers// the algorithm is a faster by some constant factors #include <bitset>#include <iostream>using namespace std; bitset<500001> Primes;void SieveOfEratosthenes(int n){ Primes[0] = 1; for (int i = 3; i*i <= n; i += 2) { if (Primes[i / 2] == 0) { for (int j = 3 * i; j <= n; j += 2 * i) Primes[j / 2] = 1; } }} int main(){ int n = 100; SieveOfEratosthenes(n); for (int i = 1; i <= n; i++) { if (i == 2) cout << i << ' '; else if (i % 2 == 1 && Primes[i / 2] == 0) cout << i << ' '; } return 0;} // Java program for the above approachimport java.io.*;public class GFG { static int[] Primes = new int[500001]; static void SieveOfEratosthenes(int n) { Primes[0] = 1; for (int i = 3; i * i <= n; i += 2) { if (Primes[i / 2] == 0) { for (int j = 3 * i; j <= n; j += 2 * i) Primes[j / 2] = 1; } } } // Driver Code public static void main(String[] args) { int n = 100; SieveOfEratosthenes(n); for (int i = 1; i <= n; i++) { if (i == 2) System.out.print(i + " "); else if (i % 2 == 1 && Primes[i / 2] == 0) System.out.print(i + " "); } }} // This code is contributed by ukasp. # Python program for the above approachPrimes = [0] * 500001def SieveOfEratosthenes(n) : Primes[0] = 1 i = 3 while(i*i <= n) : if (Primes[i // 2] == 0) : for j in range(3 * i, n+1, 2 * i) : Primes[j // 2] = 1 i += 2 # Driver Codeif __name__ == "__main__": n = 100 SieveOfEratosthenes(n) for i in range(1, n+1) : if (i == 2) : print( i, end = " ") elif (i % 2 == 1 and Primes[i // 2] == 0) : print( i, end = " ") # This code is contributed by code_hunt. // C# program for the above approachusing System;public class GFG { static int[] Primes = new int[500001]; static void SieveOfEratosthenes(int n) { Primes[0] = 1; for (int i = 3; i*i <= n; i += 2) { if (Primes[i / 2] == 0) { for (int j = 3 * i; j <= n; j += 2 * i) Primes[j / 2] = 1; } } } // Driver Code public static void Main(String[] args) { int n = 100; SieveOfEratosthenes(n); for (int i = 1; i <= n; i++) { if (i == 2) Console.Write(i + " "); else if (i % 2 == 1 && Primes[i / 2] == 0) Console.Write(i + " "); } }} // This code is contributed by sanjoy_62. // A JavaScript Program// the following implementation// stores only halves of odd numbers// the algorithm is a faster by some constant factors let Primes = new Array(500001).fill(0); function SieveOfEratosthenes(n){ Primes[0] = 1; for (let i = 3; i*i <= n; i += 2) { if (Primes[Math.floor(i / 2)] == 0) { for (let j = 3 * i; j <= n; j += 2 * i){ Primes[Math.floor(j / 2)] = 1; } } }} let n = 100;SieveOfEratosthenes(n);let res = "";for (let i = 1; i <= n; i++) { if (i == 2){ res = res + i + " "; } else if (i % 2 == 1 && Primes[Math.floor(i / 2)] == 0){ res = res + i + " "; }}console.log(res); // The code is contributed by Gautam goel (gautamgoel962) You may also like to see : How is the time complexity of Sieve of Eratosthenes is n*log(log(n))? Segmented Sieve. Sieve of Eratosthenes in 0(n) time complexity Auxiliary Space: O(1) Mithun Kumar radhesh shivamnayak diwakarjaiswal880 vsasvipul siddhantj17 mrmgssingh 29AjayKumar subham348 davidgatea21 januszeko simranarora5sos rushil1904 sanjoy_62 dangerahead pt7957 ukasp adityakumar129 code_hunt rishavnitro gautamgoel962 GE MAQ Software number-theory Prime Number Qualcomm sieve VMWare Dynamic Programming Mathematical VMWare MAQ Software Qualcomm GE number-theory Dynamic Programming Mathematical Prime Number sieve Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Largest Sum Contiguous Subarray Program for Fibonacci numbers 0-1 Knapsack Problem | DP-10 Longest Common Subsequence | DP-4 Subset Sum Problem | DP-25 Program for Fibonacci numbers 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
[ { "code": null, "e": 54, "s": 26, "text": "\n07 Jun, 2022" }, { "code": null, "e": 161, "s": 54, "text": "Given a number n, print all primes smaller than or equal to n. It is also given that n is a small number. " }, { "code": null, "e": 171, "s": 161, "text": "Example: " }, { "code": null, "e": 202, "s": 171, "text": "Input : n =10Output : 2 3 5 7 " }, { "code": null, "e": 245, "s": 202, "text": "Input : n = 20 Output: 2 3 5 7 11 13 17 19" }, { "code": null, "e": 391, "s": 245, "text": "The sieve of Eratosthenes is one of the most efficient ways to find all primes smaller than n when n is smaller than 10 million or so (Ref Wiki)." }, { "code": null, "e": 607, "s": 391, "text": "Following is the algorithm to find all the prime numbers less than or equal to a given integer n by the Eratosthene’s method: When the algorithm terminates, all the numbers in the list that are not marked are prime." }, { "code": null, "e": 634, "s": 607, "text": "Explanation with Example: " }, { "code": null, "e": 738, "s": 634, "text": "Let us take an example when n = 50. So we need to print all prime numbers smaller than or equal to 50. " }, { "code": null, "e": 786, "s": 738, "text": "We create a list of all numbers from 2 to 50. " }, { "code": null, "e": 919, "s": 786, "text": "According to the algorithm we will mark all the numbers which are divisible by 2 and are greater than or equal to the square of it. " }, { "code": null, "e": 1064, "s": 919, "text": "Now we move to our next unmarked number 3 and mark all the numbers which are multiples of 3 and are greater than or equal to the square of it. " }, { "code": null, "e": 1183, "s": 1064, "text": "We move to our next unmarked number 5 and mark all multiples of 5 and are greater than or equal to the square of it. " }, { "code": null, "e": 1252, "s": 1183, "text": "We continue this process and our final table will look like below: " }, { "code": null, "e": 1352, "s": 1252, "text": "So the prime numbers are the unmarked ones: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47." }, { "code": null, "e": 1413, "s": 1352, "text": "Thanks to Krishan Kumar for providing the above explanation." }, { "code": null, "e": 1430, "s": 1413, "text": "Implementation: " }, { "code": null, "e": 1596, "s": 1430, "text": "Following is the implementation of the above algorithm. In the following implementation, a boolean array arr[] of size n is used to mark multiples of prime numbers. " }, { "code": null, "e": 1600, "s": 1596, "text": "C++" }, { "code": null, "e": 1602, "s": 1600, "text": "C" }, { "code": null, "e": 1607, "s": 1602, "text": "Java" }, { "code": null, "e": 1615, "s": 1607, "text": "Python3" }, { "code": null, "e": 1618, "s": 1615, "text": "C#" }, { "code": null, "e": 1622, "s": 1618, "text": "PHP" }, { "code": null, "e": 1633, "s": 1622, "text": "Javascript" }, { "code": "// C++ program to print all primes smaller than or equal to// n using Sieve of Eratosthenes#include <bits/stdc++.h>using namespace std; void SieveOfEratosthenes(int n){ // Create a boolean array \"prime[0..n]\" and initialize // all entries it as true. A value in prime[i] will // finally be false if i is Not a prime, else true. bool prime[n + 1]; memset(prime, true, sizeof(prime)); for (int p = 2; p * p <= n; p++) { // If prime[p] is not changed, then it is a prime if (prime[p] == true) { // Update all multiples of p greater than or // equal to the square of it numbers which are // multiple of p and are less than p^2 are // already been marked. for (int i = p * p; i <= n; i += p) prime[i] = false; } } // Print all prime numbers for (int p = 2; p <= n; p++) if (prime[p]) cout << p << \" \";} // Driver Codeint main(){ int n = 30; cout << \"Following are the prime numbers smaller \" << \" than or equal to \" << n << endl; SieveOfEratosthenes(n); return 0;}", "e": 2751, "s": 1633, "text": null }, { "code": "// C program to print all primes smaller than or equal to// n using Sieve of Eratosthenes#include <stdio.h>#include <stdbool.h>#include <string.h> void SieveOfEratosthenes(int n){ // Create a boolean array \"prime[0..n]\" and initialize // all entries it as true. A value in prime[i] will // finally be false if i is Not a prime, else true. bool prime[n + 1]; memset(prime, true, sizeof(prime)); for (int p = 2; p * p <= n; p++) { // If prime[p] is not changed, then it is a prime if (prime[p] == true) { // Update all multiples of p greater than or // equal to the square of it numbers which are // multiple of p and are less than p^2 are // already been marked. for (int i = p * p; i <= n; i += p) prime[i] = false; } } // Print all prime numbers for (int p = 2; p <= n; p++) if (prime[p]) printf(\"%d \",p);} // Driver Codeint main(){ int n = 30; printf(\"Following are the prime numbers smaller than or equal to %d \\n\", n); SieveOfEratosthenes(n); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)", "e": 3923, "s": 2751, "text": null }, { "code": "// Java program to print all primes smaller than or equal to// n using Sieve of Eratosthenes class SieveOfEratosthenes { void sieveOfEratosthenes(int n) { // Create a boolean array \"prime[0..n]\" and // initialize all entries it as true. A value in // prime[i] will finally be false if i is Not a // prime, else true. boolean prime[] = new boolean[n + 1]; for (int i = 0; i <= n; i++) prime[i] = true; for (int p = 2; p * p <= n; p++) { // If prime[p] is not changed, then it is a // prime if (prime[p] == true) { // Update all multiples of p greater than or // equal to the square of it numbers which // are multiple of p and are less than p^2 // are already been marked. for (int i = p * p; i <= n; i += p) prime[i] = false; } } // Print all prime numbers for (int i = 2; i <= n; i++) { if (prime[i] == true) System.out.print(i + \" \"); } } // Driver Code public static void main(String args[]) { int n = 30; System.out.print(\"Following are the prime numbers \"); System.out.println(\"smaller than or equal to \" + n); SieveOfEratosthenes g = new SieveOfEratosthenes(); g.sieveOfEratosthenes(n); }} // This code is contributed by Aditya Kumar (adityakumar129)", "e": 5391, "s": 3923, "text": null }, { "code": "# Python program to print all# primes smaller than or equal to# n using Sieve of Eratosthenes def SieveOfEratosthenes(n): # Create a boolean array # \"prime[0..n]\" and initialize # all entries it as true. # A value in prime[i] will # finally be false if i is # Not a prime, else true. prime = [True for i in range(n+1)] p = 2 while (p * p <= n): # If prime[p] is not # changed, then it is a prime if (prime[p] == True): # Update all multiples of p for i in range(p * p, n+1, p): prime[i] = False p += 1 # Print all prime numbers for p in range(2, n+1): if prime[p]: print(p) # Driver codeif __name__ == '__main__': n = 20 print(\"Following are the prime numbers smaller\"), print(\"than or equal to\", n) SieveOfEratosthenes(n)", "e": 6249, "s": 5391, "text": null }, { "code": "// C# program to print all primes// smaller than or equal to n// using Sieve of Eratosthenesusing System; namespace prime {public class GFG { public static void SieveOfEratosthenes(int n) { // Create a boolean array // \"prime[0..n]\" and // initialize all entries // it as true. A value in // prime[i] will finally be // false if i is Not a // prime, else true. bool[] prime = new bool[n + 1]; for (int i = 0; i <= n; i++) prime[i] = true; for (int p = 2; p * p <= n; p++) { // If prime[p] is not changed, // then it is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p * p; i <= n; i += p) prime[i] = false; } } // Print all prime numbers for (int i = 2; i <= n; i++) { if (prime[i] == true) Console.Write(i + \" \"); } } // Driver Code public static void Main() { int n = 30; Console.WriteLine( \"Following are the prime numbers\"); Console.WriteLine(\"smaller than or equal to \" + n); SieveOfEratosthenes(n); }}} // This code is contributed by Sam007.", "e": 7544, "s": 6249, "text": null }, { "code": "<?php// php program to print all primes smaller// than or equal to n using Sieve of// Eratosthenes function SieveOfEratosthenes($n){ // Create a boolean array \"prime[0..n]\" // and initialize all entries it as true. // A value in prime[i] will finally be // false if i is Not a prime, else true. $prime = array_fill(0, $n+1, true); for ($p = 2; $p*$p <= $n; $p++) { // If prime[p] is not changed, // then it is a prime if ($prime[$p] == true) { // Update all multiples of p for ($i = $p*$p; $i <= $n; $i += $p) $prime[$i] = false; } } // Print all prime numbers for ($p = 2; $p <= $n; $p++) if ($prime[$p]) echo $p.\" \";} // Driver Code $n = 30; echo \"Following are the prime numbers \" .\"smaller than or equal to \" .$n.\"\\n\" ; SieveOfEratosthenes($n); // This code is contributed by mits?>", "e": 8488, "s": 7544, "text": null }, { "code": "<script> // javascript program to print all// primes smaller than or equal to// n using Sieve of Eratosthenes function sieveOfEratosthenes(n){ // Create a boolean array // \"prime[0..n]\" and // initialize all entries // it as true. A value in // prime[i] will finally be // false if i is Not a // prime, else true. prime = Array.from({length: n+1}, (_, i) => true); for (p = 2; p * p <= n; p++) { // If prime[p] is not changed, then it is a // prime if (prime[p] == true) { // Update all multiples of p for (i = p * p; i <= n; i += p) prime[i] = false; } } // Print all prime numbers for (i = 2; i <= n; i++) { if (prime[i] == true) document.write(i + \" \"); }} // Driver Codevar n = 30;document.write( \"Following are the prime numbers \");document.write(\"smaller than or equal to \" + n+\"<br>\");sieveOfEratosthenes(n); // This code is contributed by 29AjayKumar </script>", "e": 9498, "s": 8488, "text": null }, { "code": null, "e": 9532, "s": 9498, "text": "Time Complexity: O(n*log(log(n)))" }, { "code": null, "e": 9554, "s": 9532, "text": "Auxiliary Space: O(n)" }, { "code": null, "e": 9558, "s": 9554, "text": "C++" }, { "code": null, "e": 9563, "s": 9558, "text": "Java" }, { "code": null, "e": 9571, "s": 9563, "text": "Python3" }, { "code": null, "e": 9574, "s": 9571, "text": "C#" }, { "code": null, "e": 9585, "s": 9574, "text": "Javascript" }, { "code": "// the following implementation// stores only halves of odd numbers// the algorithm is a faster by some constant factors #include <bitset>#include <iostream>using namespace std; bitset<500001> Primes;void SieveOfEratosthenes(int n){ Primes[0] = 1; for (int i = 3; i*i <= n; i += 2) { if (Primes[i / 2] == 0) { for (int j = 3 * i; j <= n; j += 2 * i) Primes[j / 2] = 1; } }} int main(){ int n = 100; SieveOfEratosthenes(n); for (int i = 1; i <= n; i++) { if (i == 2) cout << i << ' '; else if (i % 2 == 1 && Primes[i / 2] == 0) cout << i << ' '; } return 0;}", "e": 10243, "s": 9585, "text": null }, { "code": "// Java program for the above approachimport java.io.*;public class GFG { static int[] Primes = new int[500001]; static void SieveOfEratosthenes(int n) { Primes[0] = 1; for (int i = 3; i * i <= n; i += 2) { if (Primes[i / 2] == 0) { for (int j = 3 * i; j <= n; j += 2 * i) Primes[j / 2] = 1; } } } // Driver Code public static void main(String[] args) { int n = 100; SieveOfEratosthenes(n); for (int i = 1; i <= n; i++) { if (i == 2) System.out.print(i + \" \"); else if (i % 2 == 1 && Primes[i / 2] == 0) System.out.print(i + \" \"); } }} // This code is contributed by ukasp.", "e": 10900, "s": 10243, "text": null }, { "code": "# Python program for the above approachPrimes = [0] * 500001def SieveOfEratosthenes(n) : Primes[0] = 1 i = 3 while(i*i <= n) : if (Primes[i // 2] == 0) : for j in range(3 * i, n+1, 2 * i) : Primes[j // 2] = 1 i += 2 # Driver Codeif __name__ == \"__main__\": n = 100 SieveOfEratosthenes(n) for i in range(1, n+1) : if (i == 2) : print( i, end = \" \") elif (i % 2 == 1 and Primes[i // 2] == 0) : print( i, end = \" \") # This code is contributed by code_hunt.", "e": 11486, "s": 10900, "text": null }, { "code": "// C# program for the above approachusing System;public class GFG { static int[] Primes = new int[500001]; static void SieveOfEratosthenes(int n) { Primes[0] = 1; for (int i = 3; i*i <= n; i += 2) { if (Primes[i / 2] == 0) { for (int j = 3 * i; j <= n; j += 2 * i) Primes[j / 2] = 1; } } } // Driver Code public static void Main(String[] args) { int n = 100; SieveOfEratosthenes(n); for (int i = 1; i <= n; i++) { if (i == 2) Console.Write(i + \" \"); else if (i % 2 == 1 && Primes[i / 2] == 0) Console.Write(i + \" \"); } }} // This code is contributed by sanjoy_62.", "e": 12132, "s": 11486, "text": null }, { "code": "// A JavaScript Program// the following implementation// stores only halves of odd numbers// the algorithm is a faster by some constant factors let Primes = new Array(500001).fill(0); function SieveOfEratosthenes(n){ Primes[0] = 1; for (let i = 3; i*i <= n; i += 2) { if (Primes[Math.floor(i / 2)] == 0) { for (let j = 3 * i; j <= n; j += 2 * i){ Primes[Math.floor(j / 2)] = 1; } } }} let n = 100;SieveOfEratosthenes(n);let res = \"\";for (let i = 1; i <= n; i++) { if (i == 2){ res = res + i + \" \"; } else if (i % 2 == 1 && Primes[Math.floor(i / 2)] == 0){ res = res + i + \" \"; }}console.log(res); // The code is contributed by Gautam goel (gautamgoel962)", "e": 12874, "s": 12132, "text": null }, { "code": null, "e": 12903, "s": 12874, "text": "You may also like to see : " }, { "code": null, "e": 12973, "s": 12903, "text": "How is the time complexity of Sieve of Eratosthenes is n*log(log(n))?" }, { "code": null, "e": 12990, "s": 12973, "text": "Segmented Sieve." }, { "code": null, "e": 13036, "s": 12990, "text": "Sieve of Eratosthenes in 0(n) time complexity" }, { "code": null, "e": 13058, "s": 13036, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 13071, "s": 13058, "text": "Mithun Kumar" }, { "code": null, "e": 13079, "s": 13071, "text": "radhesh" }, { "code": null, "e": 13091, "s": 13079, "text": "shivamnayak" }, { "code": null, "e": 13109, "s": 13091, "text": "diwakarjaiswal880" }, { "code": null, "e": 13119, "s": 13109, "text": "vsasvipul" }, { "code": null, "e": 13131, "s": 13119, "text": "siddhantj17" }, { "code": null, "e": 13142, "s": 13131, "text": "mrmgssingh" }, { "code": null, "e": 13154, "s": 13142, "text": "29AjayKumar" }, { "code": null, "e": 13164, "s": 13154, "text": "subham348" }, { "code": null, "e": 13177, "s": 13164, "text": "davidgatea21" }, { "code": null, "e": 13187, "s": 13177, "text": "januszeko" }, { "code": null, "e": 13203, "s": 13187, "text": "simranarora5sos" }, { "code": null, "e": 13214, "s": 13203, "text": "rushil1904" }, { "code": null, "e": 13224, "s": 13214, "text": "sanjoy_62" }, { "code": null, "e": 13236, "s": 13224, "text": "dangerahead" }, { "code": null, "e": 13243, "s": 13236, "text": "pt7957" }, { "code": null, "e": 13249, "s": 13243, "text": "ukasp" }, { "code": null, "e": 13264, "s": 13249, "text": "adityakumar129" }, { "code": null, "e": 13274, "s": 13264, "text": "code_hunt" }, { "code": null, "e": 13286, "s": 13274, "text": "rishavnitro" }, { "code": null, "e": 13300, "s": 13286, "text": "gautamgoel962" }, { "code": null, "e": 13303, "s": 13300, "text": "GE" }, { "code": null, "e": 13316, "s": 13303, "text": "MAQ Software" }, { "code": null, "e": 13330, "s": 13316, "text": "number-theory" }, { "code": null, "e": 13343, "s": 13330, "text": "Prime Number" }, { "code": null, "e": 13352, "s": 13343, "text": "Qualcomm" }, { "code": null, "e": 13358, "s": 13352, "text": "sieve" }, { "code": null, "e": 13365, "s": 13358, "text": "VMWare" }, { "code": null, "e": 13385, "s": 13365, "text": "Dynamic Programming" }, { "code": null, "e": 13398, "s": 13385, "text": "Mathematical" }, { "code": null, "e": 13405, "s": 13398, "text": "VMWare" }, { "code": null, "e": 13418, "s": 13405, "text": "MAQ Software" }, { "code": null, "e": 13427, "s": 13418, "text": "Qualcomm" }, { "code": null, "e": 13430, "s": 13427, "text": "GE" }, { "code": null, "e": 13444, "s": 13430, "text": "number-theory" }, { "code": null, "e": 13464, "s": 13444, "text": "Dynamic Programming" }, { "code": null, "e": 13477, "s": 13464, "text": "Mathematical" }, { "code": null, "e": 13490, "s": 13477, "text": "Prime Number" }, { "code": null, "e": 13496, "s": 13490, "text": "sieve" }, { "code": null, "e": 13594, "s": 13496, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 13626, "s": 13594, "text": "Largest Sum Contiguous Subarray" }, { "code": null, "e": 13656, "s": 13626, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 13685, "s": 13656, "text": "0-1 Knapsack Problem | DP-10" }, { "code": null, "e": 13719, "s": 13685, "text": "Longest Common Subsequence | DP-4" }, { "code": null, "e": 13746, "s": 13719, "text": "Subset Sum Problem | DP-25" }, { "code": null, "e": 13776, "s": 13746, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 13819, "s": 13776, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 13879, "s": 13819, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 13894, "s": 13879, "text": "C++ Data Types" } ]
Number of sub arrays with odd sum
11 Jul, 2022 Given an array, find the number of subarrays whose sum is odd. Examples: Input : arr[] = {5, 4, 4, 5, 1, 3} Output : 12 There are possible subarrays with odd sum. The subarrays are 1) {5} Sum = 5 (At index 0) 2) {5, 4} Sum = 9 3) {5, 4, 4} Sum = 13 4) {5, 4, 4, 5, 1} Sum = 19 5) {4, 4, 5} Sum = 13 6) {4, 4, 5, 1, 3} Sum = 17 7) {4, 5} Sum = 9 8) {4, 5, 1, 3} Sum = 13 9) {5} Sum = 5 (At index 3) 10) {5, 1, 3} Sum = 9 11) {1} Sum = 1 12) {3} Sum = 3 O(n2) time and O(1) space method [Brute Force] We can simply generate all the possible sub-arrays and find whether the sum of all the elements in them is an odd or not. If it is odd then we will count that sub-array otherwise neglect it. C++ C Java Python3 C# PHP Javascript // C++ code to find count of sub-arrays with odd sum#include <bits/stdc++.h>using namespace std; int countOddSum(int ar[], int n){ int result = 0; // Find sum of all subarrays and increment result if sum // is odd for (int i = 0; i <= n - 1; i++) { int val = 0; for (int j = i; j <= n - 1; j++) { val = val + ar[j]; if (val % 2 != 0) result++; } } return (result);} // Driver codeint main(){ int arr[] = { 5, 4, 4, 5, 1, 3 }; int n = sizeof(arr) / sizeof(arr[0]); cout << "The Number of Subarrays with odd sum is " << countOddSum(arr, n); return (0);} // This code is contributed by Sania Kumari Gupta // C++ code to find count of sub-arrays with odd sum#include <stdio.h> int countOddSum(int ar[], int n){ int result = 0; // Find sum of all subarrays and increment result if sum // is odd for (int i = 0; i <= n - 1; i++) { int val = 0; for (int j = i; j <= n - 1; j++) { val = val + ar[j]; if (val % 2 != 0) result++; } } return (result);} // Driver codeint main(){ int arr[] = { 5, 4, 4, 5, 1, 3 }; int n = sizeof(arr) / sizeof(arr[0]); printf("The Number of Subarrays with odd sum is %d", countOddSum(arr, n)); return (0);} // This code is contributed by Sania Kumari Gupta // Java code to find count of sub-arrays with odd sumimport java.io.*; class GFG { static int countOddSum(int ar[], int n) { int result = 0; // Find sum of all subarrays and increment result if // sum is odd for (int i = 0; i <= n - 1; i++) { int val = 0; for (int j = i; j <= n - 1; j++) { val = val + ar[j]; if (val % 2 != 0) result++; } } return (result); } // Driver code public static void main(String[] args) { int ar[] = { 5, 4, 4, 5, 1, 3 }; int n = ar.length; System.out.print( "The Number of Subarrays with odd sum is "); System.out.println(countOddSum(ar, n)); }} // This code is contributed by Sania Kumari Gupta # Python 3 code to find count# of sub-arrays with odd sum def countOddSum(ar, n): result = 0 # Find sum of all subarrays and # increment result if sum is odd for i in range(n): val = 0 for j in range(i, n ): val = val + ar[j] if (val % 2 != 0): result +=1 return (result) # Driver codear = [ 5, 4, 4, 5, 1, 3 ] print("The Number of Subarrays" , "with odd", end = "") print(" sum is "+ str(countOddSum(ar, 6))) # This code is contributed# by ChitraNayal // C# code to find count// of sub-arrays with odd sumusing System; class GFG{static int countOddSum(int []ar, int n){ int result = 0; // Find sum of all subarrays // and increment result if // sum is odd for (int i = 0; i <= n - 1; i++) { int val = 0; for (int j = i; j <= n - 1; j++) { val = val + ar[j]; if (val % 2 != 0) result++; } } return (result);} // Driver codepublic static void Main(){ int []ar = {5, 4, 4, 5, 1, 3}; int n = ar.Length; Console.Write("The Number of Subarrays" + " with odd sum is "); Console.WriteLine(countOddSum(ar, n));}} // This code is contributed// by chandan_jnu. <?php// PHP code to find count// of sub-arrays with odd sum function countOddSum(&$ar, $n){ $result = 0; // Find sum of all subarrays and // increment result if sum is odd for ($i = 0; $i <= $n - 1; $i++) { $val = 0; for ($j = $i; $j <= $n - 1; $j++) { $val = $val + $ar[$j]; if ($val % 2 != 0) $result++; } } return ($result);} // Driver code$ar = array(5, 4, 4, 5, 1, 3);$n = sizeof($ar); echo "The Number of Subarrays with odd ";echo "sum is ".countOddSum($ar, $n); // This code is contributed// by ChitraNayal?> <script> // Javascript code to find count of// sub-arrays with odd sumfunction countOddSum(ar, n){ let result = 0; // Find sum of all subarrays // and increment result if // sum is odd for(let i = 0; i <= n - 1; i++) { let val = 0; for(let j = i; j <= n - 1; j++) { val = val + ar[j]; if (val % 2 != 0) result++; } } return (result);} // Driver codelet ar = [ 5, 4, 4, 5, 1, 3 ];let n = ar.length;document.write("The Number of Subarrays" + " with odd sum is "); document.write(countOddSum(ar, n)); // This code is contributed by avanitrachhadiya2155 </script> Output: The Number of Subarrays with odd sum is 12 Time Complexity: O(n2) Auxiliary Space: O(1)O(n) Time and O(1) Space Method [Efficient] If we do compute the cumulative sum array in temp[] of our input array, then we can see that the sub-array starting from i and ending at j, has an even sum if temp[] if (temp[j] – temp[i]) % 2 = 0. So, instead of building a cumulative sum array, we build a cumulative sum modulo 2 array. Then calculating odd-even pairs will give the required result i.e. temp[0]*temp[1]. C++ C Java Python3 C# PHP Javascript // C++ program to find count of sub-arrays// with odd sum#include <bits/stdc++.h>using namespace std; int countOddSum(int ar[], int n){ // A temporary array of size 2. temp[0] is going to // store count of even subarrays and temp[1] count of // odd. temp[0] is initialized as 1 because there a // single odd element is also counted as a subarray int temp[2] = { 1, 0 }; // Initialize count. sum is sum of elements under modulo // 2 and ending with arr[i]. int result = 0, val = 0; // i'th iteration computes sum of arr[0..i] under modulo // 2 and increments even/odd count according to sum's // value for (int i = 0; i <= n - 1; i++) { // 2 is added to handle negative numbers val = ((val + ar[i]) % 2 + 2) % 2; // Increment even/odd count temp[val]++; } // An odd can be formed by even-odd pair result = (temp[0] * temp[1]); return (result);} // Driver codeint main(){ int ar[] = { 5, 4, 4, 5, 1, 3 }; int n = sizeof(ar) / sizeof(ar[0]); cout << "The Number of Subarrays with odd sum is " << countOddSum(ar, n); return (0);} // This code is contributed by Sania Kumari Gupta // C++ program to find count of sub-arrays// with odd sum#include <stdio.h> int countOddSum(int ar[], int n){ // A temporary array of size 2. temp[0] is going to // store count of even subarrays and temp[1] count of // odd. temp[0] is initialized as 1 because there a // single odd element is also counted as a subarray int temp[2] = { 1, 0 }; // Initialize count. sum is sum of elements under modulo // 2 and ending with arr[i]. int result = 0, val = 0; // i'th iteration computes sum of arr[0..i] under modulo // 2 and increments even/odd count according to sum's // value for (int i = 0; i <= n - 1; i++) { // 2 is added to handle negative numbers val = ((val + ar[i]) % 2 + 2) % 2; // Increment even/odd count temp[val]++; } // An odd can be formed by even-odd pair result = (temp[0] * temp[1]); return (result);} // Driver codeint main(){ int ar[] = { 5, 4, 4, 5, 1, 3 }; int n = sizeof(ar) / sizeof(ar[0]); printf("The Number of Subarrays with odd sum is %d", countOddSum(ar, n)); return (0);} // This code is contributed by Sania Kumari Gupta // Java code to find count of sub-arrays// with odd sumimport java.io.*; class GFG { static int countOddSum(int ar[], int n) { // A temporary array of size 2. temp[0] is going to // store count of even subarrays and temp[1] count // of odd. temp[0] is initialized as 1 because there // a single odd element is also counted as a // subarray int temp[] = { 1, 0 }; // Initialize count. sum is sum of elements under // modulo 2 and ending with arr[i]. int result = 0, val = 0; // i'th iteration computes sum of arr[0..i] under // modulo 2 and increments even/odd count according // to sum's value for (int i = 0; i <= n - 1; i++) { // 2 is added to handle negative numbers val = ((val + ar[i]) % 2 + 2) % 2; // Increment even/odd count temp[val]++; } // An odd can be formed by an even-odd pair result = temp[0] * temp[1]; return (result); } // Driver code public static void main(String[] args) { int ar[] = { 5, 4, 4, 5, 1, 3 }; int n = ar.length; System.out.println( "The Number of Subarrays with odd sum is " + countOddSum(ar, n)); }} // This code is contributed by Sania Kumari Gupta # Python 3 program to # find count of sub-arrays# with odd sumdef countOddSum(ar, n): # A temporary array of size # 2. temp[0] is going to # store count of even subarrays # and temp[1] count of odd. # temp[0] is initialized as 1 # because there is a single odd # element is also counted as # a subarray temp = [ 1, 0 ] # Initialize count. sum is sum # of elements under modulo 2 # and ending with arr[i]. result = 0 val = 0 # i'th iteration computes # sum of arr[0..i] under # modulo 2 and increments # even/odd count according # to sum's value for i in range(n): # 2 is added to handle # negative numbers val = ((val + ar[i]) % 2 + 2) % 2 # Increment even/odd count temp[val] += 1 # An odd can be formed # by even-odd pair result = (temp[0] * temp[1]) return (result) # Driver codear = [ 5, 4, 4, 5, 1, 3 ] print("The Number of Subarrays" " with odd sum is "+ str(countOddSum(ar, 6))) # This code is contributed# by ChitraNayal // C# code to find count of// sub-arrays with odd sumusing System; class GFG{static int countOddSum(int[] ar, int n){ // A temporary array of size 2. // temp[0] is going to store // count of even subarrays // and temp[1] count of odd. // temp[0] is initialized as // 1 because there a single odd // element is also counted as // a subarray int[] temp = { 1, 0 }; // Initialize count. sum is // sum of elements under modulo // 2 and ending with arr[i]. int result = 0, val = 0; // i'th iteration computes sum // of arr[0..i] under modulo 2 // and increments even/odd count // according to sum's value for (int i = 0; i <= n - 1; i++) { // 2 is added to handle // negative numbers val = ((val + ar[i]) % 2 + 2) % 2; // Increment even/odd count temp[val]++; } // An odd can be formed // by an even-odd pair result = temp[0] * temp[1]; return (result);} // Driver codepublic static void Main(){ int[] ar = { 5, 4, 4, 5, 1, 3 }; int n = ar.Length; Console.Write("The Number of Subarrays" + " with odd sum is " + countOddSum(ar, n));}} // This code is contributed// by ChitraNayal <?php// PHP program to find count// of sub-arrays with odd sum function countOddSum($ar, $n){ // A temporary array of size // 2. temp[0] is going to // store count of even subarrays // and temp[1] count of odd. // temp[0] is initialized as 1 // because there is a single odd // element is also counted as // a subarray $temp = array(1, 0); // Initialize count. sum is // sum of elements under // modulo 2 and ending with arr[i]. $result = 0; $val = 0; // i'th iteration computes sum // of arr[0..i] under modulo 2 // and increments even/odd count // according to sum's value for ($i = 0; $i <= $n - 1; $i++) { // 2 is added to handle // negative numbers $val = (($val + $ar[$i]) % 2 + 2) % 2; // Increment even/odd count $temp[$val]++; } // An odd can be formed // by even-odd pair $result = ($temp[0] * $temp[1]); return ($result);} // Driver code$ar = array(5, 4, 4, 5, 1, 3);$n = sizeof($ar); echo "The Number of Subarrays with odd". " sum is ".countOddSum($ar, $n); // This code is contributed// by ChitraNayal?> <script> // Javascript code to find count of// sub-arrays with odd sumfunction countOddSum(ar, n){ // A temporary array of size 2. // temp[0] is going to store // count of even subarrays // and temp[1] count of odd. // temp[0] is initialized as // 1 because there a single odd // element is also counted as // a subarray let temp = [1, 0]; // Initialize count. sum is // sum of elements under modulo // 2 and ending with arr[i]. let result = 0, val = 0; // i'th iteration computes sum // of arr[0..i] under modulo 2 // and increments even/odd count // according to sum's value for(let i = 0; i <= n - 1; i++) { // 2 is added to handle // negative numbers val = ((val + ar[i]) % 2 + 2) % 2; // Increment even/odd count temp[val]++; } // An odd can be formed // by an even-odd pair result = temp[0] * temp[1]; return (result);} // Driver codelet ar = [ 5, 4, 4, 5, 1, 3 ];let n = ar.length; document.write("The Number of Subarrays" + " with odd sum is " + countOddSum(ar, n)); // This code is contributed by rameshtravel07 </script> Output: The Number of Subarrays with odd sum is 12 Time Complexity: O(n) Auxiliary Space: O(1)Another efficient approach is to first find the number of subarrays starting at index 0 and having an odd sum. Then traverse the array and update the number of subarrays starting at index i and having an odd sum. Below is the implementation of the above approach : C++ C Java Python3 C# Javascript // C++ program to find number of subarrays with odd sum#include <bits/stdc++.h>using namespace std; // Function to find number of subarrays with odd sumint countOddSum(int a[], int n){ // 'odd' stores number of odd numbers upto ith index // 'c_odd' stores number of odd sum subarrays starting // at ith index //'Result' stores the number of odd sum subarrays int odd = 0, c_odd = 0, result = 0; // First find number of odd sum subarrays starting at // 0th index for (int i = 0; i < n; i++) { if (a[i] & 1) odd = !odd; if (odd) c_odd++; } // Find number of odd sum subarrays starting at ith // index add to result for (int i = 0; i < n; i++) { result += c_odd; if (a[i] & 1) c_odd = (n - i - c_odd); } return result;} // Driver codeint main(){ int ar[] = { 5, 4, 4, 5, 1, 3 }; int n = sizeof(ar) / sizeof(ar[0]); cout << "The Number of Subarrays with odd sum is " << countOddSum(ar, n); return (0);} // This code is contributed by Sania Kumari Gupta // C++ program to find number of subarrays with odd sum#include <stdio.h> // Function to find number of subarrays with odd sumint countOddSum(int a[], int n){ // 'odd' stores number of odd numbers upto ith index // 'c_odd' stores number of odd sum subarrays starting // at ith index //'Result' stores the number of odd sum subarrays int odd = 0, c_odd = 0, result = 0; // First find number of odd sum subarrays starting at // 0th index for (int i = 0; i < n; i++) { if (a[i] & 1) odd = !odd; if (odd) c_odd++; } // Find number of odd sum subarrays starting at ith // index add to result for (int i = 0; i < n; i++) { result += c_odd; if (a[i] & 1) c_odd = (n - i - c_odd); } return result;} // Driver codeint main(){ int ar[] = { 5, 4, 4, 5, 1, 3 }; int n = sizeof(ar) / sizeof(ar[0]); printf("The Number of Subarrays with odd sum is %d", countOddSum(ar, n)); return (0);} // This code is contributed by Sania Kumari Gupta // Java program to find number of subarrays// with odd sumimport java.util.*; class GFG { // Function to find number of subarrays with odd sum static int countOddSum(int a[], int n) { // 'odd' stores number of odd numbers upto ith index // 'c_odd' stores number of odd sum subarrays starting at ith index //'Result' stores the number of odd sum subarrays int c_odd = 0, result = 0; boolean odd = false; // First find number of odd sum subarrays starting // at 0th index for (int i = 0; i < n; i++) { if (a[i] % 2 == 1) odd = !odd; if (odd) c_odd++; } // Find number of odd sum subarrays starting at ith // index add to result for (int i = 0; i < n; i++) { result += c_odd; if (a[i] % 2 == 1) c_odd = (n - i - c_odd); } return result; } // Driver code public static void main(String[] args) { int ar[] = { 5, 4, 4, 5, 1, 3 }; int n = ar.length; System.out.print( "The Number of Subarrays with odd sum is " + countOddSum(ar, n)); }} // This code is contributed by Sania Kumari Gupta # Python3 program to find# number of subarrays with# odd sum # Function to find number# of subarrays with odd sum def countOddSum(a, n): # 'odd' stores number of # odd numbers upto ith index # 'c_odd' stores number of # odd sum subarrays starting # at ith index # 'Result' stores the number # of odd sum subarrays c_odd = 0; result = 0; odd = False; # First find number of odd # sum subarrays starting at # 0th index for i in range(n): if (a[i] % 2 == 1): if(odd == True): odd = False; else: odd = True; if (odd): c_odd += 1; # Find number of odd sum # subarrays starting at ith # index add to result for i in range(n): result += c_odd; if (a[i] % 2 == 1): c_odd = (n - i - c_odd); return result; # Driver codeif __name__ == '__main__': ar = [5, 4, 4, 5, 1, 3]; n = len(ar); print("The Number of Subarrays" + "with odd sum is " , countOddSum(ar, n)); # This code is contributed by shikhasingrajput // C# program to find number of subarrays// with odd sumusing System; public class GFG{ // Function to find number of// subarrays with odd sumstatic int countOddSum(int []a, int n){ // 'odd' stores number of odd numbers // upto ith index // 'c_odd' stores number of odd sum // subarrays starting at ith index // 'Result' stores the number of // odd sum subarrays int c_odd = 0, result = 0; bool odd = false; // First find number of odd sum // subarrays starting at 0th index for(int i = 0; i < n; i++) { if (a[i] % 2 == 1) { odd = !odd; } if (odd) { c_odd++; } } // Find number of odd sum subarrays // starting at ith index add to result for(int i = 0; i < n; i++) { result += c_odd; if (a[i] % 2 == 1) { c_odd = (n - i - c_odd); } } return result;} // Driver codepublic static void Main(String[] args){ int []ar = { 5, 4, 4, 5, 1, 3 }; int n = ar.Length; Console.Write("The Number of Subarrays " + "with odd sum is " + countOddSum(ar, n));}} // This code is contributed by 29AjayKumar <script> // JavaScript program to find number // of subarrays with odd sum // Function to find number of // subarrays with odd sum function countOddSum(a, n) { // 'odd' stores number of odd numbers // upto ith index // 'c_odd' stores number of odd sum // subarrays starting at ith index // 'Result' stores the number of // odd sum subarrays let c_odd = 0, result = 0; let odd = false; // First find number of odd sum // subarrays starting at 0th index for(let i = 0; i < n; i++) { if (a[i] % 2 == 1) { odd = !odd; } if (odd) { c_odd++; } } // Find number of odd sum subarrays // starting at ith index add to result for(let i = 0; i < n; i++) { result += c_odd; if (a[i] % 2 == 1) { c_odd = (n - i - c_odd); } } return result; } let ar = [ 5, 4, 4, 5, 1, 3 ]; let n = ar.length; document.write("The Number of Subarrays " + "with odd sum is " + countOddSum(ar, n)); </script> Output: The Number of Subarrays with odd sum is 12 Time Complexity: O(n) Auxiliary Space: O(1) Chandan_Kumar ukasp paperba1l amit143katiyar 29AjayKumar shikhasingrajput avanitrachhadiya2155 rameshtravel07 decode2207 simmytarika5 krisania804 rishavpgl4 subarray Arrays Mathematical Arrays Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n11 Jul, 2022" }, { "code": null, "e": 117, "s": 54, "text": "Given an array, find the number of subarrays whose sum is odd." }, { "code": null, "e": 128, "s": 117, "text": "Examples: " }, { "code": null, "e": 520, "s": 128, "text": "Input : arr[] = {5, 4, 4, 5, 1, 3} \nOutput : 12\n\nThere are possible subarrays with odd\nsum. The subarrays are \n1) {5} Sum = 5 (At index 0)\n2) {5, 4} Sum = 9\n3) {5, 4, 4} Sum = 13 \n4) {5, 4, 4, 5, 1} Sum = 19\n5) {4, 4, 5} Sum = 13\n6) {4, 4, 5, 1, 3} Sum = 17\n7) {4, 5} Sum = 9 \n8) {4, 5, 1, 3} Sum = 13\n9) {5} Sum = 5 (At index 3)\n10) {5, 1, 3} Sum = 9\n11) {1} Sum = 1\n12) {3} Sum = 3" }, { "code": null, "e": 758, "s": 520, "text": "O(n2) time and O(1) space method [Brute Force] We can simply generate all the possible sub-arrays and find whether the sum of all the elements in them is an odd or not. If it is odd then we will count that sub-array otherwise neglect it." }, { "code": null, "e": 762, "s": 758, "text": "C++" }, { "code": null, "e": 764, "s": 762, "text": "C" }, { "code": null, "e": 769, "s": 764, "text": "Java" }, { "code": null, "e": 777, "s": 769, "text": "Python3" }, { "code": null, "e": 780, "s": 777, "text": "C#" }, { "code": null, "e": 784, "s": 780, "text": "PHP" }, { "code": null, "e": 795, "s": 784, "text": "Javascript" }, { "code": "// C++ code to find count of sub-arrays with odd sum#include <bits/stdc++.h>using namespace std; int countOddSum(int ar[], int n){ int result = 0; // Find sum of all subarrays and increment result if sum // is odd for (int i = 0; i <= n - 1; i++) { int val = 0; for (int j = i; j <= n - 1; j++) { val = val + ar[j]; if (val % 2 != 0) result++; } } return (result);} // Driver codeint main(){ int arr[] = { 5, 4, 4, 5, 1, 3 }; int n = sizeof(arr) / sizeof(arr[0]); cout << \"The Number of Subarrays with odd sum is \" << countOddSum(arr, n); return (0);} // This code is contributed by Sania Kumari Gupta", "e": 1493, "s": 795, "text": null }, { "code": "// C++ code to find count of sub-arrays with odd sum#include <stdio.h> int countOddSum(int ar[], int n){ int result = 0; // Find sum of all subarrays and increment result if sum // is odd for (int i = 0; i <= n - 1; i++) { int val = 0; for (int j = i; j <= n - 1; j++) { val = val + ar[j]; if (val % 2 != 0) result++; } } return (result);} // Driver codeint main(){ int arr[] = { 5, 4, 4, 5, 1, 3 }; int n = sizeof(arr) / sizeof(arr[0]); printf(\"The Number of Subarrays with odd sum is %d\", countOddSum(arr, n)); return (0);} // This code is contributed by Sania Kumari Gupta", "e": 2167, "s": 1493, "text": null }, { "code": "// Java code to find count of sub-arrays with odd sumimport java.io.*; class GFG { static int countOddSum(int ar[], int n) { int result = 0; // Find sum of all subarrays and increment result if // sum is odd for (int i = 0; i <= n - 1; i++) { int val = 0; for (int j = i; j <= n - 1; j++) { val = val + ar[j]; if (val % 2 != 0) result++; } } return (result); } // Driver code public static void main(String[] args) { int ar[] = { 5, 4, 4, 5, 1, 3 }; int n = ar.length; System.out.print( \"The Number of Subarrays with odd sum is \"); System.out.println(countOddSum(ar, n)); }} // This code is contributed by Sania Kumari Gupta", "e": 2977, "s": 2167, "text": null }, { "code": "# Python 3 code to find count# of sub-arrays with odd sum def countOddSum(ar, n): result = 0 # Find sum of all subarrays and # increment result if sum is odd for i in range(n): val = 0 for j in range(i, n ): val = val + ar[j] if (val % 2 != 0): result +=1 return (result) # Driver codear = [ 5, 4, 4, 5, 1, 3 ] print(\"The Number of Subarrays\" , \"with odd\", end = \"\") print(\" sum is \"+ str(countOddSum(ar, 6))) # This code is contributed# by ChitraNayal", "e": 3509, "s": 2977, "text": null }, { "code": "// C# code to find count// of sub-arrays with odd sumusing System; class GFG{static int countOddSum(int []ar, int n){ int result = 0; // Find sum of all subarrays // and increment result if // sum is odd for (int i = 0; i <= n - 1; i++) { int val = 0; for (int j = i; j <= n - 1; j++) { val = val + ar[j]; if (val % 2 != 0) result++; } } return (result);} // Driver codepublic static void Main(){ int []ar = {5, 4, 4, 5, 1, 3}; int n = ar.Length; Console.Write(\"The Number of Subarrays\" + \" with odd sum is \"); Console.WriteLine(countOddSum(ar, n));}} // This code is contributed// by chandan_jnu.", "e": 4285, "s": 3509, "text": null }, { "code": "<?php// PHP code to find count// of sub-arrays with odd sum function countOddSum(&$ar, $n){ $result = 0; // Find sum of all subarrays and // increment result if sum is odd for ($i = 0; $i <= $n - 1; $i++) { $val = 0; for ($j = $i; $j <= $n - 1; $j++) { $val = $val + $ar[$j]; if ($val % 2 != 0) $result++; } } return ($result);} // Driver code$ar = array(5, 4, 4, 5, 1, 3);$n = sizeof($ar); echo \"The Number of Subarrays with odd \";echo \"sum is \".countOddSum($ar, $n); // This code is contributed// by ChitraNayal?>", "e": 4901, "s": 4285, "text": null }, { "code": "<script> // Javascript code to find count of// sub-arrays with odd sumfunction countOddSum(ar, n){ let result = 0; // Find sum of all subarrays // and increment result if // sum is odd for(let i = 0; i <= n - 1; i++) { let val = 0; for(let j = i; j <= n - 1; j++) { val = val + ar[j]; if (val % 2 != 0) result++; } } return (result);} // Driver codelet ar = [ 5, 4, 4, 5, 1, 3 ];let n = ar.length;document.write(\"The Number of Subarrays\" + \" with odd sum is \"); document.write(countOddSum(ar, n)); // This code is contributed by avanitrachhadiya2155 </script>", "e": 5578, "s": 4901, "text": null }, { "code": null, "e": 5587, "s": 5578, "text": "Output: " }, { "code": null, "e": 5630, "s": 5587, "text": "The Number of Subarrays with odd sum is 12" }, { "code": null, "e": 5653, "s": 5630, "text": "Time Complexity: O(n2)" }, { "code": null, "e": 6090, "s": 5653, "text": "Auxiliary Space: O(1)O(n) Time and O(1) Space Method [Efficient] If we do compute the cumulative sum array in temp[] of our input array, then we can see that the sub-array starting from i and ending at j, has an even sum if temp[] if (temp[j] – temp[i]) % 2 = 0. So, instead of building a cumulative sum array, we build a cumulative sum modulo 2 array. Then calculating odd-even pairs will give the required result i.e. temp[0]*temp[1]." }, { "code": null, "e": 6094, "s": 6090, "text": "C++" }, { "code": null, "e": 6096, "s": 6094, "text": "C" }, { "code": null, "e": 6101, "s": 6096, "text": "Java" }, { "code": null, "e": 6109, "s": 6101, "text": "Python3" }, { "code": null, "e": 6112, "s": 6109, "text": "C#" }, { "code": null, "e": 6116, "s": 6112, "text": "PHP" }, { "code": null, "e": 6127, "s": 6116, "text": "Javascript" }, { "code": "// C++ program to find count of sub-arrays// with odd sum#include <bits/stdc++.h>using namespace std; int countOddSum(int ar[], int n){ // A temporary array of size 2. temp[0] is going to // store count of even subarrays and temp[1] count of // odd. temp[0] is initialized as 1 because there a // single odd element is also counted as a subarray int temp[2] = { 1, 0 }; // Initialize count. sum is sum of elements under modulo // 2 and ending with arr[i]. int result = 0, val = 0; // i'th iteration computes sum of arr[0..i] under modulo // 2 and increments even/odd count according to sum's // value for (int i = 0; i <= n - 1; i++) { // 2 is added to handle negative numbers val = ((val + ar[i]) % 2 + 2) % 2; // Increment even/odd count temp[val]++; } // An odd can be formed by even-odd pair result = (temp[0] * temp[1]); return (result);} // Driver codeint main(){ int ar[] = { 5, 4, 4, 5, 1, 3 }; int n = sizeof(ar) / sizeof(ar[0]); cout << \"The Number of Subarrays with odd sum is \" << countOddSum(ar, n); return (0);} // This code is contributed by Sania Kumari Gupta", "e": 7301, "s": 6127, "text": null }, { "code": "// C++ program to find count of sub-arrays// with odd sum#include <stdio.h> int countOddSum(int ar[], int n){ // A temporary array of size 2. temp[0] is going to // store count of even subarrays and temp[1] count of // odd. temp[0] is initialized as 1 because there a // single odd element is also counted as a subarray int temp[2] = { 1, 0 }; // Initialize count. sum is sum of elements under modulo // 2 and ending with arr[i]. int result = 0, val = 0; // i'th iteration computes sum of arr[0..i] under modulo // 2 and increments even/odd count according to sum's // value for (int i = 0; i <= n - 1; i++) { // 2 is added to handle negative numbers val = ((val + ar[i]) % 2 + 2) % 2; // Increment even/odd count temp[val]++; } // An odd can be formed by even-odd pair result = (temp[0] * temp[1]); return (result);} // Driver codeint main(){ int ar[] = { 5, 4, 4, 5, 1, 3 }; int n = sizeof(ar) / sizeof(ar[0]); printf(\"The Number of Subarrays with odd sum is %d\", countOddSum(ar, n)); return (0);} // This code is contributed by Sania Kumari Gupta", "e": 8451, "s": 7301, "text": null }, { "code": "// Java code to find count of sub-arrays// with odd sumimport java.io.*; class GFG { static int countOddSum(int ar[], int n) { // A temporary array of size 2. temp[0] is going to // store count of even subarrays and temp[1] count // of odd. temp[0] is initialized as 1 because there // a single odd element is also counted as a // subarray int temp[] = { 1, 0 }; // Initialize count. sum is sum of elements under // modulo 2 and ending with arr[i]. int result = 0, val = 0; // i'th iteration computes sum of arr[0..i] under // modulo 2 and increments even/odd count according // to sum's value for (int i = 0; i <= n - 1; i++) { // 2 is added to handle negative numbers val = ((val + ar[i]) % 2 + 2) % 2; // Increment even/odd count temp[val]++; } // An odd can be formed by an even-odd pair result = temp[0] * temp[1]; return (result); } // Driver code public static void main(String[] args) { int ar[] = { 5, 4, 4, 5, 1, 3 }; int n = ar.length; System.out.println( \"The Number of Subarrays with odd sum is \" + countOddSum(ar, n)); }} // This code is contributed by Sania Kumari Gupta", "e": 9768, "s": 8451, "text": null }, { "code": "# Python 3 program to # find count of sub-arrays# with odd sumdef countOddSum(ar, n): # A temporary array of size # 2. temp[0] is going to # store count of even subarrays # and temp[1] count of odd. # temp[0] is initialized as 1 # because there is a single odd # element is also counted as # a subarray temp = [ 1, 0 ] # Initialize count. sum is sum # of elements under modulo 2 # and ending with arr[i]. result = 0 val = 0 # i'th iteration computes # sum of arr[0..i] under # modulo 2 and increments # even/odd count according # to sum's value for i in range(n): # 2 is added to handle # negative numbers val = ((val + ar[i]) % 2 + 2) % 2 # Increment even/odd count temp[val] += 1 # An odd can be formed # by even-odd pair result = (temp[0] * temp[1]) return (result) # Driver codear = [ 5, 4, 4, 5, 1, 3 ] print(\"The Number of Subarrays\" \" with odd sum is \"+ str(countOddSum(ar, 6))) # This code is contributed# by ChitraNayal", "e": 10846, "s": 9768, "text": null }, { "code": "// C# code to find count of// sub-arrays with odd sumusing System; class GFG{static int countOddSum(int[] ar, int n){ // A temporary array of size 2. // temp[0] is going to store // count of even subarrays // and temp[1] count of odd. // temp[0] is initialized as // 1 because there a single odd // element is also counted as // a subarray int[] temp = { 1, 0 }; // Initialize count. sum is // sum of elements under modulo // 2 and ending with arr[i]. int result = 0, val = 0; // i'th iteration computes sum // of arr[0..i] under modulo 2 // and increments even/odd count // according to sum's value for (int i = 0; i <= n - 1; i++) { // 2 is added to handle // negative numbers val = ((val + ar[i]) % 2 + 2) % 2; // Increment even/odd count temp[val]++; } // An odd can be formed // by an even-odd pair result = temp[0] * temp[1]; return (result);} // Driver codepublic static void Main(){ int[] ar = { 5, 4, 4, 5, 1, 3 }; int n = ar.Length; Console.Write(\"The Number of Subarrays\" + \" with odd sum is \" + countOddSum(ar, n));}} // This code is contributed// by ChitraNayal", "e": 12113, "s": 10846, "text": null }, { "code": "<?php// PHP program to find count// of sub-arrays with odd sum function countOddSum($ar, $n){ // A temporary array of size // 2. temp[0] is going to // store count of even subarrays // and temp[1] count of odd. // temp[0] is initialized as 1 // because there is a single odd // element is also counted as // a subarray $temp = array(1, 0); // Initialize count. sum is // sum of elements under // modulo 2 and ending with arr[i]. $result = 0; $val = 0; // i'th iteration computes sum // of arr[0..i] under modulo 2 // and increments even/odd count // according to sum's value for ($i = 0; $i <= $n - 1; $i++) { // 2 is added to handle // negative numbers $val = (($val + $ar[$i]) % 2 + 2) % 2; // Increment even/odd count $temp[$val]++; } // An odd can be formed // by even-odd pair $result = ($temp[0] * $temp[1]); return ($result);} // Driver code$ar = array(5, 4, 4, 5, 1, 3);$n = sizeof($ar); echo \"The Number of Subarrays with odd\". \" sum is \".countOddSum($ar, $n); // This code is contributed// by ChitraNayal?>", "e": 13274, "s": 12113, "text": null }, { "code": "<script> // Javascript code to find count of// sub-arrays with odd sumfunction countOddSum(ar, n){ // A temporary array of size 2. // temp[0] is going to store // count of even subarrays // and temp[1] count of odd. // temp[0] is initialized as // 1 because there a single odd // element is also counted as // a subarray let temp = [1, 0]; // Initialize count. sum is // sum of elements under modulo // 2 and ending with arr[i]. let result = 0, val = 0; // i'th iteration computes sum // of arr[0..i] under modulo 2 // and increments even/odd count // according to sum's value for(let i = 0; i <= n - 1; i++) { // 2 is added to handle // negative numbers val = ((val + ar[i]) % 2 + 2) % 2; // Increment even/odd count temp[val]++; } // An odd can be formed // by an even-odd pair result = temp[0] * temp[1]; return (result);} // Driver codelet ar = [ 5, 4, 4, 5, 1, 3 ];let n = ar.length; document.write(\"The Number of Subarrays\" + \" with odd sum is \" + countOddSum(ar, n)); // This code is contributed by rameshtravel07 </script>", "e": 14482, "s": 13274, "text": null }, { "code": null, "e": 14491, "s": 14482, "text": "Output: " }, { "code": null, "e": 14534, "s": 14491, "text": "The Number of Subarrays with odd sum is 12" }, { "code": null, "e": 14556, "s": 14534, "text": "Time Complexity: O(n)" }, { "code": null, "e": 14790, "s": 14556, "text": "Auxiliary Space: O(1)Another efficient approach is to first find the number of subarrays starting at index 0 and having an odd sum. Then traverse the array and update the number of subarrays starting at index i and having an odd sum." }, { "code": null, "e": 14842, "s": 14790, "text": "Below is the implementation of the above approach :" }, { "code": null, "e": 14846, "s": 14842, "text": "C++" }, { "code": null, "e": 14848, "s": 14846, "text": "C" }, { "code": null, "e": 14853, "s": 14848, "text": "Java" }, { "code": null, "e": 14861, "s": 14853, "text": "Python3" }, { "code": null, "e": 14864, "s": 14861, "text": "C#" }, { "code": null, "e": 14875, "s": 14864, "text": "Javascript" }, { "code": "// C++ program to find number of subarrays with odd sum#include <bits/stdc++.h>using namespace std; // Function to find number of subarrays with odd sumint countOddSum(int a[], int n){ // 'odd' stores number of odd numbers upto ith index // 'c_odd' stores number of odd sum subarrays starting // at ith index //'Result' stores the number of odd sum subarrays int odd = 0, c_odd = 0, result = 0; // First find number of odd sum subarrays starting at // 0th index for (int i = 0; i < n; i++) { if (a[i] & 1) odd = !odd; if (odd) c_odd++; } // Find number of odd sum subarrays starting at ith // index add to result for (int i = 0; i < n; i++) { result += c_odd; if (a[i] & 1) c_odd = (n - i - c_odd); } return result;} // Driver codeint main(){ int ar[] = { 5, 4, 4, 5, 1, 3 }; int n = sizeof(ar) / sizeof(ar[0]); cout << \"The Number of Subarrays with odd sum is \" << countOddSum(ar, n); return (0);} // This code is contributed by Sania Kumari Gupta", "e": 15949, "s": 14875, "text": null }, { "code": "// C++ program to find number of subarrays with odd sum#include <stdio.h> // Function to find number of subarrays with odd sumint countOddSum(int a[], int n){ // 'odd' stores number of odd numbers upto ith index // 'c_odd' stores number of odd sum subarrays starting // at ith index //'Result' stores the number of odd sum subarrays int odd = 0, c_odd = 0, result = 0; // First find number of odd sum subarrays starting at // 0th index for (int i = 0; i < n; i++) { if (a[i] & 1) odd = !odd; if (odd) c_odd++; } // Find number of odd sum subarrays starting at ith // index add to result for (int i = 0; i < n; i++) { result += c_odd; if (a[i] & 1) c_odd = (n - i - c_odd); } return result;} // Driver codeint main(){ int ar[] = { 5, 4, 4, 5, 1, 3 }; int n = sizeof(ar) / sizeof(ar[0]); printf(\"The Number of Subarrays with odd sum is %d\", countOddSum(ar, n)); return (0);} // This code is contributed by Sania Kumari Gupta", "e": 16999, "s": 15949, "text": null }, { "code": "// Java program to find number of subarrays// with odd sumimport java.util.*; class GFG { // Function to find number of subarrays with odd sum static int countOddSum(int a[], int n) { // 'odd' stores number of odd numbers upto ith index // 'c_odd' stores number of odd sum subarrays starting at ith index //'Result' stores the number of odd sum subarrays int c_odd = 0, result = 0; boolean odd = false; // First find number of odd sum subarrays starting // at 0th index for (int i = 0; i < n; i++) { if (a[i] % 2 == 1) odd = !odd; if (odd) c_odd++; } // Find number of odd sum subarrays starting at ith // index add to result for (int i = 0; i < n; i++) { result += c_odd; if (a[i] % 2 == 1) c_odd = (n - i - c_odd); } return result; } // Driver code public static void main(String[] args) { int ar[] = { 5, 4, 4, 5, 1, 3 }; int n = ar.length; System.out.print( \"The Number of Subarrays with odd sum is \" + countOddSum(ar, n)); }} // This code is contributed by Sania Kumari Gupta", "e": 18239, "s": 16999, "text": null }, { "code": "# Python3 program to find# number of subarrays with# odd sum # Function to find number# of subarrays with odd sum def countOddSum(a, n): # 'odd' stores number of # odd numbers upto ith index # 'c_odd' stores number of # odd sum subarrays starting # at ith index # 'Result' stores the number # of odd sum subarrays c_odd = 0; result = 0; odd = False; # First find number of odd # sum subarrays starting at # 0th index for i in range(n): if (a[i] % 2 == 1): if(odd == True): odd = False; else: odd = True; if (odd): c_odd += 1; # Find number of odd sum # subarrays starting at ith # index add to result for i in range(n): result += c_odd; if (a[i] % 2 == 1): c_odd = (n - i - c_odd); return result; # Driver codeif __name__ == '__main__': ar = [5, 4, 4, 5, 1, 3]; n = len(ar); print(\"The Number of Subarrays\" + \"with odd sum is \" , countOddSum(ar, n)); # This code is contributed by shikhasingrajput", "e": 19333, "s": 18239, "text": null }, { "code": "// C# program to find number of subarrays// with odd sumusing System; public class GFG{ // Function to find number of// subarrays with odd sumstatic int countOddSum(int []a, int n){ // 'odd' stores number of odd numbers // upto ith index // 'c_odd' stores number of odd sum // subarrays starting at ith index // 'Result' stores the number of // odd sum subarrays int c_odd = 0, result = 0; bool odd = false; // First find number of odd sum // subarrays starting at 0th index for(int i = 0; i < n; i++) { if (a[i] % 2 == 1) { odd = !odd; } if (odd) { c_odd++; } } // Find number of odd sum subarrays // starting at ith index add to result for(int i = 0; i < n; i++) { result += c_odd; if (a[i] % 2 == 1) { c_odd = (n - i - c_odd); } } return result;} // Driver codepublic static void Main(String[] args){ int []ar = { 5, 4, 4, 5, 1, 3 }; int n = ar.Length; Console.Write(\"The Number of Subarrays \" + \"with odd sum is \" + countOddSum(ar, n));}} // This code is contributed by 29AjayKumar", "e": 20543, "s": 19333, "text": null }, { "code": "<script> // JavaScript program to find number // of subarrays with odd sum // Function to find number of // subarrays with odd sum function countOddSum(a, n) { // 'odd' stores number of odd numbers // upto ith index // 'c_odd' stores number of odd sum // subarrays starting at ith index // 'Result' stores the number of // odd sum subarrays let c_odd = 0, result = 0; let odd = false; // First find number of odd sum // subarrays starting at 0th index for(let i = 0; i < n; i++) { if (a[i] % 2 == 1) { odd = !odd; } if (odd) { c_odd++; } } // Find number of odd sum subarrays // starting at ith index add to result for(let i = 0; i < n; i++) { result += c_odd; if (a[i] % 2 == 1) { c_odd = (n - i - c_odd); } } return result; } let ar = [ 5, 4, 4, 5, 1, 3 ]; let n = ar.length; document.write(\"The Number of Subarrays \" + \"with odd sum is \" + countOddSum(ar, n)); </script>", "e": 21720, "s": 20543, "text": null }, { "code": null, "e": 21729, "s": 21720, "text": "Output: " }, { "code": null, "e": 21772, "s": 21729, "text": "The Number of Subarrays with odd sum is 12" }, { "code": null, "e": 21794, "s": 21772, "text": "Time Complexity: O(n)" }, { "code": null, "e": 21817, "s": 21794, "text": "Auxiliary Space: O(1) " }, { "code": null, "e": 21831, "s": 21817, "text": "Chandan_Kumar" }, { "code": null, "e": 21837, "s": 21831, "text": "ukasp" }, { "code": null, "e": 21847, "s": 21837, "text": "paperba1l" }, { "code": null, "e": 21862, "s": 21847, "text": "amit143katiyar" }, { "code": null, "e": 21874, "s": 21862, "text": "29AjayKumar" }, { "code": null, "e": 21891, "s": 21874, "text": "shikhasingrajput" }, { "code": null, "e": 21912, "s": 21891, "text": "avanitrachhadiya2155" }, { "code": null, "e": 21927, "s": 21912, "text": "rameshtravel07" }, { "code": null, "e": 21938, "s": 21927, "text": "decode2207" }, { "code": null, "e": 21951, "s": 21938, "text": "simmytarika5" }, { "code": null, "e": 21963, "s": 21951, "text": "krisania804" }, { "code": null, "e": 21974, "s": 21963, "text": "rishavpgl4" }, { "code": null, "e": 21983, "s": 21974, "text": "subarray" }, { "code": null, "e": 21990, "s": 21983, "text": "Arrays" }, { "code": null, "e": 22003, "s": 21990, "text": "Mathematical" }, { "code": null, "e": 22010, "s": 22003, "text": "Arrays" }, { "code": null, "e": 22023, "s": 22010, "text": "Mathematical" } ]
How to know which radio button is selected using jQuery?
03 Aug, 2021 To check which radio button is selected in a form, we first get the desired input group with the type of input as an option and then the value of this selection can then be accessed by the val() method. This returns the name of the option that is currently selected. The selector ‘input[name=option]:checked’ is used to select all input groups that have the option type of input in the specified form. Syntax: $('input[name=option]:checked', 'formName').val() This is shown in the example below.Example: <!DOCTYPE html><html><head> <title> How to know which radio button is selected via jQuery? </title></head> <body> <h1 style="color: green"> GeeksForGeeks </h1> <b> How to know which radio button is selected via jQuery? </b> <p> <form id="myForm"> <label> <input type="radio" name="option" value="free"> Free Membership </label> <label> <input type="radio" name="option" value="premium"> Premium Membership </label> </form> <p> The value of the option selected is: <span class="output"></span> </p> <button id="btn"> Check option button </button> <script src="https://code.jquery.com/jquery-2.2.4.min.js"> </script> <script type="text/javascript"> // Check the radio button value. $('#btn').on('click', function() { output = $('input[name=option]:checked', '#myForm').val(); document.querySelector( '.output').textContent = output; }); </script></body> </html> Output: Check after clicking on the first option: Check after clicking on the second option: jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”.You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples. jQuery-Misc Picked JQuery Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. JQuery | Set the value of an input text field How to change selected value of a drop-down list using jQuery? Form validation using jQuery How to add options to a select element using jQuery? How to fetch data from JSON file and display in HTML table using jQuery ? 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": 52, "s": 24, "text": "\n03 Aug, 2021" }, { "code": null, "e": 319, "s": 52, "text": "To check which radio button is selected in a form, we first get the desired input group with the type of input as an option and then the value of this selection can then be accessed by the val() method. This returns the name of the option that is currently selected." }, { "code": null, "e": 454, "s": 319, "text": "The selector ‘input[name=option]:checked’ is used to select all input groups that have the option type of input in the specified form." }, { "code": null, "e": 462, "s": 454, "text": "Syntax:" }, { "code": null, "e": 512, "s": 462, "text": "$('input[name=option]:checked', 'formName').val()" }, { "code": null, "e": 556, "s": 512, "text": "This is shown in the example below.Example:" }, { "code": "<!DOCTYPE html><html><head> <title> How to know which radio button is selected via jQuery? </title></head> <body> <h1 style=\"color: green\"> GeeksForGeeks </h1> <b> How to know which radio button is selected via jQuery? </b> <p> <form id=\"myForm\"> <label> <input type=\"radio\" name=\"option\" value=\"free\"> Free Membership </label> <label> <input type=\"radio\" name=\"option\" value=\"premium\"> Premium Membership </label> </form> <p> The value of the option selected is: <span class=\"output\"></span> </p> <button id=\"btn\"> Check option button </button> <script src=\"https://code.jquery.com/jquery-2.2.4.min.js\"> </script> <script type=\"text/javascript\"> // Check the radio button value. $('#btn').on('click', function() { output = $('input[name=option]:checked', '#myForm').val(); document.querySelector( '.output').textContent = output; }); </script></body> </html>", "e": 1840, "s": 556, "text": null }, { "code": null, "e": 1848, "s": 1840, "text": "Output:" }, { "code": null, "e": 1890, "s": 1848, "text": "Check after clicking on the first option:" }, { "code": null, "e": 1933, "s": 1890, "text": "Check after clicking on the second option:" }, { "code": null, "e": 2201, "s": 1933, "text": "jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”.You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples." }, { "code": null, "e": 2213, "s": 2201, "text": "jQuery-Misc" }, { "code": null, "e": 2220, "s": 2213, "text": "Picked" }, { "code": null, "e": 2227, "s": 2220, "text": "JQuery" }, { "code": null, "e": 2244, "s": 2227, "text": "Web Technologies" }, { "code": null, "e": 2271, "s": 2244, "text": "Web technologies Questions" }, { "code": null, "e": 2369, "s": 2271, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2415, "s": 2369, "text": "JQuery | Set the value of an input text field" }, { "code": null, "e": 2478, "s": 2415, "text": "How to change selected value of a drop-down list using jQuery?" }, { "code": null, "e": 2507, "s": 2478, "text": "Form validation using jQuery" }, { "code": null, "e": 2560, "s": 2507, "text": "How to add options to a select element using jQuery?" }, { "code": null, "e": 2634, "s": 2560, "text": "How to fetch data from JSON file and display in HTML table using jQuery ?" }, { "code": null, "e": 2667, "s": 2634, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2729, "s": 2667, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2790, "s": 2729, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2840, "s": 2790, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Maximize number of 0s by flipping a subarray - GeeksforGeeks
29 Aug, 2021 Given a binary array, find the maximum number of zeros in an array with one flip of a subarray allowed. A flip operation switches all 0s to 1s and 1s to 0s.Examples: Input : arr[] = {0, 1, 0, 0, 1, 1, 0} Output : 6 We can get 6 zeros by flipping the subarray {4, 5} Input : arr[] = {0, 0, 0, 1, 0, 1} Output : 5 Method 1 (Simple : O(n2)) A simple solution is to consider all subarrays and find a subarray with maximum value of (count of 1s) – (count of 0s). Let this value be max_diff. Finally, return count of zeros in original array plus max_diff. C++ Java Python3 C# Javascript // C++ program to maximize number of zeroes in a// binary array by at most one flip operation#include<bits/stdc++.h>using namespace std; // A Kadane's algorithm based solution to find maximum// number of 0s by flipping a subarray.int findMaxZeroCount(bool arr[], int n){ // Initialize max_diff = maximum of (Count of 0s - // count of 1s) for all subarrays. int max_diff = 0; // Initialize count of 0s in original array int orig_zero_count = 0; // Consider all Subarrays by using two nested two // loops for (int i=0; i<n; i++) { // Increment count of zeros if (arr[i] == 0) orig_zero_count++; // Initialize counts of 0s and 1s int count1 = 0, count0 = 0; // Consider all subarrays starting from arr[i] // and find the difference between 1s and 0s. // Update max_diff if required for (int j=i; j<n; j++) { (arr[j] == 1)? count1++ : count0++; max_diff = max(max_diff, count1 - count0); } } // Final result would be count of 0s in original // array plus max_diff. return orig_zero_count + max_diff;} // Driver programint main(){ bool arr[] = {0, 1, 0, 0, 1, 1, 0}; int n = sizeof(arr)/sizeof(arr[0]); cout << findMaxZeroCount(arr, n); return 0;} // Java code for Maximize number of 0s by flipping// a subarrayclass GFG { // A Kadane's algorithm based solution to find maximum // number of 0s by flipping a subarray. public static int findMaxZeroCount(int arr[], int n) { // Initialize max_diff = maximum of (Count of 0s - // count of 1s) for all subarrays. int max_diff = 0; // Initialize count of 0s in original array int orig_zero_count = 0; // Consider all Subarrays by using two nested two // loops for (int i=0; i<n; i++) { // Increment count of zeros if (arr[i] == 0) orig_zero_count++; // Initialize counts of 0s and 1s int count1 = 0, count0 = 0; // Consider all subarrays starting from arr[i] // and find the difference between 1s and 0s. // Update max_diff if required for (int j = i; j < n; j ++) { if(arr[j] == 1) count1++; else count0++; max_diff = Math.max(max_diff, count1 - count0); } } // Final result would be count of 0s in original // array plus max_diff. return orig_zero_count + max_diff; } /* Driver program to test above function */ public static void main(String[] args) { int arr[] = {0, 1, 0, 0, 1, 1, 0}; System.out.println(findMaxZeroCount(arr, arr.length)); } }// This code is contributed by Arnav Kr. Mandal. # Python3 program to maximize number of# zeroes in a binary array by at most# one flip operation # A Kadane's algorithm based solution# to find maximum number of 0s by# flipping a subarray.def findMaxZeroCount(arr, n): # Initialize max_diff = maximum # of (Count of 0s - count of 1s) # for all subarrays. max_diff = 0 # Initialize count of 0s in # original array orig_zero_count = 0 # Consider all Subarrays by using # two nested two loops for i in range(n): # Increment count of zeros if arr[i] == 0: orig_zero_count += 1 # Initialize counts of 0s and 1s count1, count0 = 0, 0 # Consider all subarrays starting # from arr[i] and find the # difference between 1s and 0s. # Update max_diff if required for j in range(i, n): if arr[j] == 1: count1 += 1 else: count0 += 1 max_diff = max(max_diff, count1 - count0) # Final result would be count of 0s # in original array plus max_diff. return orig_zero_count + max_diff # Driver codearr = [ 0, 1, 0, 0, 1, 1, 0 ]n = len(arr) print(findMaxZeroCount(arr, n)) # This code is contributed by stutipathak31jan // C# code for Maximize number of 0s by// flipping a subarrayusing System; class GFG{ // A Kadane's algorithm based solution// to find maximum number of 0s by// flipping a subarray.public static int findMaxZeroCount(int []arr, int n){ // Initialize max_diff = maximum of // (Count of 0s - count of 1s) for // all subarrays. int max_diff = 0; // Initialize count of 0s in // original array int orig_zero_count = 0; // Consider all Subarrays by // using two nested two loops for(int i = 0; i < n; i++) { // Increment count of zeros if (arr[i] == 0) orig_zero_count++; // Initialize counts of 0s and 1s int count1 = 0, count0 = 0; // Consider all subarrays starting // from arr[i] and find the difference // between 1s and 0s. // Update max_diff if required for(int j = i; j < n; j ++) { if(arr[j] == 1) count1++; else count0++; max_diff = Math.Max(max_diff, count1 - count0); } } // Final result would be count of 0s in original // array plus max_diff. return orig_zero_count + max_diff;} // Driver codepublic static void Main(String[] args){ int []arr = { 0, 1, 0, 0, 1, 1, 0 }; Console.WriteLine( findMaxZeroCount(arr, arr.Length));}} // This code is contributed by amal kumar choubey <script> // JavaScript program to maximize number of zeroes in a// binary array by at most one flip operation // A Kadane's algorithm based solution to find maximum// number of 0s by flipping a subarray.function findMaxZeroCount(arr, n){ // Initialize max_diff = maximum of (Count of 0s - // count of 1s) for all subarrays. let max_diff = 0; // Initialize count of 0s in original array let orig_zero_count = 0; // Consider all Subarrays by using two nested two // loops for (let i=0; i<n; i++) { // Increment count of zeros if (arr[i] == 0) orig_zero_count++; // Initialize counts of 0s and 1s let count1 = 0, count0 = 0; // Consider all subarrays starting from arr[i] // and find the difference between 1s and 0s. // Update max_diff if required for (let j=i; j<n; j++) { (arr[j] == 1)? count1++ : count0++; max_diff = Math.max(max_diff, count1 - count0); } } // Final result would be count of 0s in original // array plus max_diff. return orig_zero_count + max_diff;} // Driver program let arr = [0, 1, 0, 0, 1, 1, 0]; let n = arr.length; document.write(findMaxZeroCount(arr, n)); // This code is contributed by Surbhi Tyagi. </script> Output: 6 Method 2 (Efficient : O(n)) This problem can be reduced to largest subarray sum problem. The idea is to consider every 0 as -1 and every 1 as 1, find the sum of largest subarray sum in this modified array. This sum is our required max_diff ( count of 0s – count of 1s in any subarray). Finally we return the max_diff plus count of zeros in original array. C++ Java Python3 C# Javascript // C++ program to maximize number of zeroes in a// binary array by at most one flip operation#include<bits/stdc++.h>using namespace std; // A Kadane's algorithm based solution to find maximum// number of 0s by flipping a subarray.int findMaxZeroCount(bool arr[], int n){ // Initialize count of zeros and maximum difference // between count of 1s and 0s in a subarray int orig_zero_count = 0; // Initiale overall max diff for any subarray int max_diff = 0; // Initialize current diff int curr_max = 0; for (int i=0; i<n; i++) { // Count of zeros in original array (Not related // to Kadane's algorithm) if (arr[i] == 0) orig_zero_count++; // Value to be considered for finding maximum sum int val = (arr[i] == 1)? 1 : -1; // Update current max and max_diff curr_max = max(val, curr_max + val); max_diff = max(max_diff, curr_max); } max_diff = max(0, max_diff); return orig_zero_count + max_diff;} // Driver programint main(){ bool arr[] = {0, 1, 0, 0, 1, 1, 0}; int n = sizeof(arr)/sizeof(arr[0]); cout << findMaxZeroCount(arr, n); return 0;} // Java code for Maximize number of 0s by// flipping a subarrayclass GFG { // A Kadane's algorithm based solution to find maximum // number of 0s by flipping a subarray. public static int findMaxZeroCount(int arr[], int n) { // Initialize count of zeros and maximum difference // between count of 1s and 0s in a subarray int orig_zero_count = 0; // Initiale overall max diff for any subarray int max_diff = 0; // Initialize current diff int curr_max = 0; for (int i = 0; i < n; i ++) { // Count of zeros in original array (Not related // to Kadane's algorithm) if (arr[i] == 0) orig_zero_count ++; // Value to be considered for finding maximum sum int val = (arr[i] == 1)? 1 : -1; // Update current max and max_diff curr_max = Math.max(val, curr_max + val); max_diff = Math.max(max_diff, curr_max); } max_diff = Math.max(0, max_diff); return orig_zero_count + max_diff; } /* Driver program to test above function */ public static void main(String[] args) { int arr[] = {0, 1, 0, 0, 1, 1, 0}; System.out.println(findMaxZeroCount(arr, arr.length)); } }// This code is contributed by Arnav Kr. Mandal. # Python3 program to maximize number# of zeroes in a binary array by at# most one flip operation # A Kadane's algorithm based solution# to find maximum number of 0s by# flipping a subarray.def findMaxZeroCount(arr, n): # Initialize count of zeros and # maximum difference between count # of 1s and 0s in a subarray orig_zero_count = 0 # Initialize overall max diff # for any subarray max_diff = 0 # Initialize current diff curr_max = 0 for i in range(n): # Count of zeros in original # array (Not related to # Kadane's algorithm) if arr[i] == 0: orig_zero_count += 1 # Value to be considered for # finding maximum sum val = 1 if arr[i] == 1 else -1 # Update current max and max_diff curr_max = max(val, curr_max + val) max_diff = max(max_diff, curr_max) max_diff = max(0, max_diff) return orig_zero_count + max_diff # Driver codearr = [ 0, 1, 0, 0, 1, 1, 0 ]n = len(arr) print(findMaxZeroCount(arr, n)) # This code is contributed by stutipathak31jan // C# code for Maximize number of 0s by// flipping a subarrayusing System;class GFG{ // A Kadane's algorithm based solution to find maximum // number of 0s by flipping a subarray. public static int findMaxZeroCount(int []arr, int n) { // Initialize count of zeros and maximum difference // between count of 1s and 0s in a subarray int orig_zero_count = 0; // Initiale overall max diff for any subarray int max_diff = 0; // Initialize current diff int curr_max = 0; for (int i = 0; i < n; i ++) { // Count of zeros in original array (Not related // to Kadane's algorithm) if (arr[i] == 0) orig_zero_count ++; // Value to be considered for finding maximum sum int val = (arr[i] == 1)? 1 : -1; // Update current max and max_diff curr_max = Math.Max(val, curr_max + val); max_diff = Math.Max(max_diff, curr_max); } max_diff = Math.Max(0, max_diff); return orig_zero_count + max_diff; } // Driver Code public static void Main(String[] args) { int []arr = {0, 1, 0, 0, 1, 1, 0}; Console.WriteLine(findMaxZeroCount(arr, arr.Length)); }} // This code is contributed by Rohit_ranjan <script> // JavaScript program to// maximize number of zeroes in a// binary array by at most one flip operation // A Kadane's algorithm// based solution to find maximum// number of 0s by flipping a subarray.function findMaxZeroCount(arr, n){ // Initialize count of // zeros and maximum difference // between count of 1s and 0s in // a subarray var orig_zero_count = 0; // Initiale overall max diff for any subarray var max_diff = 0; // Initialize current diff var curr_max = 0; for (var i=0; i<n; i++) { // Count of zeros in original array // (Not related to Kadane's algorithm) if (arr[i] == 0) orig_zero_count++; // Value to be considered for // finding maximum sum var val; if (arr[i] == 1) val=1; else val=-1; // Update current max and max_diff curr_max = Math.max(val, curr_max + val); max_diff = Math.max(max_diff, curr_max); } max_diff = Math.max(0, max_diff); return orig_zero_count + max_diff;} var arr = [0, 1, 0, 0, 1, 1, 0]; var n=7; document.write(findMaxZeroCount(arr, n)); // This Code is Contributed by Harshit Srivastava </script> Output: 6 This article is contributed by Shivam Agrawal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. stutipathak31jan Amal Kumar Choubey Rohit_ranjan srivastavaharshit848 surbhityagi15 Vishal Shirke Amazon Kadane Arrays Amazon Arrays Kadane Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Stack Data Structure (Introduction and Program) Top 50 Array Coding Problems for Interviews Introduction to Arrays Multidimensional Arrays in Java Linear Search Python | Using 2D arrays/lists the right way Linked List vs Array Maximum and minimum of an array using minimum number of comparisons Given an array of size n and a number k, find all elements that appear more than n/k times Queue | Set 1 (Introduction and Array Implementation)
[ { "code": null, "e": 24799, "s": 24771, "text": "\n29 Aug, 2021" }, { "code": null, "e": 24965, "s": 24799, "text": "Given a binary array, find the maximum number of zeros in an array with one flip of a subarray allowed. A flip operation switches all 0s to 1s and 1s to 0s.Examples:" }, { "code": null, "e": 25114, "s": 24965, "text": "Input : arr[] = {0, 1, 0, 0, 1, 1, 0}\nOutput : 6\nWe can get 6 zeros by flipping the subarray {4, 5}\n\nInput : arr[] = {0, 0, 0, 1, 0, 1}\nOutput : 5" }, { "code": null, "e": 25352, "s": 25114, "text": "Method 1 (Simple : O(n2)) A simple solution is to consider all subarrays and find a subarray with maximum value of (count of 1s) – (count of 0s). Let this value be max_diff. Finally, return count of zeros in original array plus max_diff." }, { "code": null, "e": 25356, "s": 25352, "text": "C++" }, { "code": null, "e": 25361, "s": 25356, "text": "Java" }, { "code": null, "e": 25369, "s": 25361, "text": "Python3" }, { "code": null, "e": 25372, "s": 25369, "text": "C#" }, { "code": null, "e": 25383, "s": 25372, "text": "Javascript" }, { "code": "// C++ program to maximize number of zeroes in a// binary array by at most one flip operation#include<bits/stdc++.h>using namespace std; // A Kadane's algorithm based solution to find maximum// number of 0s by flipping a subarray.int findMaxZeroCount(bool arr[], int n){ // Initialize max_diff = maximum of (Count of 0s - // count of 1s) for all subarrays. int max_diff = 0; // Initialize count of 0s in original array int orig_zero_count = 0; // Consider all Subarrays by using two nested two // loops for (int i=0; i<n; i++) { // Increment count of zeros if (arr[i] == 0) orig_zero_count++; // Initialize counts of 0s and 1s int count1 = 0, count0 = 0; // Consider all subarrays starting from arr[i] // and find the difference between 1s and 0s. // Update max_diff if required for (int j=i; j<n; j++) { (arr[j] == 1)? count1++ : count0++; max_diff = max(max_diff, count1 - count0); } } // Final result would be count of 0s in original // array plus max_diff. return orig_zero_count + max_diff;} // Driver programint main(){ bool arr[] = {0, 1, 0, 0, 1, 1, 0}; int n = sizeof(arr)/sizeof(arr[0]); cout << findMaxZeroCount(arr, n); return 0;}", "e": 26685, "s": 25383, "text": null }, { "code": "// Java code for Maximize number of 0s by flipping// a subarrayclass GFG { // A Kadane's algorithm based solution to find maximum // number of 0s by flipping a subarray. public static int findMaxZeroCount(int arr[], int n) { // Initialize max_diff = maximum of (Count of 0s - // count of 1s) for all subarrays. int max_diff = 0; // Initialize count of 0s in original array int orig_zero_count = 0; // Consider all Subarrays by using two nested two // loops for (int i=0; i<n; i++) { // Increment count of zeros if (arr[i] == 0) orig_zero_count++; // Initialize counts of 0s and 1s int count1 = 0, count0 = 0; // Consider all subarrays starting from arr[i] // and find the difference between 1s and 0s. // Update max_diff if required for (int j = i; j < n; j ++) { if(arr[j] == 1) count1++; else count0++; max_diff = Math.max(max_diff, count1 - count0); } } // Final result would be count of 0s in original // array plus max_diff. return orig_zero_count + max_diff; } /* Driver program to test above function */ public static void main(String[] args) { int arr[] = {0, 1, 0, 0, 1, 1, 0}; System.out.println(findMaxZeroCount(arr, arr.length)); } }// This code is contributed by Arnav Kr. Mandal.", "e": 28251, "s": 26685, "text": null }, { "code": "# Python3 program to maximize number of# zeroes in a binary array by at most# one flip operation # A Kadane's algorithm based solution# to find maximum number of 0s by# flipping a subarray.def findMaxZeroCount(arr, n): # Initialize max_diff = maximum # of (Count of 0s - count of 1s) # for all subarrays. max_diff = 0 # Initialize count of 0s in # original array orig_zero_count = 0 # Consider all Subarrays by using # two nested two loops for i in range(n): # Increment count of zeros if arr[i] == 0: orig_zero_count += 1 # Initialize counts of 0s and 1s count1, count0 = 0, 0 # Consider all subarrays starting # from arr[i] and find the # difference between 1s and 0s. # Update max_diff if required for j in range(i, n): if arr[j] == 1: count1 += 1 else: count0 += 1 max_diff = max(max_diff, count1 - count0) # Final result would be count of 0s # in original array plus max_diff. return orig_zero_count + max_diff # Driver codearr = [ 0, 1, 0, 0, 1, 1, 0 ]n = len(arr) print(findMaxZeroCount(arr, n)) # This code is contributed by stutipathak31jan", "e": 29577, "s": 28251, "text": null }, { "code": "// C# code for Maximize number of 0s by// flipping a subarrayusing System; class GFG{ // A Kadane's algorithm based solution// to find maximum number of 0s by// flipping a subarray.public static int findMaxZeroCount(int []arr, int n){ // Initialize max_diff = maximum of // (Count of 0s - count of 1s) for // all subarrays. int max_diff = 0; // Initialize count of 0s in // original array int orig_zero_count = 0; // Consider all Subarrays by // using two nested two loops for(int i = 0; i < n; i++) { // Increment count of zeros if (arr[i] == 0) orig_zero_count++; // Initialize counts of 0s and 1s int count1 = 0, count0 = 0; // Consider all subarrays starting // from arr[i] and find the difference // between 1s and 0s. // Update max_diff if required for(int j = i; j < n; j ++) { if(arr[j] == 1) count1++; else count0++; max_diff = Math.Max(max_diff, count1 - count0); } } // Final result would be count of 0s in original // array plus max_diff. return orig_zero_count + max_diff;} // Driver codepublic static void Main(String[] args){ int []arr = { 0, 1, 0, 0, 1, 1, 0 }; Console.WriteLine( findMaxZeroCount(arr, arr.Length));}} // This code is contributed by amal kumar choubey", "e": 31066, "s": 29577, "text": null }, { "code": "<script> // JavaScript program to maximize number of zeroes in a// binary array by at most one flip operation // A Kadane's algorithm based solution to find maximum// number of 0s by flipping a subarray.function findMaxZeroCount(arr, n){ // Initialize max_diff = maximum of (Count of 0s - // count of 1s) for all subarrays. let max_diff = 0; // Initialize count of 0s in original array let orig_zero_count = 0; // Consider all Subarrays by using two nested two // loops for (let i=0; i<n; i++) { // Increment count of zeros if (arr[i] == 0) orig_zero_count++; // Initialize counts of 0s and 1s let count1 = 0, count0 = 0; // Consider all subarrays starting from arr[i] // and find the difference between 1s and 0s. // Update max_diff if required for (let j=i; j<n; j++) { (arr[j] == 1)? count1++ : count0++; max_diff = Math.max(max_diff, count1 - count0); } } // Final result would be count of 0s in original // array plus max_diff. return orig_zero_count + max_diff;} // Driver program let arr = [0, 1, 0, 0, 1, 1, 0]; let n = arr.length; document.write(findMaxZeroCount(arr, n)); // This code is contributed by Surbhi Tyagi. </script>", "e": 32359, "s": 31066, "text": null }, { "code": null, "e": 32369, "s": 32359, "text": "Output: " }, { "code": null, "e": 32371, "s": 32369, "text": "6" }, { "code": null, "e": 32727, "s": 32371, "text": "Method 2 (Efficient : O(n)) This problem can be reduced to largest subarray sum problem. The idea is to consider every 0 as -1 and every 1 as 1, find the sum of largest subarray sum in this modified array. This sum is our required max_diff ( count of 0s – count of 1s in any subarray). Finally we return the max_diff plus count of zeros in original array." }, { "code": null, "e": 32731, "s": 32727, "text": "C++" }, { "code": null, "e": 32736, "s": 32731, "text": "Java" }, { "code": null, "e": 32744, "s": 32736, "text": "Python3" }, { "code": null, "e": 32747, "s": 32744, "text": "C#" }, { "code": null, "e": 32758, "s": 32747, "text": "Javascript" }, { "code": "// C++ program to maximize number of zeroes in a// binary array by at most one flip operation#include<bits/stdc++.h>using namespace std; // A Kadane's algorithm based solution to find maximum// number of 0s by flipping a subarray.int findMaxZeroCount(bool arr[], int n){ // Initialize count of zeros and maximum difference // between count of 1s and 0s in a subarray int orig_zero_count = 0; // Initiale overall max diff for any subarray int max_diff = 0; // Initialize current diff int curr_max = 0; for (int i=0; i<n; i++) { // Count of zeros in original array (Not related // to Kadane's algorithm) if (arr[i] == 0) orig_zero_count++; // Value to be considered for finding maximum sum int val = (arr[i] == 1)? 1 : -1; // Update current max and max_diff curr_max = max(val, curr_max + val); max_diff = max(max_diff, curr_max); } max_diff = max(0, max_diff); return orig_zero_count + max_diff;} // Driver programint main(){ bool arr[] = {0, 1, 0, 0, 1, 1, 0}; int n = sizeof(arr)/sizeof(arr[0]); cout << findMaxZeroCount(arr, n); return 0;}", "e": 33920, "s": 32758, "text": null }, { "code": "// Java code for Maximize number of 0s by// flipping a subarrayclass GFG { // A Kadane's algorithm based solution to find maximum // number of 0s by flipping a subarray. public static int findMaxZeroCount(int arr[], int n) { // Initialize count of zeros and maximum difference // between count of 1s and 0s in a subarray int orig_zero_count = 0; // Initiale overall max diff for any subarray int max_diff = 0; // Initialize current diff int curr_max = 0; for (int i = 0; i < n; i ++) { // Count of zeros in original array (Not related // to Kadane's algorithm) if (arr[i] == 0) orig_zero_count ++; // Value to be considered for finding maximum sum int val = (arr[i] == 1)? 1 : -1; // Update current max and max_diff curr_max = Math.max(val, curr_max + val); max_diff = Math.max(max_diff, curr_max); } max_diff = Math.max(0, max_diff); return orig_zero_count + max_diff; } /* Driver program to test above function */ public static void main(String[] args) { int arr[] = {0, 1, 0, 0, 1, 1, 0}; System.out.println(findMaxZeroCount(arr, arr.length)); } }// This code is contributed by Arnav Kr. Mandal.", "e": 35303, "s": 33920, "text": null }, { "code": "# Python3 program to maximize number# of zeroes in a binary array by at# most one flip operation # A Kadane's algorithm based solution# to find maximum number of 0s by# flipping a subarray.def findMaxZeroCount(arr, n): # Initialize count of zeros and # maximum difference between count # of 1s and 0s in a subarray orig_zero_count = 0 # Initialize overall max diff # for any subarray max_diff = 0 # Initialize current diff curr_max = 0 for i in range(n): # Count of zeros in original # array (Not related to # Kadane's algorithm) if arr[i] == 0: orig_zero_count += 1 # Value to be considered for # finding maximum sum val = 1 if arr[i] == 1 else -1 # Update current max and max_diff curr_max = max(val, curr_max + val) max_diff = max(max_diff, curr_max) max_diff = max(0, max_diff) return orig_zero_count + max_diff # Driver codearr = [ 0, 1, 0, 0, 1, 1, 0 ]n = len(arr) print(findMaxZeroCount(arr, n)) # This code is contributed by stutipathak31jan", "e": 36431, "s": 35303, "text": null }, { "code": "// C# code for Maximize number of 0s by// flipping a subarrayusing System;class GFG{ // A Kadane's algorithm based solution to find maximum // number of 0s by flipping a subarray. public static int findMaxZeroCount(int []arr, int n) { // Initialize count of zeros and maximum difference // between count of 1s and 0s in a subarray int orig_zero_count = 0; // Initiale overall max diff for any subarray int max_diff = 0; // Initialize current diff int curr_max = 0; for (int i = 0; i < n; i ++) { // Count of zeros in original array (Not related // to Kadane's algorithm) if (arr[i] == 0) orig_zero_count ++; // Value to be considered for finding maximum sum int val = (arr[i] == 1)? 1 : -1; // Update current max and max_diff curr_max = Math.Max(val, curr_max + val); max_diff = Math.Max(max_diff, curr_max); } max_diff = Math.Max(0, max_diff); return orig_zero_count + max_diff; } // Driver Code public static void Main(String[] args) { int []arr = {0, 1, 0, 0, 1, 1, 0}; Console.WriteLine(findMaxZeroCount(arr, arr.Length)); }} // This code is contributed by Rohit_ranjan", "e": 37617, "s": 36431, "text": null }, { "code": "<script> // JavaScript program to// maximize number of zeroes in a// binary array by at most one flip operation // A Kadane's algorithm// based solution to find maximum// number of 0s by flipping a subarray.function findMaxZeroCount(arr, n){ // Initialize count of // zeros and maximum difference // between count of 1s and 0s in // a subarray var orig_zero_count = 0; // Initiale overall max diff for any subarray var max_diff = 0; // Initialize current diff var curr_max = 0; for (var i=0; i<n; i++) { // Count of zeros in original array // (Not related to Kadane's algorithm) if (arr[i] == 0) orig_zero_count++; // Value to be considered for // finding maximum sum var val; if (arr[i] == 1) val=1; else val=-1; // Update current max and max_diff curr_max = Math.max(val, curr_max + val); max_diff = Math.max(max_diff, curr_max); } max_diff = Math.max(0, max_diff); return orig_zero_count + max_diff;} var arr = [0, 1, 0, 0, 1, 1, 0]; var n=7; document.write(findMaxZeroCount(arr, n)); // This Code is Contributed by Harshit Srivastava </script>", "e": 38841, "s": 37617, "text": null }, { "code": null, "e": 38850, "s": 38841, "text": "Output: " }, { "code": null, "e": 38852, "s": 38850, "text": "6" }, { "code": null, "e": 39275, "s": 38852, "text": "This article is contributed by Shivam Agrawal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 39292, "s": 39275, "text": "stutipathak31jan" }, { "code": null, "e": 39311, "s": 39292, "text": "Amal Kumar Choubey" }, { "code": null, "e": 39324, "s": 39311, "text": "Rohit_ranjan" }, { "code": null, "e": 39345, "s": 39324, "text": "srivastavaharshit848" }, { "code": null, "e": 39359, "s": 39345, "text": "surbhityagi15" }, { "code": null, "e": 39373, "s": 39359, "text": "Vishal Shirke" }, { "code": null, "e": 39380, "s": 39373, "text": "Amazon" }, { "code": null, "e": 39387, "s": 39380, "text": "Kadane" }, { "code": null, "e": 39394, "s": 39387, "text": "Arrays" }, { "code": null, "e": 39401, "s": 39394, "text": "Amazon" }, { "code": null, "e": 39408, "s": 39401, "text": "Arrays" }, { "code": null, "e": 39415, "s": 39408, "text": "Kadane" }, { "code": null, "e": 39513, "s": 39415, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 39522, "s": 39513, "text": "Comments" }, { "code": null, "e": 39535, "s": 39522, "text": "Old Comments" }, { "code": null, "e": 39583, "s": 39535, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 39627, "s": 39583, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 39650, "s": 39627, "text": "Introduction to Arrays" }, { "code": null, "e": 39682, "s": 39650, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 39696, "s": 39682, "text": "Linear Search" }, { "code": null, "e": 39741, "s": 39696, "text": "Python | Using 2D arrays/lists the right way" }, { "code": null, "e": 39762, "s": 39741, "text": "Linked List vs Array" }, { "code": null, "e": 39830, "s": 39762, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 39921, "s": 39830, "text": "Given an array of size n and a number k, find all elements that appear more than n/k times" } ]
Required arguments in Python
Required arguments are the arguments passed to a function in correct positional order. Here, the number of arguments in the function call should match exactly with the function definition. To call the function printme(), you definitely need to pass one argument, otherwise it gives a syntax error as follows − Live Demo #!/usr/bin/python # Function definition is here def printme( str ): "This prints a passed string into this function" print str return; # Now you can call printme function printme() When the above code is executed, it produces the following result − Traceback (most recent call last): File "test.py", line 11, in <module> printme(); TypeError: printme() takes exactly 1 argument (0 given)
[ { "code": null, "e": 1251, "s": 1062, "text": "Required arguments are the arguments passed to a function in correct positional order. Here, the number of arguments in the function call should match exactly with the function definition." }, { "code": null, "e": 1372, "s": 1251, "text": "To call the function printme(), you definitely need to pass one argument, otherwise it gives a syntax error as follows −" }, { "code": null, "e": 1383, "s": 1372, "text": " Live Demo" }, { "code": null, "e": 1564, "s": 1383, "text": "#!/usr/bin/python\n# Function definition is here\ndef printme( str ):\n\"This prints a passed string into this function\"\nprint str\nreturn;\n# Now you can call printme function\nprintme()" }, { "code": null, "e": 1632, "s": 1564, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 1771, "s": 1632, "text": "Traceback (most recent call last):\nFile \"test.py\", line 11, in <module>\nprintme();\nTypeError: printme() takes exactly 1 argument (0 given)" } ]
Left Rotate Matrix K times | Practice | GeeksforGeeks
Given three integers N, M, and K and a matrix Mat of dimensions NxM. Left rotate the matrix K times. Example 1: Input: N=3,M=3,K=1 Mat=[[1,2,3],[4,5,6],[7,8,9]] Output: 2 3 1 5 6 4 8 9 7 Explanation: Left rotating the matrix once gives this result. Example 2: Input: N=3,M=3,K=2 Mat=[[1,2,3],[4,5,6],[7,8,9]] Output: 3 1 2 6 4 5 9 7 8 Explanation: Left rotating the matrix twice gives this result Your Task: You don't need to read input or print anything. Your task is to complete the function rotateMatrix() which takes the three integers N, M, K, and the matrix Mat and returns the matrix Mat left rotated K times. Expected Time Complexity:O(N*M) Expected Auxillary Space:O(N*M) Constraints: 1<=N,M,Mat[i][j]<=1000 1<=K<=10000 0 HEMSINGH MAKWANA9 months ago HEMSINGH MAKWANA https://uploads.disquscdn.c... -1 Taral Jain9 months ago Taral Jain int[][] rotateMatrix(int N, int M, int K, int mat[][]) { K = K % M; for(int i = 0; i < N; i++){ reverse(mat, i, 0, K - 1); reverse(mat, i, K, M - 1); reverse(mat, i, 0, M - 1); } return mat; } void reverse(int[][] mat, int row, int low, int high){ while(low < high){ int temp = mat[row][low]; mat[row][low] = mat[row][high]; mat[row][high] = temp; low++; high--; } }} 0 kundan Prakash Jha1 year ago kundan Prakash Jha vector<vector<int>> rotateMatrix(int n, int m, int k, vector<vector<int>> Mat) { vector<vector<int>>vec(n, vector<int>(m)); for(int i=0; i<n; i++)="" {="" for(int="" j="0;" j<m;="" j++)="" {="" int="" t="(k+j)%m;" vec[i][j]="Mat[i][t];" }="" }="" return="" vec;="" }=""> 0 kundan Prakash Jha This comment was deleted. 0 kundan Prakash Jha This comment was deleted. 0 dilip suthar1 year ago dilip suthar class Solution { public: vector<vector<int>> rotateMatrix(int n, int m, int k, vector<vector<int>> mat) { if(mat.size()==0&&mat[0].size()==0) { return {}; } for(int i=0;i<n;i++) {="" m="mat[i].size();" vector<int="">v(m),temp(m); k=k%m; for(int j=0;j<m;j++) {="" v[j]="mat[i][j];" }="" for(int="" j="0;j&lt;m;j++)" {="" temp[((j+(m-k))+m)%m]="v[j];" }="" for(int="" j="0;j&lt;m;j++)" {="" mat[i][j]="temp[j];" }="" }="" return="" mat;="" }="" };<="" spoiler=""> 0 dilip suthar1 year ago dilip suthar class Solution { public: vector<vector<int>> rotateMatrix(int n, int m, int k, vector<vector<int>> mat) { if(mat.size()==0&&mat[0].size()==0) { return {}; } for(int i=0;i<n;i++) {="" m="mat[i].size();" vector<int="">v(m),temp(m); k=k%m; for(int j=0;j<m;j++) {="" v[j]="mat[i][j];" }="" for(int="" j="0;j&lt;m;j++)" {="" temp[((j+(m-k))+m)%m]="v[j];" }="" for(int="" j="0;j&lt;m;j++)" {="" mat[i][j]="temp[j];" }="" }="" return="" mat;="" }="" };<="" u=""> 0 dilip suthar1 year ago dilip suthar class Solution { public: vector<vector<int>> rotateMatrix(int n, int m, int k, vector<vector<int>> mat) { if(mat.size()==0&&mat[0].size()==0) { return {}; } for(int i=0;i<n;i++) {="" m="mat[i].size();" vector<int="">v(m),temp(m); k=k%m; for(int j=0;j<m;j++) {="" v[j]="mat[i][j];" }="" for(int="" j="0;j&lt;m;j++)" {="" temp[((j+(m-k))+m)%m]="v[j];" }="" for(int="" j="0;j&lt;m;j++)" {="" mat[i][j]="temp[j];" }="" }="" return="" mat;="" }="" };<="" b=""> 0 dilip suthar1 year ago dilip suthar class Solution { public: vector<vector<int>> rotateMatrix(int n, int m, int k, vector<vector<int>> mat) { if(mat.size()==0&&mat[0].size()==0) { return {}; } for(int i=0;i<n;i++) {="" m="mat[i].size();" vector<int="">v(m),temp(m); k=k%m; for(int j=0;j<m;j++) {="" v[j]="mat[i][j];" }="" for(int="" j="0;j&lt;m;j++)" {="" temp[((j+(m-k))+m)%m]="v[j];" }="" for(int="" j="0;j&lt;m;j++)" {="" mat[i][j]="temp[j];" }="" }="" return="" mat;="" }="" };="" <="" code=""> 0 MD. TASNIN TANVIR2 years ago MD. TASNIN TANVIR Easy c++ solutionhttps://ide.geeksforgeeks.o... We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 327, "s": 226, "text": "Given three integers N, M, and K and a matrix Mat of dimensions NxM. Left rotate the matrix K times." }, { "code": null, "e": 338, "s": 327, "text": "Example 1:" }, { "code": null, "e": 475, "s": 338, "text": "Input:\nN=3,M=3,K=1\nMat=[[1,2,3],[4,5,6],[7,8,9]]\nOutput:\n2 3 1\n5 6 4\n8 9 7\nExplanation:\nLeft rotating the matrix once gives this result." }, { "code": null, "e": 486, "s": 475, "text": "Example 2:" }, { "code": null, "e": 623, "s": 486, "text": "Input:\nN=3,M=3,K=2\nMat=[[1,2,3],[4,5,6],[7,8,9]]\nOutput:\n3 1 2\n6 4 5\n9 7 8\nExplanation:\nLeft rotating the matrix twice gives this result" }, { "code": null, "e": 844, "s": 623, "text": "\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function rotateMatrix() which takes the three integers N, M, K, and the matrix Mat and returns the matrix Mat left rotated K times." }, { "code": null, "e": 909, "s": 844, "text": "\nExpected Time Complexity:O(N*M)\nExpected Auxillary Space:O(N*M)" }, { "code": null, "e": 958, "s": 909, "text": "\nConstraints:\n1<=N,M,Mat[i][j]<=1000\n1<=K<=10000" }, { "code": null, "e": 960, "s": 958, "text": "0" }, { "code": null, "e": 989, "s": 960, "text": "HEMSINGH MAKWANA9 months ago" }, { "code": null, "e": 1006, "s": 989, "text": "HEMSINGH MAKWANA" }, { "code": null, "e": 1037, "s": 1006, "text": "https://uploads.disquscdn.c..." }, { "code": null, "e": 1040, "s": 1037, "text": "-1" }, { "code": null, "e": 1063, "s": 1040, "text": "Taral Jain9 months ago" }, { "code": null, "e": 1074, "s": 1063, "text": "Taral Jain" }, { "code": null, "e": 1573, "s": 1074, "text": "int[][] rotateMatrix(int N, int M, int K, int mat[][]) { K = K % M; for(int i = 0; i < N; i++){ reverse(mat, i, 0, K - 1); reverse(mat, i, K, M - 1); reverse(mat, i, 0, M - 1); } return mat; } void reverse(int[][] mat, int row, int low, int high){ while(low < high){ int temp = mat[row][low]; mat[row][low] = mat[row][high]; mat[row][high] = temp; low++; high--; } }}" }, { "code": null, "e": 1575, "s": 1573, "text": "0" }, { "code": null, "e": 1604, "s": 1575, "text": "kundan Prakash Jha1 year ago" }, { "code": null, "e": 1623, "s": 1604, "text": "kundan Prakash Jha" }, { "code": null, "e": 1736, "s": 1623, "text": "vector<vector<int>> rotateMatrix(int n, int m, int k, vector<vector<int>> Mat) {" }, { "code": null, "e": 1941, "s": 1736, "text": " vector<vector<int>>vec(n, vector<int>(m)); for(int i=0; i<n; i++)=\"\" {=\"\" for(int=\"\" j=\"0;\" j<m;=\"\" j++)=\"\" {=\"\" int=\"\" t=\"(k+j)%m;\" vec[i][j]=\"Mat[i][t];\" }=\"\" }=\"\" return=\"\" vec;=\"\" }=\"\">" }, { "code": null, "e": 1943, "s": 1941, "text": "0" }, { "code": null, "e": 1962, "s": 1943, "text": "kundan Prakash Jha" }, { "code": null, "e": 1988, "s": 1962, "text": "This comment was deleted." }, { "code": null, "e": 1990, "s": 1988, "text": "0" }, { "code": null, "e": 2009, "s": 1990, "text": "kundan Prakash Jha" }, { "code": null, "e": 2035, "s": 2009, "text": "This comment was deleted." }, { "code": null, "e": 2037, "s": 2035, "text": "0" }, { "code": null, "e": 2060, "s": 2037, "text": "dilip suthar1 year ago" }, { "code": null, "e": 2073, "s": 2060, "text": "dilip suthar" }, { "code": null, "e": 2603, "s": 2073, "text": "class Solution { public: vector<vector<int>> rotateMatrix(int n, int m, int k, vector<vector<int>> mat) { if(mat.size()==0&&mat[0].size()==0) { return {}; } for(int i=0;i<n;i++) {=\"\" m=\"mat[i].size();\" vector<int=\"\">v(m),temp(m); k=k%m; for(int j=0;j<m;j++) {=\"\" v[j]=\"mat[i][j];\" }=\"\" for(int=\"\" j=\"0;j&lt;m;j++)\" {=\"\" temp[((j+(m-k))+m)%m]=\"v[j];\" }=\"\" for(int=\"\" j=\"0;j&lt;m;j++)\" {=\"\" mat[i][j]=\"temp[j];\" }=\"\" }=\"\" return=\"\" mat;=\"\" }=\"\" };<=\"\" spoiler=\"\">" }, { "code": null, "e": 2605, "s": 2603, "text": "0" }, { "code": null, "e": 2628, "s": 2605, "text": "dilip suthar1 year ago" }, { "code": null, "e": 2641, "s": 2628, "text": "dilip suthar" }, { "code": null, "e": 3165, "s": 2641, "text": "class Solution { public: vector<vector<int>> rotateMatrix(int n, int m, int k, vector<vector<int>> mat) { if(mat.size()==0&&mat[0].size()==0) { return {}; } for(int i=0;i<n;i++) {=\"\" m=\"mat[i].size();\" vector<int=\"\">v(m),temp(m); k=k%m; for(int j=0;j<m;j++) {=\"\" v[j]=\"mat[i][j];\" }=\"\" for(int=\"\" j=\"0;j&lt;m;j++)\" {=\"\" temp[((j+(m-k))+m)%m]=\"v[j];\" }=\"\" for(int=\"\" j=\"0;j&lt;m;j++)\" {=\"\" mat[i][j]=\"temp[j];\" }=\"\" }=\"\" return=\"\" mat;=\"\" }=\"\" };<=\"\" u=\"\">" }, { "code": null, "e": 3167, "s": 3165, "text": "0" }, { "code": null, "e": 3190, "s": 3167, "text": "dilip suthar1 year ago" }, { "code": null, "e": 3203, "s": 3190, "text": "dilip suthar" }, { "code": null, "e": 3727, "s": 3203, "text": "class Solution { public: vector<vector<int>> rotateMatrix(int n, int m, int k, vector<vector<int>> mat) { if(mat.size()==0&&mat[0].size()==0) { return {}; } for(int i=0;i<n;i++) {=\"\" m=\"mat[i].size();\" vector<int=\"\">v(m),temp(m); k=k%m; for(int j=0;j<m;j++) {=\"\" v[j]=\"mat[i][j];\" }=\"\" for(int=\"\" j=\"0;j&lt;m;j++)\" {=\"\" temp[((j+(m-k))+m)%m]=\"v[j];\" }=\"\" for(int=\"\" j=\"0;j&lt;m;j++)\" {=\"\" mat[i][j]=\"temp[j];\" }=\"\" }=\"\" return=\"\" mat;=\"\" }=\"\" };<=\"\" b=\"\">" }, { "code": null, "e": 3729, "s": 3727, "text": "0" }, { "code": null, "e": 3752, "s": 3729, "text": "dilip suthar1 year ago" }, { "code": null, "e": 3765, "s": 3752, "text": "dilip suthar" }, { "code": null, "e": 4296, "s": 3765, "text": "class Solution { public: vector<vector<int>> rotateMatrix(int n, int m, int k, vector<vector<int>> mat) { if(mat.size()==0&&mat[0].size()==0) { return {}; } for(int i=0;i<n;i++) {=\"\" m=\"mat[i].size();\" vector<int=\"\">v(m),temp(m); k=k%m; for(int j=0;j<m;j++) {=\"\" v[j]=\"mat[i][j];\" }=\"\" for(int=\"\" j=\"0;j&lt;m;j++)\" {=\"\" temp[((j+(m-k))+m)%m]=\"v[j];\" }=\"\" for(int=\"\" j=\"0;j&lt;m;j++)\" {=\"\" mat[i][j]=\"temp[j];\" }=\"\" }=\"\" return=\"\" mat;=\"\" }=\"\" };=\"\" <=\"\" code=\"\">" }, { "code": null, "e": 4298, "s": 4296, "text": "0" }, { "code": null, "e": 4327, "s": 4298, "text": "MD. TASNIN TANVIR2 years ago" }, { "code": null, "e": 4345, "s": 4327, "text": "MD. TASNIN TANVIR" }, { "code": null, "e": 4393, "s": 4345, "text": "Easy c++ solutionhttps://ide.geeksforgeeks.o..." }, { "code": null, "e": 4539, "s": 4393, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 4575, "s": 4539, "text": " Login to access your submissions. " }, { "code": null, "e": 4585, "s": 4575, "text": "\nProblem\n" }, { "code": null, "e": 4595, "s": 4585, "text": "\nContest\n" }, { "code": null, "e": 4658, "s": 4595, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 4806, "s": 4658, "text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 5014, "s": 4806, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints." }, { "code": null, "e": 5120, "s": 5014, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Create a Form Dynamically using Dform and jQuery - GeeksforGeeks
27 Jul, 2020 If you have ever used Google forms, you might have wondered how does it work. How an end-user can create there form dynamically. If these questions ever came across your mind, then this article can help you. Prerequisite: Basic of HTML and CSS Basic of JQuery The plugin which we are going to use here is dform. The jQuery.dForm plugin generates HTML markup from JavaScript objects and JSON for HTML forms. What you can do with the dform plugin? You can naturally, generate JavaScript-enhanced markup with your own extensions and custom types. You can use JSON and JavaScript instead of HTML markup. It’s an easy way to include JQuery UI elements. Scaffold forms from business objects of your server-side framework. For More Details you can refer here: Click Here How to use this plugin? Create an empty file, name it index.js to use it in our HTML file. Click here and copy the whole text, paste it in index.js. Save index.js. The plugin is ready to use. Approach: We will use type classifiers for adding form input fields. See the myFunction1 and myFunction2 in code for used classifiers and their attributes. Each and every attribute could be used in the same way. Types of Classifiers: All the type classifiers are sent in the function in JSON format. Here are some type classifiers: {“type” : “container”} {“type” : “div”} Example: Here is the basic example to show how this can be used. HTML <!DOCTYPE html><html> <body> <!-- Including jQuery --> <script src="https://code.jquery.com/jquery-1.12.4.min.js"> </script> <!-- Including index.js that we had just created --> <script type="text/javascript" src="index.js"> </script> <script> $(document).ready(function () { // Defining myFunction1 $.fn.myFunction1 = function () { $("#myform").dform({ "html": [{ // Other attributes "name": "username", "id": "txt-username", "caption": "username", // Type Classifier "type": "text", "placeholder": "E.g. [email protected]" }, { "type": "br" } ] }); } $(".call-btn-text").click(function () { // Calling myFunction1 on click $.fn.myFunction1(); }); }); $(document).ready(function () { // Defining myFunction2 $.fn.myFunction2 = function () { $("#myform").dform({ "html": [{ // Other attributes "name": "PhoneNumber", "id": "num_phone", "caption": "Phone Number", // Type Classifier "type": "number", "placeholder": "E.g. 0123456789" }, { "type": "br" } ] }); } $(".call-btn-number").click(function () { // Calling myFunction2 on click $.fn.myFunction2(); }); }); </script> <form> <input type="button" class="call-btn-text" value=" Click me to input text"> <br> <input type="button" value= "Click me to input number" class="call-btn-number"> <br> </form> <form id="myform"></form></body> </html> Output: Before Clicking the Button: When the page loads After Clicking First Button: After Clicking First Button After Clicking Second Button: After Clicking Second Button CSS-Misc HTML-Misc JavaScript-Misc jQuery-Misc CSS HTML JavaScript JQuery Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Create a Responsive Navbar using ReactJS Design a web page using HTML and CSS How to set div width to fit content using CSS ? Making a div vertically scrollable using CSS How to set fixed width for <td> in a table ? How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ? Hide or show elements in HTML using display property How to Insert Form Data into Database using PHP ? REST API (Introduction)
[ { "code": null, "e": 24498, "s": 24470, "text": "\n27 Jul, 2020" }, { "code": null, "e": 24706, "s": 24498, "text": "If you have ever used Google forms, you might have wondered how does it work. How an end-user can create there form dynamically. If these questions ever came across your mind, then this article can help you." }, { "code": null, "e": 24720, "s": 24706, "text": "Prerequisite:" }, { "code": null, "e": 24742, "s": 24720, "text": "Basic of HTML and CSS" }, { "code": null, "e": 24758, "s": 24742, "text": "Basic of JQuery" }, { "code": null, "e": 24905, "s": 24758, "text": "The plugin which we are going to use here is dform. The jQuery.dForm plugin generates HTML markup from JavaScript objects and JSON for HTML forms." }, { "code": null, "e": 24944, "s": 24905, "text": "What you can do with the dform plugin?" }, { "code": null, "e": 25042, "s": 24944, "text": "You can naturally, generate JavaScript-enhanced markup with your own extensions and custom types." }, { "code": null, "e": 25098, "s": 25042, "text": "You can use JSON and JavaScript instead of HTML markup." }, { "code": null, "e": 25146, "s": 25098, "text": "It’s an easy way to include JQuery UI elements." }, { "code": null, "e": 25214, "s": 25146, "text": "Scaffold forms from business objects of your server-side framework." }, { "code": null, "e": 25263, "s": 25214, "text": "For More Details you can refer here: Click Here" }, { "code": null, "e": 25287, "s": 25263, "text": "How to use this plugin?" }, { "code": null, "e": 25354, "s": 25287, "text": "Create an empty file, name it index.js to use it in our HTML file." }, { "code": null, "e": 25412, "s": 25354, "text": "Click here and copy the whole text, paste it in index.js." }, { "code": null, "e": 25427, "s": 25412, "text": "Save index.js." }, { "code": null, "e": 25455, "s": 25427, "text": "The plugin is ready to use." }, { "code": null, "e": 25465, "s": 25455, "text": "Approach:" }, { "code": null, "e": 25524, "s": 25465, "text": "We will use type classifiers for adding form input fields." }, { "code": null, "e": 25667, "s": 25524, "text": "See the myFunction1 and myFunction2 in code for used classifiers and their attributes. Each and every attribute could be used in the same way." }, { "code": null, "e": 25787, "s": 25667, "text": "Types of Classifiers: All the type classifiers are sent in the function in JSON format. Here are some type classifiers:" }, { "code": null, "e": 25810, "s": 25787, "text": "{“type” : “container”}" }, { "code": null, "e": 25827, "s": 25810, "text": "{“type” : “div”}" }, { "code": null, "e": 25892, "s": 25827, "text": "Example: Here is the basic example to show how this can be used." }, { "code": null, "e": 25897, "s": 25892, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <body> <!-- Including jQuery --> <script src=\"https://code.jquery.com/jquery-1.12.4.min.js\"> </script> <!-- Including index.js that we had just created --> <script type=\"text/javascript\" src=\"index.js\"> </script> <script> $(document).ready(function () { // Defining myFunction1 $.fn.myFunction1 = function () { $(\"#myform\").dform({ \"html\": [{ // Other attributes \"name\": \"username\", \"id\": \"txt-username\", \"caption\": \"username\", // Type Classifier \"type\": \"text\", \"placeholder\": \"E.g. [email protected]\" }, { \"type\": \"br\" } ] }); } $(\".call-btn-text\").click(function () { // Calling myFunction1 on click $.fn.myFunction1(); }); }); $(document).ready(function () { // Defining myFunction2 $.fn.myFunction2 = function () { $(\"#myform\").dform({ \"html\": [{ // Other attributes \"name\": \"PhoneNumber\", \"id\": \"num_phone\", \"caption\": \"Phone Number\", // Type Classifier \"type\": \"number\", \"placeholder\": \"E.g. 0123456789\" }, { \"type\": \"br\" } ] }); } $(\".call-btn-number\").click(function () { // Calling myFunction2 on click $.fn.myFunction2(); }); }); </script> <form> <input type=\"button\" class=\"call-btn-text\" value=\" Click me to input text\"> <br> <input type=\"button\" value= \"Click me to input number\" class=\"call-btn-number\"> <br> </form> <form id=\"myform\"></form></body> </html>", "e": 28104, "s": 25897, "text": null }, { "code": null, "e": 28112, "s": 28104, "text": "Output:" }, { "code": null, "e": 28140, "s": 28112, "text": "Before Clicking the Button:" }, { "code": null, "e": 28160, "s": 28140, "text": "When the page loads" }, { "code": null, "e": 28189, "s": 28160, "text": "After Clicking First Button:" }, { "code": null, "e": 28217, "s": 28189, "text": "After Clicking First Button" }, { "code": null, "e": 28247, "s": 28217, "text": "After Clicking Second Button:" }, { "code": null, "e": 28276, "s": 28247, "text": "After Clicking Second Button" }, { "code": null, "e": 28285, "s": 28276, "text": "CSS-Misc" }, { "code": null, "e": 28295, "s": 28285, "text": "HTML-Misc" }, { "code": null, "e": 28311, "s": 28295, "text": "JavaScript-Misc" }, { "code": null, "e": 28323, "s": 28311, "text": "jQuery-Misc" }, { "code": null, "e": 28327, "s": 28323, "text": "CSS" }, { "code": null, "e": 28332, "s": 28327, "text": "HTML" }, { "code": null, "e": 28343, "s": 28332, "text": "JavaScript" }, { "code": null, "e": 28350, "s": 28343, "text": "JQuery" }, { "code": null, "e": 28367, "s": 28350, "text": "Web Technologies" }, { "code": null, "e": 28394, "s": 28367, "text": "Web technologies Questions" }, { "code": null, "e": 28399, "s": 28394, "text": "HTML" }, { "code": null, "e": 28497, "s": 28399, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28506, "s": 28497, "text": "Comments" }, { "code": null, "e": 28519, "s": 28506, "text": "Old Comments" }, { "code": null, "e": 28560, "s": 28519, "text": "Create a Responsive Navbar using ReactJS" }, { "code": null, "e": 28597, "s": 28560, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 28645, "s": 28597, "text": "How to set div width to fit content using CSS ?" }, { "code": null, "e": 28690, "s": 28645, "text": "Making a div vertically scrollable using CSS" }, { "code": null, "e": 28735, "s": 28690, "text": "How to set fixed width for <td> in a table ?" }, { "code": null, "e": 28795, "s": 28735, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 28856, "s": 28795, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 28909, "s": 28856, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 28959, "s": 28909, "text": "How to Insert Form Data into Database using PHP ?" } ]
JavaScript - Date getFullYear() Method
Javascript date getFullYear() method returns the year of the specified date according to local time. The value returned by getFullYear() is an absolute number. For dates between the years 1000 and 9999, getFullYear() returns a four-digit number, for example, 2008. Its syntax is as follows − Date.getFullYear() Returns the year of the specified date according to local time. Try the following example. <html> <head> <title>JavaScript getFullYear Method</title> </head> <body> <script type = "text/javascript"> var dt = new Date("December 25, 1995 23:15:00"); document.write("getFullYear() : " + dt.getFullYear() ); </script> </body> </html> getFullYear() : 1995 25 Lectures 2.5 hours Anadi Sharma 74 Lectures 10 hours Lets Kode It 72 Lectures 4.5 hours Frahaan Hussain 70 Lectures 4.5 hours Frahaan Hussain 46 Lectures 6 hours Eduonix Learning Solutions 88 Lectures 14 hours Eduonix Learning Solutions Print Add Notes Bookmark this page
[ { "code": null, "e": 2731, "s": 2466, "text": "Javascript date getFullYear() method returns the year of the specified date according to local time. The value returned by getFullYear() is an absolute number. For dates between the years 1000 and 9999, getFullYear() returns a four-digit number, for example, 2008." }, { "code": null, "e": 2758, "s": 2731, "text": "Its syntax is as follows −" }, { "code": null, "e": 2778, "s": 2758, "text": "Date.getFullYear()\n" }, { "code": null, "e": 2842, "s": 2778, "text": "Returns the year of the specified date according to local time." }, { "code": null, "e": 2869, "s": 2842, "text": "Try the following example." }, { "code": null, "e": 3170, "s": 2869, "text": "<html>\n <head>\n <title>JavaScript getFullYear Method</title>\n </head>\n \n <body> \n <script type = \"text/javascript\">\n var dt = new Date(\"December 25, 1995 23:15:00\");\n document.write(\"getFullYear() : \" + dt.getFullYear() ); \n </script> \n </body>\n</html>" }, { "code": null, "e": 3193, "s": 3170, "text": "getFullYear() : 1995 \n" }, { "code": null, "e": 3228, "s": 3193, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3242, "s": 3228, "text": " Anadi Sharma" }, { "code": null, "e": 3276, "s": 3242, "text": "\n 74 Lectures \n 10 hours \n" }, { "code": null, "e": 3290, "s": 3276, "text": " Lets Kode It" }, { "code": null, "e": 3325, "s": 3290, "text": "\n 72 Lectures \n 4.5 hours \n" }, { "code": null, "e": 3342, "s": 3325, "text": " Frahaan Hussain" }, { "code": null, "e": 3377, "s": 3342, "text": "\n 70 Lectures \n 4.5 hours \n" }, { "code": null, "e": 3394, "s": 3377, "text": " Frahaan Hussain" }, { "code": null, "e": 3427, "s": 3394, "text": "\n 46 Lectures \n 6 hours \n" }, { "code": null, "e": 3455, "s": 3427, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3489, "s": 3455, "text": "\n 88 Lectures \n 14 hours \n" }, { "code": null, "e": 3517, "s": 3489, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3524, "s": 3517, "text": " Print" }, { "code": null, "e": 3535, "s": 3524, "text": " Add Notes" } ]
Impala - Create a Database
In Impala, a database is a construct which holds related tables, views, and functions within their namespaces. It is represented as a directory tree in HDFS; it contains tables partitions, and data files. This chapter explains how to create a database in Impala. The CREATE DATABASE Statement is used to create a new database in Impala. Following is the syntax of the CREATE DATABASE Statement. CREATE DATABASE IF NOT EXISTS database_name; Here, IF NOT EXISTS is an optional clause. If we use this clause, a database with the given name is created, only if there is no existing database with the same name. Following is an example of the create database statement. In this example, we have created a database with the name my_database. [quickstart.cloudera:21000] > CREATE DATABASE IF NOT EXISTS my_database; On executing the above query in cloudera impala-shell, you will get the following output. Query: create DATABASE my_database Fetched 0 row(s) in 0.21s The SHOW DATABASES query gives the list of the databases in Impala, therefore you can verify whether the database is created, using the SHOW DATABASES statement. Here you can observe the newly created database my_db in the list. [quickstart.cloudera:21000] > show databases; Query: show databases +-----------------------------------------------+ | name | +-----------------------------------------------+ | _impala_builtins | | default | | my_db | +-----------------------------------------------+ Fetched 3 row(s) in 0.20s [quickstart.cloudera:21000] > In order to create a database in HDFS file system, you need to specify the location where the database is to be created. CREATE DATABASE IF NOT EXISTS database_name LOCATION hdfs_path; Open Impala Query editor and type the CREATE DATABASE statement in it. Thereafter, click the execute button as shown in the following screenshot. After executing the query, gently move the curser to the top of the dropdown menu and you will find a refresh symbol. If you click on the refresh symbol, the list of databases will be refreshed and the recent changes are applied to it. Click the drop-down box under the heading DATABASE on the left-hand side of the editor. There you can see a list of databases in the system. Here you can observe the newly created database my_db as shown below. If you observe carefully, you can see only one database, i.e., my_db in the list along with the default database. Print Add Notes Bookmark this page
[ { "code": null, "e": 2548, "s": 2285, "text": "In Impala, a database is a construct which holds related tables, views, and functions within their namespaces. It is represented as a directory tree in HDFS; it contains tables partitions, and data files. This chapter explains how to create a database in Impala." }, { "code": null, "e": 2622, "s": 2548, "text": "The CREATE DATABASE Statement is used to create a new database in Impala." }, { "code": null, "e": 2680, "s": 2622, "text": "Following is the syntax of the CREATE DATABASE Statement." }, { "code": null, "e": 2726, "s": 2680, "text": "CREATE DATABASE IF NOT EXISTS database_name;\n" }, { "code": null, "e": 2893, "s": 2726, "text": "Here, IF NOT EXISTS is an optional clause. If we use this clause, a database with the given name is created, only if there is no existing database with the same name." }, { "code": null, "e": 3022, "s": 2893, "text": "Following is an example of the create database statement. In this example, we have created a database with the name my_database." }, { "code": null, "e": 3095, "s": 3022, "text": "[quickstart.cloudera:21000] > CREATE DATABASE IF NOT EXISTS my_database;" }, { "code": null, "e": 3185, "s": 3095, "text": "On executing the above query in cloudera impala-shell, you will get the following output." }, { "code": null, "e": 3249, "s": 3185, "text": "Query: create DATABASE my_database \n\nFetched 0 row(s) in 0.21s\n" }, { "code": null, "e": 3478, "s": 3249, "text": "The SHOW DATABASES query gives the list of the databases in Impala, therefore you can verify whether the database is created, using the SHOW DATABASES statement. Here you can observe the newly created database my_db in the list." }, { "code": null, "e": 3960, "s": 3478, "text": "[quickstart.cloudera:21000] > show databases; \n\nQuery: show databases\n+-----------------------------------------------+\n| name | \n+-----------------------------------------------+ \n| _impala_builtins |\n| default | \n| my_db | \n+-----------------------------------------------+\nFetched 3 row(s) in 0.20s \n[quickstart.cloudera:21000] >\n" }, { "code": null, "e": 4081, "s": 3960, "text": "In order to create a database in HDFS file system, you need to specify the location where the database is to be created." }, { "code": null, "e": 4146, "s": 4081, "text": "CREATE DATABASE IF NOT EXISTS database_name LOCATION hdfs_path;\n" }, { "code": null, "e": 4292, "s": 4146, "text": "Open Impala Query editor and type the CREATE DATABASE statement in it. Thereafter, click the execute button as shown in the following screenshot." }, { "code": null, "e": 4528, "s": 4292, "text": "After executing the query, gently move the curser to the top of the dropdown menu and you will find a refresh symbol. If you click on the refresh symbol, the list of databases will be refreshed and the recent changes are applied to it." }, { "code": null, "e": 4739, "s": 4528, "text": "Click the drop-down box under the heading DATABASE on the left-hand side of the editor. There you can see a list of databases in the system. Here you can observe the newly created database my_db as shown below." }, { "code": null, "e": 4853, "s": 4739, "text": "If you observe carefully, you can see only one database, i.e., my_db in the list along with the default database." }, { "code": null, "e": 4860, "s": 4853, "text": " Print" }, { "code": null, "e": 4871, "s": 4860, "text": " Add Notes" } ]
Cypress - Prompt Pop-up Window
Cypress can handle prompt pop-up windows, where users can input values. A prompt has a text field, where the input is taken. To handle a prompt pop-up, cy.window() method is used. It obtains the value of the object of the prompt (remote window). In a confirmation/alert pop-up, we have to fire a browser event. But for prompt pop-up, we have to use cy.stub() method. Let us look at the below example, on clicking the Click for JS Prompt button, a prompt pop up gets displayed, as shown below − The following prompt with the user input field gets displayed. Tutorialspoint is entered in the prompt pop-up, as shown below. You entered − Tutorialspoint gets displayed under Result. This can be seen in the screen displayed below − Given below is an implementation of the commands for displaying prompt pop-up windows in Cypress − describe('Tutorialspoint Test', function () { // test case it("Scenario 1", function () { //URL launch cy.visit("https://the-internet.herokuapp.com/javascript_alerts") //handling prompt alert cy.window().then(function(p){ //stubbing prompt window cy.stub(p, "prompt").returns("Tutorialspoint"); // click on Click for JS Prompt button cy.get(':nth-child(3) > button').click() // verify application message on clicking on OK cy.get('#result').contains('You entered: Tutorialspoint') }); }); }); Execution Results The output is as follows − The output logs show the successful verification of the text. You entered − Tutorialspoint, is produced on clicking OK button on prompt pop up. Also, the stub applied on the prompt window is visible on the output log. 73 Lectures 12 hours Rahul Shetty Print Add Notes Bookmark this page
[ { "code": null, "e": 2677, "s": 2497, "text": "Cypress can handle prompt pop-up windows, where users can input values. A prompt has a text field, where the input is taken. To handle a prompt pop-up, cy.window() method is used." }, { "code": null, "e": 2864, "s": 2677, "text": "It obtains the value of the object of the prompt (remote window). In a confirmation/alert pop-up, we have to fire a browser event. But for prompt pop-up, we have to use cy.stub() method." }, { "code": null, "e": 2991, "s": 2864, "text": "Let us look at the below example, on clicking the Click for JS Prompt button, a prompt pop up gets displayed, as shown below −" }, { "code": null, "e": 3118, "s": 2991, "text": "The following prompt with the user input field gets displayed. Tutorialspoint is entered in the prompt pop-up, as shown below." }, { "code": null, "e": 3176, "s": 3118, "text": "You entered − Tutorialspoint gets displayed under Result." }, { "code": null, "e": 3225, "s": 3176, "text": "This can be seen in the screen displayed below −" }, { "code": null, "e": 3324, "s": 3225, "text": "Given below is an implementation of the commands for displaying prompt pop-up windows in Cypress −" }, { "code": null, "e": 3913, "s": 3324, "text": "describe('Tutorialspoint Test', function () {\n // test case\n it(\"Scenario 1\", function () {\n //URL launch\n cy.visit(\"https://the-internet.herokuapp.com/javascript_alerts\")\n //handling prompt alert\n cy.window().then(function(p){\n //stubbing prompt window\n cy.stub(p, \"prompt\").returns(\"Tutorialspoint\");\n // click on Click for JS Prompt button\n cy.get(':nth-child(3) > button').click()\n // verify application message on clicking on OK\n cy.get('#result').contains('You entered: Tutorialspoint')\n });\n });\n}); " }, { "code": null, "e": 3931, "s": 3913, "text": "Execution Results" }, { "code": null, "e": 3958, "s": 3931, "text": "The output is as follows −" }, { "code": null, "e": 4020, "s": 3958, "text": "The output logs show the successful verification of the text." }, { "code": null, "e": 4176, "s": 4020, "text": "You entered − Tutorialspoint, is produced on clicking OK button on prompt pop up. Also,\nthe stub applied on the prompt window is visible on the output log." }, { "code": null, "e": 4210, "s": 4176, "text": "\n 73 Lectures \n 12 hours \n" }, { "code": null, "e": 4224, "s": 4210, "text": " Rahul Shetty" }, { "code": null, "e": 4231, "s": 4224, "text": " Print" }, { "code": null, "e": 4242, "s": 4231, "text": " Add Notes" } ]
Building Custom Layers on AWS Lambda | by Israel Aminu | Towards Data Science
Many developers face issues when importing custom modules on AWS Lambda, you see errors like “No module named pandas” or “No module named numpy”, and most times, the easiest ways to solve this is to bundle your lambda function code with the module and deploy it on AWS lambda which at the end makes the whole project large and doesn't give room for flexibility. To solve this problem, we use something called Layers on AWS Lambda. According to the docs, A layer is a ZIP archive that contains libraries, a custom runtime, or other dependencies. With layers, you can use libraries in your function without needing to include them in your deployment package. Layers let you install all the modules you need for your application to run, it provides that flexibility for you deploy your lambda function and even with layers you can even make your own custom code and add external functionality as a layer itself. It saves you the stress of managing packages and allows you to focus more on your code. Makes your deployment package smaller and easily deployable The layer can also be used across other lambda functions. Make code changes quickly on the console. Lambda layers enable versioning, which allows you to add more packages and also use previous package versions when needed. Now that we know what layers and see how useful it is, let’s build one 🚀. Create a new directory and navigate to the directory on your computer: israel@israel:~$ mkdir my-lambda-layer && cd my-lambda-layer Next, create a folder structure for the modules that you need to install: israel@israel:~/my-lambda-layer$ mkdir -p aws-layer/python/lib/python3.7/site-packages The folder structure is essential because that is where Python expects to find the modules you’ve installed. For this article, I used python 3.7, if you want to use a different python version, change the python3.7 in the folder above to the desired version. Let’s install our libraries. To install just a single module for your application, use the following command, in this example I’ll be using numpy. israel@israel:~/my-lambda-layer$ pip3 install numpy --target aws-layer/python/lib/python3.7/site-packages To install multiple modules, create a requirements.txt file in the base directory and add the modules with their respective versions: israel@israel:~/my-lambda-layer$ nano requirements.txt Add your modules, just like in the image below: Then install them with the command below: israel@israel:~/my-lambda-layer$ pip3 install -r requirements.txt --target aws-layer/python/lib/python3.7/site-packages You should have a folder tree like this: Next, we navigate to the lambda-layer directory and create a zip file for the layer that will be uploaded. israel@israel:~/my-lambda-layer$ cd aws-layer Now zip the entire folder: israel@israel:~/my-lambda-layer/aws-layer$ zip -r9 lambda-layer.zip . After zipping the packages it will have the name “lambda-layer.zip” You can upload the zip file to your lambda layer using AWS CLI or using the AWS web Console, for this article I’ll be using the AWS CLI To create the lambda layer automatically using the AWS CLI you can use the command below: aws lambda publish-layer-version \ --layer-name Data-Preprocessing \ --description "My Python layer" \ --zip-file fileb://lambda-layer.zip \ --compatible-runtimes python3.7 And you’ll see the lambda layer created in your Web Console. Also, be sure to set your credentials and permissions on the AWS CLI to deploy the layer. To test the Lambda Layer, I simply created a new Lambda function and added my layer to it, you can do this by simply clicking on Layers, then click on the custom layer option and select the layer you just deployed to Lambda, at the end, you should see an image below: Then on the function, I imported Pandas and numpy Then I tested the function and got the following response From the image, our code was able to run successfully and we could import external packages for our application. So far we've been able to see the beauty of layers and how powerful they are, you should always use them wherever you want to use external modules or even when you have your own custom code you’ve written. Thanks for reading 😊.
[ { "code": null, "e": 603, "s": 172, "text": "Many developers face issues when importing custom modules on AWS Lambda, you see errors like “No module named pandas” or “No module named numpy”, and most times, the easiest ways to solve this is to bundle your lambda function code with the module and deploy it on AWS lambda which at the end makes the whole project large and doesn't give room for flexibility. To solve this problem, we use something called Layers on AWS Lambda." }, { "code": null, "e": 829, "s": 603, "text": "According to the docs, A layer is a ZIP archive that contains libraries, a custom runtime, or other dependencies. With layers, you can use libraries in your function without needing to include them in your deployment package." }, { "code": null, "e": 1169, "s": 829, "text": "Layers let you install all the modules you need for your application to run, it provides that flexibility for you deploy your lambda function and even with layers you can even make your own custom code and add external functionality as a layer itself. It saves you the stress of managing packages and allows you to focus more on your code." }, { "code": null, "e": 1229, "s": 1169, "text": "Makes your deployment package smaller and easily deployable" }, { "code": null, "e": 1287, "s": 1229, "text": "The layer can also be used across other lambda functions." }, { "code": null, "e": 1329, "s": 1287, "text": "Make code changes quickly on the console." }, { "code": null, "e": 1452, "s": 1329, "text": "Lambda layers enable versioning, which allows you to add more packages and also use previous package versions when needed." }, { "code": null, "e": 1526, "s": 1452, "text": "Now that we know what layers and see how useful it is, let’s build one 🚀." }, { "code": null, "e": 1597, "s": 1526, "text": "Create a new directory and navigate to the directory on your computer:" }, { "code": null, "e": 1658, "s": 1597, "text": "israel@israel:~$ mkdir my-lambda-layer && cd my-lambda-layer" }, { "code": null, "e": 1732, "s": 1658, "text": "Next, create a folder structure for the modules that you need to install:" }, { "code": null, "e": 1819, "s": 1732, "text": "israel@israel:~/my-lambda-layer$ mkdir -p aws-layer/python/lib/python3.7/site-packages" }, { "code": null, "e": 2077, "s": 1819, "text": "The folder structure is essential because that is where Python expects to find the modules you’ve installed. For this article, I used python 3.7, if you want to use a different python version, change the python3.7 in the folder above to the desired version." }, { "code": null, "e": 2224, "s": 2077, "text": "Let’s install our libraries. To install just a single module for your application, use the following command, in this example I’ll be using numpy." }, { "code": null, "e": 2330, "s": 2224, "text": "israel@israel:~/my-lambda-layer$ pip3 install numpy --target aws-layer/python/lib/python3.7/site-packages" }, { "code": null, "e": 2464, "s": 2330, "text": "To install multiple modules, create a requirements.txt file in the base directory and add the modules with their respective versions:" }, { "code": null, "e": 2520, "s": 2464, "text": "israel@israel:~/my-lambda-layer$ nano requirements.txt " }, { "code": null, "e": 2568, "s": 2520, "text": "Add your modules, just like in the image below:" }, { "code": null, "e": 2610, "s": 2568, "text": "Then install them with the command below:" }, { "code": null, "e": 2730, "s": 2610, "text": "israel@israel:~/my-lambda-layer$ pip3 install -r requirements.txt --target aws-layer/python/lib/python3.7/site-packages" }, { "code": null, "e": 2771, "s": 2730, "text": "You should have a folder tree like this:" }, { "code": null, "e": 2878, "s": 2771, "text": "Next, we navigate to the lambda-layer directory and create a zip file for the layer that will be uploaded." }, { "code": null, "e": 2924, "s": 2878, "text": "israel@israel:~/my-lambda-layer$ cd aws-layer" }, { "code": null, "e": 2951, "s": 2924, "text": "Now zip the entire folder:" }, { "code": null, "e": 3021, "s": 2951, "text": "israel@israel:~/my-lambda-layer/aws-layer$ zip -r9 lambda-layer.zip ." }, { "code": null, "e": 3089, "s": 3021, "text": "After zipping the packages it will have the name “lambda-layer.zip”" }, { "code": null, "e": 3225, "s": 3089, "text": "You can upload the zip file to your lambda layer using AWS CLI or using the AWS web Console, for this article I’ll be using the AWS CLI" }, { "code": null, "e": 3315, "s": 3225, "text": "To create the lambda layer automatically using the AWS CLI you can use the command below:" }, { "code": null, "e": 3500, "s": 3315, "text": "aws lambda publish-layer-version \\ --layer-name Data-Preprocessing \\ --description \"My Python layer\" \\ --zip-file fileb://lambda-layer.zip \\ --compatible-runtimes python3.7" }, { "code": null, "e": 3651, "s": 3500, "text": "And you’ll see the lambda layer created in your Web Console. Also, be sure to set your credentials and permissions on the AWS CLI to deploy the layer." }, { "code": null, "e": 3919, "s": 3651, "text": "To test the Lambda Layer, I simply created a new Lambda function and added my layer to it, you can do this by simply clicking on Layers, then click on the custom layer option and select the layer you just deployed to Lambda, at the end, you should see an image below:" }, { "code": null, "e": 3969, "s": 3919, "text": "Then on the function, I imported Pandas and numpy" }, { "code": null, "e": 4027, "s": 3969, "text": "Then I tested the function and got the following response" }, { "code": null, "e": 4140, "s": 4027, "text": "From the image, our code was able to run successfully and we could import external packages for our application." }, { "code": null, "e": 4346, "s": 4140, "text": "So far we've been able to see the beauty of layers and how powerful they are, you should always use them wherever you want to use external modules or even when you have your own custom code you’ve written." } ]
How to set a particular font for a button text in Android?
This example demonstrates how do I set a particular font for a button text in 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. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/rl" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="10dp" tools:context=".MainActivity"> <Button android:id="@+id/btnChangeFont" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:text="Click to change font of the Button" /> <Button android:id="@+id/btnChangeFont2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:layout_below="@id/btnChangeFont" android:layout_marginTop="10dp" android:text="Click to change font of the Button" /> </RelativeLayout> Step 3 − Add the following code to src/MainActivity.java import android.graphics.Typeface; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import static android.graphics.Typeface.BOLD_ITALIC; public class MainActivity extends AppCompatActivity { Button btnChangeFont, btnChangeFont2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btnChangeFont = findViewById(R.id.btnChangeFont); btnChangeFont.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { btnChangeFont.setTypeface(Typeface.MONOSPACE,Typeface.BOLD); } }); btnChangeFont2 = findViewById(R.id.btnChangeFont2); btnChangeFont2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { btnChangeFont2.setTypeface(Typeface.SERIF, BOLD_ITALIC); } }); } } Step 4 - Add the following code to androidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen – Click here to download the project code.
[ { "code": null, "e": 1149, "s": 1062, "text": "This example demonstrates how do I set a particular font for a button text in android." }, { "code": null, "e": 1278, "s": 1149, "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": 1343, "s": 1278, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2210, "s": 1343, "text": "<RelativeLayout\n xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:id=\"@+id/rl\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:padding=\"10dp\"\n tools:context=\".MainActivity\">\n <Button\n android:id=\"@+id/btnChangeFont\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerInParent=\"true\"\n android:text=\"Click to change font of the Button\" />\n <Button\n android:id=\"@+id/btnChangeFont2\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerInParent=\"true\"\n android:layout_below=\"@id/btnChangeFont\"\n android:layout_marginTop=\"10dp\"\n android:text=\"Click to change font of the Button\" />\n</RelativeLayout>" }, { "code": null, "e": 2267, "s": 2210, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 3295, "s": 2267, "text": "import android.graphics.Typeface;\nimport android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.widget.Button;\nimport static android.graphics.Typeface.BOLD_ITALIC;\npublic class MainActivity extends AppCompatActivity {\n Button btnChangeFont, btnChangeFont2;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n btnChangeFont = findViewById(R.id.btnChangeFont);\n btnChangeFont.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n btnChangeFont.setTypeface(Typeface.MONOSPACE,Typeface.BOLD);\n }\n });\n btnChangeFont2 = findViewById(R.id.btnChangeFont2);\n btnChangeFont2.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n btnChangeFont2.setTypeface(Typeface.SERIF, BOLD_ITALIC);\n }\n });\n }\n}" }, { "code": null, "e": 3350, "s": 3295, "text": "Step 4 - Add the following code to androidManifest.xml" }, { "code": null, "e": 4023, "s": 3350, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"app.com.sample\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 4370, "s": 4023, "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": 4411, "s": 4370, "text": "Click here to download the project code." } ]
Deep Emotion Recognition based on Facial Expressions | by Stefanos Kanellopoulos | Towards Data Science
Motivated by the dissertation for my MSc in Robotics I decided to write a trilogy of articles. The aspiration behind this endeavor is to share the findings and the knowledge I have acquired through this magical journey. These three articles will mostly take the form of step-by-step coding tutorials while explaining on a theoretical level many technical choices that have been made. Before we start implementing let’s talk about the field of Facial Expression Recognition (FER) a little bit: FER is the scientific research area that deals with techniques and methods that try to identify/infer emotional states from facial expressions. In human communication, facial expressions play a crucial role in inferring emotions that could potentially help in understanding the intentions of others. According to different surveys [1, 2], verbal components convey only one-third of interpersonal communication, and non-verbal components convey two-thirds. The majority of messages related to attitudes and feelings lies in facial expressions. Hence, facial expressions have proven to play a vital role in the entire information exchange process. Expressions and emotions are indissolubly connected. Ekman and Friesen in [3] triggered the first wave of Basic Emotion Theory inspired studies on emotional expression. They used still photographs of prototypical emotional facial expressions and documented some degree of universality in the recognition and production of a limited set of “basic” emotions (happiness 😀, surprise 😮, fear 😨, disgust 🤮, sadness 😭, and anger 😡). These 6 categories are going to be used for our task as well, and CK+48 [4] is the chosen dataset that will help us train and evaluate our model. The whole implementation took place on Google Colab using GPU acceleration. So, without further ado let’s dive into our task... A) First things first, let’s import the necessary libraries as shown below. Right after you store your dataset on your Google Drive, you have to mount your drive and go to the directory, which contains your dataset. The next step is to load our data into the memory, this is why I created two auxiliary functions to make things easier. Below you can see their docstrings that describe their functionality (in order to avoid huge chunks of code in the article). Of course, you can find the full code on my GitHub account. And this is how our data distribution looks like. Note: Ideally, we should have equally distributed classes for our training since the model more frequently encounters examples of “surprise” compared to examples of “fear”. In the end, this will impair the model’s performance, as we will see later on that the majority of the misclassifications will be connected to the classes of “sadness” and “fear”. B) The dataset I have used comprises 927 images of shape 48x48x3. Afterward, we randomly split the dataset into training (70%), validation (15%), and test (15%) sets (generally speaking, this is considered as a good rule of thumb to split our data). An indicative print of the split is shown below. X_train has shape: (648, 48, 48, 3) y_train has shape: (648, 6) X_valid has shape: (139, 48, 48, 3) y_valid has shape: (139, 6) X_test has shape: (140, 48, 48, 3) y_test has shape: (140, 6)X_train + X_valid + X_test = 927 samples in total Note: It is very important for our validation and test set to be drawn from the same distribution. Dr. Andrew Ng explains the reason in a remarkable (and easy to digest) way in this video. The thing is that our data is coming from the same distribution (since it is created under lab constraints) but the largely unequal number of samples among some classes, combined with the relatively small amount of data can harm the efficiency of the model. Ideally, we should somehow “control” the ~140 samples for X_valid and X_test by dedicating ~23 different examples from each category. C) Furthermore, data augmentation is going to be used only on the training samples in order to let the model encounter a variety of different examples since we don’t have so many examples at our disposal, and thus this will help it enhance its predictive performance. Note: Not all parameters of ImageDataGenerator class are relevant. We have to be careful about that. For example, a vertical flip has no meaning for our task and presumably could harm the precision of the model. Some examples of the augmentation applied on the training samples are shown below. I created the function build_model that loads the EfficientNetB0 model pre-trained on ImageNet (without its original classifier) and adds 3 more layers at its top as you can see below. The idea of picking just 3 layers (and not something more complicated) came from the official documentation of Keras that shows how to fine-tune EfficientNet on an Image classification. Additionally, this function compiles the model with an Adam optimizer, a categorical cross-entropy loss function, and accuracy as a metric. In my GitHub repo, I have uploaded the summary of the model as well as the graph of the model, so that you can take a look. As for the training phase I used 3 very helpful callbacks: ModelCheckPoint: Saves the weights of the model with which achieved the best validation accuracy. EarlyStopping: If the validation accuracy does not get improved for 15 consecutive epochs, the training will be interrupted (this callback prevents overfitting) ReduceLROnPlateaue: This is a scheduler that reduces the learning rate (by half) each time the validation accuracy is on a plateau. The combination of the aforementioned callbacks assures that our model won’t overfit. Of course, we can also observe that through our learning curves that we will check in a while. Note: As for the batch size, I experimented with a range of values. For batch sizes 16 and 32, the training time increased (and this is something that it does matter especially when the dataset is considerably large) while the validation accuracy wasn’t even higher compared to a batch of 64 samples. On the other hand, a batch of 128 samples, of course, accelerated the training procedure, however, not only the validation wasn’t better but also there were observed significant oscillations to the learning curves (something that could possibly hamper the convergence of the model). Note: Two very important things that I realized during building this model are: (1) Despite the fact that in most cases pixel normalization is applied to the input images, EfficientNet does this anyway with its Rescale layers, and thus, further pixel-wise division with the value 255. would harm the performance of the model. (2) Despite the fact that the model takes as input tensors of shape (224, 224, 3), I realized that better performance achieved when I modified the Input Layer in order to receive tensors of shape (48, 48, 3), instead of rescaling the dataset to 224x224. The only relevant source I managed to find was from Adrian Rosebrock in one of his articles on pyimagesearch.com. In the end, the model needed only 46 epochs to converge and the training procedure was interrupted from our callback. The corresponding learning curves are shown below. The model seems to fit quite well the new data with a fairly small generalization gap. Both training and validation accuracy approximated 98-99% accuracy. However, the weights of the best version of the model will automatically be loaded. Finally, we are going to test our model on samples that it has not seen again. This set is the test set that is drawn from our initial dataset. The model achieved 96.43% accuracy, and the predictions are depicted through a confusion matrix so that we can thoroughly check the misclassifications of the model. As you can observe from this matrix, the class “sadness” essentially causes the problem. It is absolutely reasonable though, due to the small number of examples that are available. Furthermore do not forget that even for a human, facial expressions that express sadness, fear, disgust, or anger might be confusing anyway, and this can become obvious if you check the augmented samples of facial expressions above, and try to predict the class of each expression on your own. You will realize that there is inherent difficulty on this task even for humans. You can also see some random predictions of the model with a barplot on the right side that shows the confidence of each prediction. In this article, we saw how we can build a classifier of facial expressions that could predict emotions. For this dataset (CK+48), achieving 96.43% accuracy is near to the state-of-the-art performance, and in the next article of this trilogy, we are going to apply a visualization technique (GradCam) that reveals the regions of an image that play a crucial role for a model in order to infer, by applying heatmaps onto the original images. Such techniques are very important for deep learning approaches because they assist in the model’s explainability and interpretability. So, at our next meeting, we will see how we can interpret our model’s inaccuracies and how we can possibly improve it. Thank you so much for your time! (The full project can be found here). [1] Albert Mehrabian. Communication without words. Communication theory, pages 193–200, 2008. [2] Kathrin Kaulard, DouglasWCunningham, Heinrich H Bülthoff, and ChristianWallraven. The mpi facial expression database — a validated database of emotional and conversational facial expressions. PloS one, 7(3), 2012. [3] Paul Ekman, E Richard Sorenson, and Wallace V Friesen. Pan-cultural elements in facial displays of emotion. Science, 164(3875):86–88, 1969. [4] Patrick Lucey, Jeffrey F Cohn, Takeo Kanade, Jason Saragih, Zara Ambadar, and Iain Matthews. The extended cohn-kanade dataset (ck+): A complete dataset for action unit and emotion-specified expression. In 2010 ieee computer society conference on computer vision and pattern recognition-workshops, pages 94–101. IEEE, 2010.
[ { "code": null, "e": 555, "s": 171, "text": "Motivated by the dissertation for my MSc in Robotics I decided to write a trilogy of articles. The aspiration behind this endeavor is to share the findings and the knowledge I have acquired through this magical journey. These three articles will mostly take the form of step-by-step coding tutorials while explaining on a theoretical level many technical choices that have been made." }, { "code": null, "e": 664, "s": 555, "text": "Before we start implementing let’s talk about the field of Facial Expression Recognition (FER) a little bit:" }, { "code": null, "e": 1736, "s": 664, "text": "FER is the scientific research area that deals with techniques and methods that try to identify/infer emotional states from facial expressions. In human communication, facial expressions play a crucial role in inferring emotions that could potentially help in understanding the intentions of others. According to different surveys [1, 2], verbal components convey only one-third of interpersonal communication, and non-verbal components convey two-thirds. The majority of messages related to attitudes and feelings lies in facial expressions. Hence, facial expressions have proven to play a vital role in the entire information exchange process. Expressions and emotions are indissolubly connected. Ekman and Friesen in [3] triggered the first wave of Basic Emotion Theory inspired studies on emotional expression. They used still photographs of prototypical emotional facial expressions and documented some degree of universality in the recognition and production of a limited set of “basic” emotions (happiness 😀, surprise 😮, fear 😨, disgust 🤮, sadness 😭, and anger 😡)." }, { "code": null, "e": 2010, "s": 1736, "text": "These 6 categories are going to be used for our task as well, and CK+48 [4] is the chosen dataset that will help us train and evaluate our model. The whole implementation took place on Google Colab using GPU acceleration. So, without further ado let’s dive into our task..." }, { "code": null, "e": 2086, "s": 2010, "text": "A) First things first, let’s import the necessary libraries as shown below." }, { "code": null, "e": 2226, "s": 2086, "text": "Right after you store your dataset on your Google Drive, you have to mount your drive and go to the directory, which contains your dataset." }, { "code": null, "e": 2531, "s": 2226, "text": "The next step is to load our data into the memory, this is why I created two auxiliary functions to make things easier. Below you can see their docstrings that describe their functionality (in order to avoid huge chunks of code in the article). Of course, you can find the full code on my GitHub account." }, { "code": null, "e": 2581, "s": 2531, "text": "And this is how our data distribution looks like." }, { "code": null, "e": 2934, "s": 2581, "text": "Note: Ideally, we should have equally distributed classes for our training since the model more frequently encounters examples of “surprise” compared to examples of “fear”. In the end, this will impair the model’s performance, as we will see later on that the majority of the misclassifications will be connected to the classes of “sadness” and “fear”." }, { "code": null, "e": 3184, "s": 2934, "text": "B) The dataset I have used comprises 927 images of shape 48x48x3. Afterward, we randomly split the dataset into training (70%), validation (15%), and test (15%) sets (generally speaking, this is considered as a good rule of thumb to split our data)." }, { "code": null, "e": 3233, "s": 3184, "text": "An indicative print of the split is shown below." }, { "code": null, "e": 3474, "s": 3233, "text": "X_train has shape: (648, 48, 48, 3) y_train has shape: (648, 6) X_valid has shape: (139, 48, 48, 3) y_valid has shape: (139, 6) X_test has shape: (140, 48, 48, 3) y_test has shape: (140, 6)X_train + X_valid + X_test = 927 samples in total" }, { "code": null, "e": 4055, "s": 3474, "text": "Note: It is very important for our validation and test set to be drawn from the same distribution. Dr. Andrew Ng explains the reason in a remarkable (and easy to digest) way in this video. The thing is that our data is coming from the same distribution (since it is created under lab constraints) but the largely unequal number of samples among some classes, combined with the relatively small amount of data can harm the efficiency of the model. Ideally, we should somehow “control” the ~140 samples for X_valid and X_test by dedicating ~23 different examples from each category." }, { "code": null, "e": 4323, "s": 4055, "text": "C) Furthermore, data augmentation is going to be used only on the training samples in order to let the model encounter a variety of different examples since we don’t have so many examples at our disposal, and thus this will help it enhance its predictive performance." }, { "code": null, "e": 4535, "s": 4323, "text": "Note: Not all parameters of ImageDataGenerator class are relevant. We have to be careful about that. For example, a vertical flip has no meaning for our task and presumably could harm the precision of the model." }, { "code": null, "e": 4618, "s": 4535, "text": "Some examples of the augmentation applied on the training samples are shown below." }, { "code": null, "e": 5129, "s": 4618, "text": "I created the function build_model that loads the EfficientNetB0 model pre-trained on ImageNet (without its original classifier) and adds 3 more layers at its top as you can see below. The idea of picking just 3 layers (and not something more complicated) came from the official documentation of Keras that shows how to fine-tune EfficientNet on an Image classification. Additionally, this function compiles the model with an Adam optimizer, a categorical cross-entropy loss function, and accuracy as a metric." }, { "code": null, "e": 5253, "s": 5129, "text": "In my GitHub repo, I have uploaded the summary of the model as well as the graph of the model, so that you can take a look." }, { "code": null, "e": 5312, "s": 5253, "text": "As for the training phase I used 3 very helpful callbacks:" }, { "code": null, "e": 5410, "s": 5312, "text": "ModelCheckPoint: Saves the weights of the model with which achieved the best validation accuracy." }, { "code": null, "e": 5571, "s": 5410, "text": "EarlyStopping: If the validation accuracy does not get improved for 15 consecutive epochs, the training will be interrupted (this callback prevents overfitting)" }, { "code": null, "e": 5703, "s": 5571, "text": "ReduceLROnPlateaue: This is a scheduler that reduces the learning rate (by half) each time the validation accuracy is on a plateau." }, { "code": null, "e": 5884, "s": 5703, "text": "The combination of the aforementioned callbacks assures that our model won’t overfit. Of course, we can also observe that through our learning curves that we will check in a while." }, { "code": null, "e": 6468, "s": 5884, "text": "Note: As for the batch size, I experimented with a range of values. For batch sizes 16 and 32, the training time increased (and this is something that it does matter especially when the dataset is considerably large) while the validation accuracy wasn’t even higher compared to a batch of 64 samples. On the other hand, a batch of 128 samples, of course, accelerated the training procedure, however, not only the validation wasn’t better but also there were observed significant oscillations to the learning curves (something that could possibly hamper the convergence of the model)." }, { "code": null, "e": 7162, "s": 6468, "text": "Note: Two very important things that I realized during building this model are: (1) Despite the fact that in most cases pixel normalization is applied to the input images, EfficientNet does this anyway with its Rescale layers, and thus, further pixel-wise division with the value 255. would harm the performance of the model. (2) Despite the fact that the model takes as input tensors of shape (224, 224, 3), I realized that better performance achieved when I modified the Input Layer in order to receive tensors of shape (48, 48, 3), instead of rescaling the dataset to 224x224. The only relevant source I managed to find was from Adrian Rosebrock in one of his articles on pyimagesearch.com." }, { "code": null, "e": 7331, "s": 7162, "text": "In the end, the model needed only 46 epochs to converge and the training procedure was interrupted from our callback. The corresponding learning curves are shown below." }, { "code": null, "e": 7570, "s": 7331, "text": "The model seems to fit quite well the new data with a fairly small generalization gap. Both training and validation accuracy approximated 98-99% accuracy. However, the weights of the best version of the model will automatically be loaded." }, { "code": null, "e": 7879, "s": 7570, "text": "Finally, we are going to test our model on samples that it has not seen again. This set is the test set that is drawn from our initial dataset. The model achieved 96.43% accuracy, and the predictions are depicted through a confusion matrix so that we can thoroughly check the misclassifications of the model." }, { "code": null, "e": 8435, "s": 7879, "text": "As you can observe from this matrix, the class “sadness” essentially causes the problem. It is absolutely reasonable though, due to the small number of examples that are available. Furthermore do not forget that even for a human, facial expressions that express sadness, fear, disgust, or anger might be confusing anyway, and this can become obvious if you check the augmented samples of facial expressions above, and try to predict the class of each expression on your own. You will realize that there is inherent difficulty on this task even for humans." }, { "code": null, "e": 8568, "s": 8435, "text": "You can also see some random predictions of the model with a barplot on the right side that shows the confidence of each prediction." }, { "code": null, "e": 9264, "s": 8568, "text": "In this article, we saw how we can build a classifier of facial expressions that could predict emotions. For this dataset (CK+48), achieving 96.43% accuracy is near to the state-of-the-art performance, and in the next article of this trilogy, we are going to apply a visualization technique (GradCam) that reveals the regions of an image that play a crucial role for a model in order to infer, by applying heatmaps onto the original images. Such techniques are very important for deep learning approaches because they assist in the model’s explainability and interpretability. So, at our next meeting, we will see how we can interpret our model’s inaccuracies and how we can possibly improve it." }, { "code": null, "e": 9335, "s": 9264, "text": "Thank you so much for your time! (The full project can be found here)." }, { "code": null, "e": 9429, "s": 9335, "text": "[1] Albert Mehrabian. Communication without words. Communication theory, pages 193–200, 2008." }, { "code": null, "e": 9648, "s": 9429, "text": "[2] Kathrin Kaulard, DouglasWCunningham, Heinrich H Bülthoff, and ChristianWallraven. The mpi facial expression database — a validated database of emotional and conversational facial expressions. PloS one, 7(3), 2012." }, { "code": null, "e": 9792, "s": 9648, "text": "[3] Paul Ekman, E Richard Sorenson, and Wallace V Friesen. Pan-cultural elements in facial displays of emotion. Science, 164(3875):86–88, 1969." } ]
Java is Strictly Pass by Value! - GeeksforGeeks
11 Apr, 2022 Consider the following Java program that passes a primitive type to function. public class Main{ public static void main(String[] args) { int x = 5; change(x); System.out.println(x); } public static void change(int x) { x = 10; }} Output: 5 We pass an int to the function “change()” and as a result the change in the value of that integer is not reflected in the main method. Like C/C++, Java creates a copy of the variable being passed in the method and then do the manipulations. Hence the change is not reflected in the main method. How about objects or references? In Java, all primitives like int, char, etc are similar to C/C++, but all non-primitives (or objects of any class) are always references. So it gets tricky when we pass object references to methods. Java creates a copy of references and pass it to method, but they still point to same memory reference. Mean if set some other object to reference passed inside method, the object from calling method as well its reference will remain unaffected. The changes are not reflected back if we change the object itself to refer some other location or objectIf we assign reference to some other location, then changes are not reflected back in main(). // A Java program to show that references are also passed// by value.class Test{ int x; Test(int i) { x = i; } Test() { x = 0; }} class Main{ public static void main(String[] args) { // t is a reference Test t = new Test(5); // Reference is passed and a copy of reference // is created in change() change(t); // Old value of t.x is printed System.out.println(t.x); } public static void change(Test t) { // We changed reference to refer some other location // now any changes made to reference are not reflected // back in main t = new Test(); t.x = 10; }} Output: 5 Changes are reflected back if we do not assign reference to a new location or object:If we do not change the reference to refer some other object (or memory location), we can make changes to the members and these changes are reflected back. // A Java program to show that we can change members using using// reference if we do not change the reference itself.class Test{ int x; Test(int i) { x = i; } Test() { x = 0; }} class Main{ public static void main(String[] args) { // t is a reference Test t = new Test(5); // Reference is passed and a copy of reference // is created in change() change(t); // New value of x is printed System.out.println(t.x); } // This change() doesn't change the reference, it only // changes member of object referred by reference public static void change(Test t) { t.x = 10; }} Output: 10 Exercise: Predict the output of following Java program // Test.javaclass Main { // swap() doesn't swap i and j public static void swap(Integer i, Integer j) { Integer temp = new Integer(i); i = j; j = temp; } public static void main(String[] args) { Integer i = new Integer(10); Integer j = new Integer(20); swap(i, j); System.out.println("i = " + i + ", j = " + j); }} This article is contributed by Pranjal Mathur. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above solankimayank Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Arrays in Java Split() String method in Java with examples For-each loop in Java Reverse a string in Java Object Oriented Programming (OOPs) Concept in Java Arrays.sort() in Java with examples HashMap in Java with Examples How to iterate any Map in Java Initialize an ArrayList in Java Interfaces in Java
[ { "code": null, "e": 23395, "s": 23367, "text": "\n11 Apr, 2022" }, { "code": null, "e": 23473, "s": 23395, "text": "Consider the following Java program that passes a primitive type to function." }, { "code": "public class Main{ public static void main(String[] args) { int x = 5; change(x); System.out.println(x); } public static void change(int x) { x = 10; }}", "e": 23672, "s": 23473, "text": null }, { "code": null, "e": 23680, "s": 23672, "text": "Output:" }, { "code": null, "e": 23682, "s": 23680, "text": "5" }, { "code": null, "e": 23977, "s": 23682, "text": "We pass an int to the function “change()” and as a result the change in the value of that integer is not reflected in the main method. Like C/C++, Java creates a copy of the variable being passed in the method and then do the manipulations. Hence the change is not reflected in the main method." }, { "code": null, "e": 24010, "s": 23977, "text": "How about objects or references?" }, { "code": null, "e": 24455, "s": 24010, "text": "In Java, all primitives like int, char, etc are similar to C/C++, but all non-primitives (or objects of any class) are always references. So it gets tricky when we pass object references to methods. Java creates a copy of references and pass it to method, but they still point to same memory reference. Mean if set some other object to reference passed inside method, the object from calling method as well its reference will remain unaffected." }, { "code": null, "e": 24653, "s": 24455, "text": "The changes are not reflected back if we change the object itself to refer some other location or objectIf we assign reference to some other location, then changes are not reflected back in main()." }, { "code": "// A Java program to show that references are also passed// by value.class Test{ int x; Test(int i) { x = i; } Test() { x = 0; }} class Main{ public static void main(String[] args) { // t is a reference Test t = new Test(5); // Reference is passed and a copy of reference // is created in change() change(t); // Old value of t.x is printed System.out.println(t.x); } public static void change(Test t) { // We changed reference to refer some other location // now any changes made to reference are not reflected // back in main t = new Test(); t.x = 10; }}", "e": 25332, "s": 24653, "text": null }, { "code": null, "e": 25340, "s": 25332, "text": "Output:" }, { "code": null, "e": 25342, "s": 25340, "text": "5" }, { "code": null, "e": 25583, "s": 25342, "text": "Changes are reflected back if we do not assign reference to a new location or object:If we do not change the reference to refer some other object (or memory location), we can make changes to the members and these changes are reflected back." }, { "code": "// A Java program to show that we can change members using using// reference if we do not change the reference itself.class Test{ int x; Test(int i) { x = i; } Test() { x = 0; }} class Main{ public static void main(String[] args) { // t is a reference Test t = new Test(5); // Reference is passed and a copy of reference // is created in change() change(t); // New value of x is printed System.out.println(t.x); } // This change() doesn't change the reference, it only // changes member of object referred by reference public static void change(Test t) { t.x = 10; }}", "e": 26252, "s": 25583, "text": null }, { "code": null, "e": 26260, "s": 26252, "text": "Output:" }, { "code": null, "e": 26263, "s": 26260, "text": "10" }, { "code": null, "e": 26318, "s": 26263, "text": "Exercise: Predict the output of following Java program" }, { "code": "// Test.javaclass Main { // swap() doesn't swap i and j public static void swap(Integer i, Integer j) { Integer temp = new Integer(i); i = j; j = temp; } public static void main(String[] args) { Integer i = new Integer(10); Integer j = new Integer(20); swap(i, j); System.out.println(\"i = \" + i + \", j = \" + j); }}", "e": 26685, "s": 26318, "text": null }, { "code": null, "e": 26953, "s": 26685, "text": "This article is contributed by Pranjal Mathur. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 27077, "s": 26953, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above" }, { "code": null, "e": 27091, "s": 27077, "text": "solankimayank" }, { "code": null, "e": 27096, "s": 27091, "text": "Java" }, { "code": null, "e": 27101, "s": 27096, "text": "Java" }, { "code": null, "e": 27199, "s": 27101, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27208, "s": 27199, "text": "Comments" }, { "code": null, "e": 27221, "s": 27208, "text": "Old Comments" }, { "code": null, "e": 27236, "s": 27221, "text": "Arrays in Java" }, { "code": null, "e": 27280, "s": 27236, "text": "Split() String method in Java with examples" }, { "code": null, "e": 27302, "s": 27280, "text": "For-each loop in Java" }, { "code": null, "e": 27327, "s": 27302, "text": "Reverse a string in Java" }, { "code": null, "e": 27378, "s": 27327, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 27414, "s": 27378, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 27444, "s": 27414, "text": "HashMap in Java with Examples" }, { "code": null, "e": 27475, "s": 27444, "text": "How to iterate any Map in Java" }, { "code": null, "e": 27507, "s": 27475, "text": "Initialize an ArrayList in Java" } ]
Bias and Variance in Machine Learning | by Arun Jagota | Towards Data Science
These concepts are important to both the theory and the practice of data science. They also come up in job interviews and academic exams. A biased predictor is eccentric, i.e. its predictions are consistently off. No matter how well it’s trained, it just doesn’t get it. Generally, such a predictor is too simple for the problem at hand. It under-fits the data, no matter how rich. A high-variance predictor is, in a sense, the opposite. It often arises when one tries to fix bias and over-compensates. One’s gone from a model that is too simple — i.e., biased — to one that is too complex — i.e. has high variance. It over-fits the data. Somewhere between these two is the “sweet spot” — the best predictor. Often this is not easy to find. A data scientist can help. That’s another story ... Example The input is a temperature in (say) Fahrenheit. We want it classified comfortable or not. The training set may capture the judgments of a single person or a group. As noted elsewhere, this problem is not linearly separable. Simply put, the correct solution should behave as Too low -> uncomfortable (U)Just right -> comfortable (C)Too high -> uncomfortable (U) It’s clear we need two thresholds, one to distinguish too low from just right, one to distinguish just rightfrom too high. Bias What if we are limited to use only one? Such as when our classifier is only capable of learning linear decision boundaries. No training set — no matter how rich — will help. We just can’t get the middle predicted comfortable and the two extremes predicted uncomfortable. Towards A Better Solution What if we had domain knowledge. That is, we knew the characteristics of the problem. Here that it needs two thresholds. We could work out a good solution. We’ll suppose we don’t have such domain knowledge. Said another way, we want a generic solution. Nearest Neighbor Approach We’ll consider a single nearest neighbors approach because it can learn nonlinear decision boundaries and is simple to describe. We’ll describe it specialized to our problem. For two reasons: (i) further clarity and (ii) convenient for discussing its variance. Predict the temperature to be comfortable if at least half the people labeled it comfortable; uncomfortable if not. Now suppose the algorithm is trained on the following data set. Each temperature was labeled — C or U — by 10 people. Temperature 10 ... 45 50 55 60 ... 80 ... 100 ..% who Labeled C 0 ... 50 30 40 70 ... 70 ... 0 This algorithm would label 45 as C, 50 and 55 as U, and 60 as C. This doesn’t seem right. 50 and 55 are deemed uncomfortable. We expect 45 should also be. What is going on here? We have only 10 labelers. It’s plausible that “half of them labeling 45 as C” is noise. With many more labelings, this fraction might well drop to below 0.5. Another way to look at this is that the model’s predictions have high variance. Think this way. Imagine a different set of 10 people labeling the data. Train on this new set. The prediction at 45 is unlikely to be off. This would be too much of a coincidence. That said, there very well could be some temperature on which the prediction is off. So, as we’ve seen in our example, a high variance predictor is susceptible to learning the noise in the training set. Noise doesn’t repeat itself. Next time we train it, it will learn noise on a different input. From the point of view of a user, who only uses it as a black-box predictor, the predictions aren’t consistent across training runs. Reducing Variance So how do we fix this algorithmically . That is, without asking for additional labeling (which incurs a cost). We smooth the data, either during pre-processing, or as part of the algorithm. Below we opt for the latter. We replace single nearest neighbor by three. For simplicity, ignoring computational efficiency considerations, we describe it in the form below: For the input temperature T, get all the labelings of T, T-1, and T+1. Predict T’s label to be the majority label among all these. We have a more robust classifier. Each prediction will be based on a labeled sample of size 30 — three times more than we had from our single nearest neighbor classifier. Compared to the single threshold classifier, this one is less biased. It is inherently still capable of learning non-linear decision boundaries. Of course, precisely how accurate this new classifier is compared to the previous two is an empirical question. This involves a precise comparison of the combined effects of bias and variance of each classifier. In short, it needs a suitable train-test empirical evaluation. That’s another story.
[ { "code": null, "e": 309, "s": 171, "text": "These concepts are important to both the theory and the practice of data science. They also come up in job interviews and academic exams." }, { "code": null, "e": 553, "s": 309, "text": "A biased predictor is eccentric, i.e. its predictions are consistently off. No matter how well it’s trained, it just doesn’t get it. Generally, such a predictor is too simple for the problem at hand. It under-fits the data, no matter how rich." }, { "code": null, "e": 810, "s": 553, "text": "A high-variance predictor is, in a sense, the opposite. It often arises when one tries to fix bias and over-compensates. One’s gone from a model that is too simple — i.e., biased — to one that is too complex — i.e. has high variance. It over-fits the data." }, { "code": null, "e": 964, "s": 810, "text": "Somewhere between these two is the “sweet spot” — the best predictor. Often this is not easy to find. A data scientist can help. That’s another story ..." }, { "code": null, "e": 972, "s": 964, "text": "Example" }, { "code": null, "e": 1136, "s": 972, "text": "The input is a temperature in (say) Fahrenheit. We want it classified comfortable or not. The training set may capture the judgments of a single person or a group." }, { "code": null, "e": 1246, "s": 1136, "text": "As noted elsewhere, this problem is not linearly separable. Simply put, the correct solution should behave as" }, { "code": null, "e": 1352, "s": 1246, "text": "Too low -> uncomfortable (U)Just right -> comfortable (C)Too high -> uncomfortable (U)" }, { "code": null, "e": 1475, "s": 1352, "text": "It’s clear we need two thresholds, one to distinguish too low from just right, one to distinguish just rightfrom too high." }, { "code": null, "e": 1480, "s": 1475, "text": "Bias" }, { "code": null, "e": 1751, "s": 1480, "text": "What if we are limited to use only one? Such as when our classifier is only capable of learning linear decision boundaries. No training set — no matter how rich — will help. We just can’t get the middle predicted comfortable and the two extremes predicted uncomfortable." }, { "code": null, "e": 1777, "s": 1751, "text": "Towards A Better Solution" }, { "code": null, "e": 1933, "s": 1777, "text": "What if we had domain knowledge. That is, we knew the characteristics of the problem. Here that it needs two thresholds. We could work out a good solution." }, { "code": null, "e": 2030, "s": 1933, "text": "We’ll suppose we don’t have such domain knowledge. Said another way, we want a generic solution." }, { "code": null, "e": 2056, "s": 2030, "text": "Nearest Neighbor Approach" }, { "code": null, "e": 2317, "s": 2056, "text": "We’ll consider a single nearest neighbors approach because it can learn nonlinear decision boundaries and is simple to describe. We’ll describe it specialized to our problem. For two reasons: (i) further clarity and (ii) convenient for discussing its variance." }, { "code": null, "e": 2433, "s": 2317, "text": "Predict the temperature to be comfortable if at least half the people labeled it comfortable; uncomfortable if not." }, { "code": null, "e": 2551, "s": 2433, "text": "Now suppose the algorithm is trained on the following data set. Each temperature was labeled — C or U — by 10 people." }, { "code": null, "e": 2665, "s": 2551, "text": "Temperature 10 ... 45 50 55 60 ... 80 ... 100 ..% who Labeled C 0 ... 50 30 40 70 ... 70 ... 0" }, { "code": null, "e": 2820, "s": 2665, "text": "This algorithm would label 45 as C, 50 and 55 as U, and 60 as C. This doesn’t seem right. 50 and 55 are deemed uncomfortable. We expect 45 should also be." }, { "code": null, "e": 3001, "s": 2820, "text": "What is going on here? We have only 10 labelers. It’s plausible that “half of them labeling 45 as C” is noise. With many more labelings, this fraction might well drop to below 0.5." }, { "code": null, "e": 3346, "s": 3001, "text": "Another way to look at this is that the model’s predictions have high variance. Think this way. Imagine a different set of 10 people labeling the data. Train on this new set. The prediction at 45 is unlikely to be off. This would be too much of a coincidence. That said, there very well could be some temperature on which the prediction is off." }, { "code": null, "e": 3691, "s": 3346, "text": "So, as we’ve seen in our example, a high variance predictor is susceptible to learning the noise in the training set. Noise doesn’t repeat itself. Next time we train it, it will learn noise on a different input. From the point of view of a user, who only uses it as a black-box predictor, the predictions aren’t consistent across training runs." }, { "code": null, "e": 3709, "s": 3691, "text": "Reducing Variance" }, { "code": null, "e": 4073, "s": 3709, "text": "So how do we fix this algorithmically . That is, without asking for additional labeling (which incurs a cost). We smooth the data, either during pre-processing, or as part of the algorithm. Below we opt for the latter. We replace single nearest neighbor by three. For simplicity, ignoring computational efficiency considerations, we describe it in the form below:" }, { "code": null, "e": 4204, "s": 4073, "text": "For the input temperature T, get all the labelings of T, T-1, and T+1. Predict T’s label to be the majority label among all these." }, { "code": null, "e": 4520, "s": 4204, "text": "We have a more robust classifier. Each prediction will be based on a labeled sample of size 30 — three times more than we had from our single nearest neighbor classifier. Compared to the single threshold classifier, this one is less biased. It is inherently still capable of learning non-linear decision boundaries." } ]
JavaFX - 2D Shapes Rounded Rectangle
In JavaFX, you can draw a rectangle either with sharp edges or with arched edges as shown in the following diagram. The one with arched edges is known as a rounded rectangle and it has two additional properties namely − arcHeight − The vertical diameter of the arc, at the corners of a rounded rectangle. arcHeight − The vertical diameter of the arc, at the corners of a rounded rectangle. arcWidth − The horizontal diameter of the arc at the corners of a rounded rectangle. arcWidth − The horizontal diameter of the arc at the corners of a rounded rectangle. By default, JavaFX creates a rectangle with sharp edges unless you set the height and width of the arc to +ve values (0<) using their respective setter methods setArcHeight() and setArcWidth(). Following is a program which generates a rounded rectangle using JavaFX. Save this code in a file with the name RoundedRectangle.java. import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.stage.Stage; import javafx.scene.shape.Rectangle; public class RoundedRectangle extends Application { @Override public void start(Stage stage) { //Drawing a Rectangle Rectangle rectangle = new Rectangle(); //Setting the properties of the rectangle rectangle.setX(150.0f); rectangle.setY(75.0f); rectangle.setWidth(300.0f); rectangle.setHeight(150.0f); //Setting the height and width of the arc rectangle.setArcWidth(30.0); rectangle.setArcHeight(20.0); //Creating a Group object Group root = new Group(rectangle); //Creating a scene object Scene scene = new Scene(root, 600, 300); //Setting title to the Stage stage.setTitle("Drawing a Rectangle"); //Adding scene to the stage stage.setScene(scene); //Displaying the contents of the stage stage.show(); } public static void main(String args[]){ launch(args); } } Compile and execute the saved java file from the command prompt using the following commands. javac RoundedRectangle.java java RoundedRectangle On executing, the above program generates a JavaFX window displaying a rounded rectangle as shown below. 33 Lectures 7.5 hours Syed Raza 64 Lectures 12.5 hours Emenwa Global, Ejike IfeanyiChukwu 20 Lectures 4 hours Emenwa Global, Ejike IfeanyiChukwu Print Add Notes Bookmark this page
[ { "code": null, "e": 2016, "s": 1900, "text": "In JavaFX, you can draw a rectangle either with sharp edges or with arched edges as shown in the following diagram." }, { "code": null, "e": 2120, "s": 2016, "text": "The one with arched edges is known as a rounded rectangle and it has two additional properties namely −" }, { "code": null, "e": 2205, "s": 2120, "text": "arcHeight − The vertical diameter of the arc, at the corners of a rounded rectangle." }, { "code": null, "e": 2290, "s": 2205, "text": "arcHeight − The vertical diameter of the arc, at the corners of a rounded rectangle." }, { "code": null, "e": 2375, "s": 2290, "text": "arcWidth − The horizontal diameter of the arc at the corners of a rounded rectangle." }, { "code": null, "e": 2460, "s": 2375, "text": "arcWidth − The horizontal diameter of the arc at the corners of a rounded rectangle." }, { "code": null, "e": 2654, "s": 2460, "text": "By default, JavaFX creates a rectangle with sharp edges unless you set the height and width of the arc to +ve values (0<) using their respective setter methods setArcHeight() and setArcWidth()." }, { "code": null, "e": 2789, "s": 2654, "text": "Following is a program which generates a rounded rectangle using JavaFX. Save this code in a file with the name RoundedRectangle.java." }, { "code": null, "e": 3959, "s": 2789, "text": "import javafx.application.Application; \nimport javafx.scene.Group; \nimport javafx.scene.Scene; \nimport javafx.stage.Stage; \nimport javafx.scene.shape.Rectangle; \n \npublic class RoundedRectangle extends Application { \n @Override \n public void start(Stage stage) { \n //Drawing a Rectangle \n Rectangle rectangle = new Rectangle(); \n \n //Setting the properties of the rectangle \n rectangle.setX(150.0f); \n rectangle.setY(75.0f); \n rectangle.setWidth(300.0f); \n rectangle.setHeight(150.0f); \n \n //Setting the height and width of the arc \n rectangle.setArcWidth(30.0); \n rectangle.setArcHeight(20.0); \n \n //Creating a Group object \n Group root = new Group(rectangle); \n \n //Creating a scene object \n Scene scene = new Scene(root, 600, 300); \n \n //Setting title to the Stage \n stage.setTitle(\"Drawing a Rectangle\");\n \n //Adding scene to the stage \n stage.setScene(scene); \n \n //Displaying the contents of the stage \n stage.show(); \n } \n public static void main(String args[]){ \n launch(args); \n } \n}" }, { "code": null, "e": 4053, "s": 3959, "text": "Compile and execute the saved java file from the command prompt using the following commands." }, { "code": null, "e": 4105, "s": 4053, "text": "javac RoundedRectangle.java \njava RoundedRectangle\n" }, { "code": null, "e": 4210, "s": 4105, "text": "On executing, the above program generates a JavaFX window displaying a rounded rectangle as shown below." }, { "code": null, "e": 4245, "s": 4210, "text": "\n 33 Lectures \n 7.5 hours \n" }, { "code": null, "e": 4256, "s": 4245, "text": " Syed Raza" }, { "code": null, "e": 4292, "s": 4256, "text": "\n 64 Lectures \n 12.5 hours \n" }, { "code": null, "e": 4328, "s": 4292, "text": " Emenwa Global, Ejike IfeanyiChukwu" }, { "code": null, "e": 4361, "s": 4328, "text": "\n 20 Lectures \n 4 hours \n" }, { "code": null, "e": 4397, "s": 4361, "text": " Emenwa Global, Ejike IfeanyiChukwu" }, { "code": null, "e": 4404, "s": 4397, "text": " Print" }, { "code": null, "e": 4415, "s": 4404, "text": " Add Notes" } ]
Java ResultSetMetaData getColumnLabel() method with example
The getColumnLabel() method of the ResultSetMetaData (interface) retrieves the display name of a particular column. This method accepts an integer value representing the index of the column in the current ResultSet object, as an argument and, returns a String value representing the label of the specified column. To get the ResultSetMetaData object, you need to: Register the Driver: Select the required database register the Driver class of the particular database using the registerDriver() method of the DriverManager class or, the forName() method of the class named Class. DriverManager.registerDriver(new com.mysql.jdbc.Driver()); Get connection: Create a connection object by passing the URL of the database, username and password of a user in the database (in string format) as parameters to the getConnection() method of the DriverManager class. Connection mysqlCon = DriverManager.getConnection(mysqlUrl, "root", "password"); Create a Statement object: Create a Statement object using the createStatement method of the connection interface. Statement stmt = con.createStatement(); Execute the Query: Execute the SELECT query using the executeQuery() methods of the Statement interface and Retrieve the results into the ResultSet object. String query = "Select * from MyPlayers"; ResultSet rs = stmt.executeQuery(query); Get the ResultSetMetsdata object: Retrieve the ResultSetMetsdata object of the current ResultSet by invoking the getMetaData() method. ResultSetMetaData resultSetMetaData = rs.getMetaData(); Finally, using the getColumnLabel() method of the ResultSetMetaData interface get the column label of the required column by specifying its index as: String columnLabel = resultSetMetaData.getColumnLabel(4); Let us create a table with name MyPlayers in MySQL database using CREATE statement as shown below: CREATE TABLE MyPlayers( ID INT, First_Name VARCHAR(255), Last_Name VARCHAR(255), Date_Of_Birth date, Place_Of_Birth VARCHAR(255), Country VARCHAR(255), PRIMARY KEY (ID) ); Now, we will insert 7 records in MyPlayers table using INSERT statements: insert into MyPlayers values(1, 'Shikhar', 'Dhawan', DATE('1981-12-05'), 'Delhi', 'India'); insert into MyPlayers values(2, 'Jonathan', 'Trott', DATE('1981-04-22'), 'CapeTown', 'SouthAfrica'); insert into MyPlayers values(3, 'Kumara', 'Sangakkara', DATE('1977-10-27'), 'Matale', 'Srilanka'); insert into MyPlayers values(4, 'Virat', 'Kohli', DATE('1988-11-05'), 'Delhi', 'India'); insert into MyPlayers values(5, 'Rohit', 'Sharma', DATE('1987-04-30'), 'Nagpur', 'India'); insert into MyPlayers values(6, 'Ravindra', 'Jadeja', DATE('1988-12-06'), 'Nagpur', 'India'); insert into MyPlayers values(7, 'James', 'Anderson', DATE('1982-06-30'), 'Burnley', 'England'); Following JDBC program establishes connection with MySQL database, retrieves and displays the Column label of a column with index 4 in the MyPlayers table using the getColumnLabel() method. import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; public class ResultSetMetaData_getColumnLabel { public static void main(String args[]) throws SQLException { //Registering the Driver DriverManager.registerDriver(new com.mysql.jdbc.Driver()); //Getting the connection String mysqlUrl = "jdbc:mysql://localhost/mydatabase"; Connection con = DriverManager.getConnection(mysqlUrl, "root", "password"); System.out.println("Connection established......"); //Creating the Statement Statement stmt = con.createStatement(); //Query to retrieve records String query = "Select ID, First_Name, Last_Name, Date_Of_Birth as DOB, Place_Of_Birth as POB, Country from MyPlayers"; //Executing the query ResultSet rs = stmt.executeQuery(query); //retrieving the ResultSetMetaData object ResultSetMetaData resultSetMetaData = rs.getMetaData(); //Retrieving the column label String columnLabel1 = resultSetMetaData.getColumnLabel(4); System.out.println("Column label of the column Date_Of_Birth (4th column): "+ columnLabel1); } } Connection established...... Column label of the column Date_Of_Birth (4th column): DOB
[ { "code": null, "e": 1178, "s": 1062, "text": "The getColumnLabel() method of the ResultSetMetaData (interface) retrieves the display name of a particular column." }, { "code": null, "e": 1376, "s": 1178, "text": "This method accepts an integer value representing the index of the column in the current ResultSet object, as an argument and, returns a String value representing the label of the specified column." }, { "code": null, "e": 1426, "s": 1376, "text": "To get the ResultSetMetaData object, you need to:" }, { "code": null, "e": 1641, "s": 1426, "text": "Register the Driver: Select the required database register the Driver class of the particular database using the registerDriver() method of the DriverManager class or, the forName() method of the class named Class." }, { "code": null, "e": 1700, "s": 1641, "text": "DriverManager.registerDriver(new com.mysql.jdbc.Driver());" }, { "code": null, "e": 1918, "s": 1700, "text": "Get connection: Create a connection object by passing the URL of the database, username and password of a user in the database (in string format) as parameters to the getConnection() method of the DriverManager class." }, { "code": null, "e": 1999, "s": 1918, "text": "Connection mysqlCon = DriverManager.getConnection(mysqlUrl, \"root\", \"password\");" }, { "code": null, "e": 2114, "s": 1999, "text": "Create a Statement object: Create a Statement object using the createStatement method of the connection interface." }, { "code": null, "e": 2154, "s": 2114, "text": "Statement stmt = con.createStatement();" }, { "code": null, "e": 2310, "s": 2154, "text": "Execute the Query: Execute the SELECT query using the executeQuery() methods of the Statement interface and Retrieve the results into the ResultSet object." }, { "code": null, "e": 2393, "s": 2310, "text": "String query = \"Select * from MyPlayers\";\nResultSet rs = stmt.executeQuery(query);" }, { "code": null, "e": 2528, "s": 2393, "text": "Get the ResultSetMetsdata object: Retrieve the ResultSetMetsdata object of the current ResultSet by invoking the getMetaData() method." }, { "code": null, "e": 2584, "s": 2528, "text": "ResultSetMetaData resultSetMetaData = rs.getMetaData();" }, { "code": null, "e": 2734, "s": 2584, "text": "Finally, using the getColumnLabel() method of the ResultSetMetaData interface get the column label of the required column by specifying its index as:" }, { "code": null, "e": 2792, "s": 2734, "text": "String columnLabel = resultSetMetaData.getColumnLabel(4);" }, { "code": null, "e": 2892, "s": 2792, "text": "Let us create a table with name MyPlayers in MySQL database using CREATE statement as shown below: " }, { "code": null, "e": 3085, "s": 2892, "text": "CREATE TABLE MyPlayers(\n ID INT,\n First_Name VARCHAR(255),\n Last_Name VARCHAR(255),\n Date_Of_Birth date,\n Place_Of_Birth VARCHAR(255),\n Country VARCHAR(255),\n PRIMARY KEY (ID)\n);" }, { "code": null, "e": 3159, "s": 3085, "text": "Now, we will insert 7 records in MyPlayers table using INSERT statements:" }, { "code": null, "e": 3821, "s": 3159, "text": "insert into MyPlayers values(1, 'Shikhar', 'Dhawan', DATE('1981-12-05'), 'Delhi', 'India');\ninsert into MyPlayers values(2, 'Jonathan', 'Trott', DATE('1981-04-22'), 'CapeTown', 'SouthAfrica');\ninsert into MyPlayers values(3, 'Kumara', 'Sangakkara', DATE('1977-10-27'), 'Matale', 'Srilanka');\ninsert into MyPlayers values(4, 'Virat', 'Kohli', DATE('1988-11-05'), 'Delhi', 'India');\ninsert into MyPlayers values(5, 'Rohit', 'Sharma', DATE('1987-04-30'), 'Nagpur', 'India');\ninsert into MyPlayers values(6, 'Ravindra', 'Jadeja', DATE('1988-12-06'), 'Nagpur', 'India');\ninsert into MyPlayers values(7, 'James', 'Anderson', DATE('1982-06-30'), 'Burnley', 'England');" }, { "code": null, "e": 4011, "s": 3821, "text": "Following JDBC program establishes connection with MySQL database, retrieves and displays the Column label of a column with index 4 in the MyPlayers table using the getColumnLabel() method." }, { "code": null, "e": 5267, "s": 4011, "text": "import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.ResultSet;\nimport java.sql.ResultSetMetaData;\nimport java.sql.SQLException;\nimport java.sql.Statement;\npublic class ResultSetMetaData_getColumnLabel {\n public static void main(String args[]) throws SQLException {\n //Registering the Driver\n DriverManager.registerDriver(new com.mysql.jdbc.Driver());\n //Getting the connection\n String mysqlUrl = \"jdbc:mysql://localhost/mydatabase\";\n Connection con = DriverManager.getConnection(mysqlUrl, \"root\", \"password\");\n System.out.println(\"Connection established......\");\n //Creating the Statement\n Statement stmt = con.createStatement();\n //Query to retrieve records\n String query = \"Select ID, First_Name, Last_Name, Date_Of_Birth as DOB,\n Place_Of_Birth as POB, Country from MyPlayers\";\n //Executing the query\n ResultSet rs = stmt.executeQuery(query);\n //retrieving the ResultSetMetaData object\n ResultSetMetaData resultSetMetaData = rs.getMetaData();\n //Retrieving the column label\n String columnLabel1 = resultSetMetaData.getColumnLabel(4);\n System.out.println(\"Column label of the column Date_Of_Birth (4th column): \"+ columnLabel1);\n }\n}" }, { "code": null, "e": 5355, "s": 5267, "text": "Connection established......\nColumn label of the column Date_Of_Birth (4th column): DOB" } ]
Print Single and Multiple variable in C#
To display single variable value in C#, you just need to use Console.WriteLine() Let us see an example. Here, we have displayed the value of a single variable “a” in a line − using System; using System.Linq; class Program { static void Main() { int a = 10; Console.WriteLine("Value: "+a); } } To display multiple variables value in C#, you need to use the comma operator in Console.WriteLine(). Let us see an example. Here, we have displayed the value of multiple variables “a” and “b” in a line − using System; using System.Linq; class Program { static void Main() { int a = 10; int b = 15; Console.WriteLine("Values: {0} {1} ",a,b); } } Above, the {0} is replaced by the value of variable a, whereas {1} is replaced by the value of variable b.
[ { "code": null, "e": 1143, "s": 1062, "text": "To display single variable value in C#, you just need to use Console.WriteLine()" }, { "code": null, "e": 1237, "s": 1143, "text": "Let us see an example. Here, we have displayed the value of a single variable “a” in a line −" }, { "code": null, "e": 1374, "s": 1237, "text": "using System;\nusing System.Linq;\n\nclass Program {\n static void Main() {\n int a = 10;\n Console.WriteLine(\"Value: \"+a);\n }\n}" }, { "code": null, "e": 1476, "s": 1374, "text": "To display multiple variables value in C#, you need to use the comma operator in Console.WriteLine()." }, { "code": null, "e": 1579, "s": 1476, "text": "Let us see an example. Here, we have displayed the value of multiple variables “a” and “b” in a line −" }, { "code": null, "e": 1745, "s": 1579, "text": "using System;\nusing System.Linq;\n\nclass Program {\n static void Main() {\n int a = 10;\n int b = 15;\n Console.WriteLine(\"Values: {0} {1} \",a,b);\n }\n}" }, { "code": null, "e": 1852, "s": 1745, "text": "Above, the {0} is replaced by the value of variable a, whereas {1} is replaced by the value of variable b." } ]
How to use std::sort to sort an array in C++
In programming language, sorting is a basic function which is applied to data to arrange these data is ascending or descending data. In C++ program, there is a function std::sort() for sorting the array. sort(start address, end address) Here, Start address => The first address of the element. Last address => The address of the next contiguous location of the last element of the array. Live Demo #include <iostream> #include <algorithm> using namespace std; void display(int a[]) { for(int i = 0; i < 5; ++i) cout << a[i] << " "; } int main() { int a[5]= {4, 2, 7, 9, 6}; cout << "\n The array before sorting is : "; display(a); sort(a, a+5); cout << "\n\n The array after sorting is : "; display(a); return 0; } The array before sorting is : 4 2 7 9 6 The array after sorting is : 2 4 6 7 9
[ { "code": null, "e": 1266, "s": 1062, "text": "In programming language, sorting is a basic function which is applied to data to arrange these data is ascending or descending data. In C++ program, there is a function std::sort() for sorting the array." }, { "code": null, "e": 1299, "s": 1266, "text": "sort(start address, end address)" }, { "code": null, "e": 1305, "s": 1299, "text": "Here," }, { "code": null, "e": 1450, "s": 1305, "text": "Start address => The first address of the element.\nLast address => The address of the next contiguous location of the last element of the array." }, { "code": null, "e": 1461, "s": 1450, "text": " Live Demo" }, { "code": null, "e": 1805, "s": 1461, "text": "#include <iostream>\n#include <algorithm>\nusing namespace std;\nvoid display(int a[]) {\n for(int i = 0; i < 5; ++i)\n cout << a[i] << \" \";\n}\nint main() {\n int a[5]= {4, 2, 7, 9, 6};\n cout << \"\\n The array before sorting is : \";\n display(a);\n sort(a, a+5);\n cout << \"\\n\\n The array after sorting is : \";\n display(a);\n return 0;\n}" }, { "code": null, "e": 1885, "s": 1805, "text": "The array before sorting is : 4 2 7 9 6\n\nThe array after sorting is : 2 4 6 7 9" } ]
Print Binary Tree in 2-Dimensions in C++
In this problem, we are given a binary tree and we have to print it two dimensional plane. Binary Tree is a special tree whose every node has at max two child nodes. So, every node is either a leaf node or has one or two child nodes. Example, Let’s take an example to understand the topic better − Output - 7 4 5 1 3 8 Now as we have seen in the example, the nodes of the tree are printed in a 2-D output screen horizontally. Here, we have flipped the tree by 90o. Let’s see what the new horizontal tree is made up of, The tree data structure is stored in a horizontal way which includesThe root at the 1st position in horizontal view n lines below the starting line. i.e. root will be at the start of the nth line.The new levels of the tree are in lines n+i and n-i. And at i tab spaces away from the start of the line.And the rightmost leaf node of the tree is printed in the first line. Whereas the leftmost node of the tree is printed at the last line. The tree data structure is stored in a horizontal way which includes The root at the 1st position in horizontal view n lines below the starting line. i.e. root will be at the start of the nth line. The root at the 1st position in horizontal view n lines below the starting line. i.e. root will be at the start of the nth line. The new levels of the tree are in lines n+i and n-i. And at i tab spaces away from the start of the line. The new levels of the tree are in lines n+i and n-i. And at i tab spaces away from the start of the line. And the rightmost leaf node of the tree is printed in the first line. Whereas the leftmost node of the tree is printed at the last line. And the rightmost leaf node of the tree is printed in the first line. Whereas the leftmost node of the tree is printed at the last line. Let’s create a program based on this logic − Live Demo #include<bits/stdc++.h> #include<iostream> using namespace std; #define COUNT 10 class Node{ public: int data; Node* left, *right; Node(int data){ this->data = data; this->left = NULL; this->right = NULL; } }; void printTree(Node *root, int space){ if (root == NULL) return; space += COUNT; printTree(root->right, space); for (int i = COUNT; i < space; i++) cout<<"\t"; cout<<root->data<<"\n"; printTree(root->left, space); } int main(){ Node *root = new Node(43); root->left = new Node(25); root->right = new Node(67); root->left->left = new Node(14); root->left->right = new Node(51); root->right->left = new Node(26); root->right->right = new Node(97); root->left->left->left = new Node(81); root->left->left->right = new Node(49); root->left->right->left = new Node(07); root->left->right->right = new Node(31); root->right->left->left = new Node(29); root->right->left->right = new Node(13); root->right->right->left = new Node(59); root->right->right->right = new Node(16); printTree(root, 0); return 0; } 16 97 59 67 13 26 29 43 31 51 7 25 49 14 81
[ { "code": null, "e": 1153, "s": 1062, "text": "In this problem, we are given a binary tree and we have to print it two dimensional plane." }, { "code": null, "e": 1296, "s": 1153, "text": "Binary Tree is a special tree whose every node has at max two child nodes. So, every node is either a leaf node or has one or two child nodes." }, { "code": null, "e": 1305, "s": 1296, "text": "Example," }, { "code": null, "e": 1360, "s": 1305, "text": "Let’s take an example to understand the topic better −" }, { "code": null, "e": 1369, "s": 1360, "text": "Output -" }, { "code": null, "e": 1405, "s": 1369, "text": " 7\n 4\n5\n 1\n 3\n 8" }, { "code": null, "e": 1512, "s": 1405, "text": "Now as we have seen in the example, the nodes of the tree are printed in a 2-D output screen horizontally." }, { "code": null, "e": 1551, "s": 1512, "text": "Here, we have flipped the tree by 90o." }, { "code": null, "e": 1605, "s": 1551, "text": "Let’s see what the new horizontal tree is made up of," }, { "code": null, "e": 2043, "s": 1605, "text": "The tree data structure is stored in a horizontal way which includesThe root at the 1st position in horizontal view n lines below the starting line. i.e. root will be at the start of the nth line.The new levels of the tree are in lines n+i and n-i. And at i tab spaces away from the start of the line.And the rightmost leaf node of the tree is printed in the first line. Whereas the leftmost node of the tree is printed at the last line." }, { "code": null, "e": 2112, "s": 2043, "text": "The tree data structure is stored in a horizontal way which includes" }, { "code": null, "e": 2241, "s": 2112, "text": "The root at the 1st position in horizontal view n lines below the starting line. i.e. root will be at the start of the nth line." }, { "code": null, "e": 2370, "s": 2241, "text": "The root at the 1st position in horizontal view n lines below the starting line. i.e. root will be at the start of the nth line." }, { "code": null, "e": 2476, "s": 2370, "text": "The new levels of the tree are in lines n+i and n-i. And at i tab spaces away from the start of the line." }, { "code": null, "e": 2582, "s": 2476, "text": "The new levels of the tree are in lines n+i and n-i. And at i tab spaces away from the start of the line." }, { "code": null, "e": 2719, "s": 2582, "text": "And the rightmost leaf node of the tree is printed in the first line. Whereas the leftmost node of the tree is printed at the last line." }, { "code": null, "e": 2856, "s": 2719, "text": "And the rightmost leaf node of the tree is printed in the first line. Whereas the leftmost node of the tree is printed at the last line." }, { "code": null, "e": 2901, "s": 2856, "text": "Let’s create a program based on this logic −" }, { "code": null, "e": 2912, "s": 2901, "text": " Live Demo" }, { "code": null, "e": 4059, "s": 2912, "text": "#include<bits/stdc++.h>\n#include<iostream>\nusing namespace std;\n#define COUNT 10\nclass Node{\n public:\n int data;\n Node* left, *right;\n Node(int data){\n this->data = data;\n this->left = NULL;\n this->right = NULL;\n }\n};\nvoid printTree(Node *root, int space){\n if (root == NULL)\n return;\n space += COUNT;\n printTree(root->right, space);\n for (int i = COUNT; i < space; i++)\n cout<<\"\\t\";\n cout<<root->data<<\"\\n\";\n printTree(root->left, space);\n}\nint main(){\n Node *root = new Node(43);\n root->left = new Node(25);\n root->right = new Node(67);\n root->left->left = new Node(14);\n root->left->right = new Node(51);\n root->right->left = new Node(26);\n root->right->right = new Node(97);\n root->left->left->left = new Node(81);\n root->left->left->right = new Node(49);\n root->left->right->left = new Node(07);\n root->left->right->right = new Node(31);\n root->right->left->left = new Node(29);\n root->right->left->right = new Node(13);\n root->right->right->left = new Node(59);\n root->right->right->right = new Node(16);\n printTree(root, 0);\n return 0;\n}" }, { "code": null, "e": 4202, "s": 4059, "text": " 16\n 97\n 59\n 67\n 13\n 26\n 29\n43\n 31\n 51\n 7\n 25\n 49\n 14\n 81" } ]
Split string into equal parts JavaScript
We are required to write a JavaScript function that takes in a string and a number n as two arguments (the number should be such that it exactly divides the length of string). And we have to return an array of n strings of equal length. For example − If the string is "helloo" and the number is 3 Our output should be: ["ho", "eo", "ll"] Here, each substring exactly contains (length of array/n) characters. And each substring is formed by taking corresponding first and last letters of the string alternatively Let's write the code for this function − const str = 'helloo'; const splitEqual = (str, n) => { if(str.length % n !== 0){ return false; } const len = str.length / n; const strArray = str.split(""); const arr = []; let i = 0, char; while(strArray.length){ if(i % 2 === 0){ char = strArray.shift(); }else{ char = strArray.pop(); }; if(i % len === 0){ arr[i / len] = char; }else{ arr[Math.floor(i / len)] += char; }; i++; }; return arr; }; console.log(splitEqual(str, 3)); The output in the console will be − [ 'ho', 'eo', 'll' ]
[ { "code": null, "e": 1299, "s": 1062, "text": "We are required to write a JavaScript function that takes in a string and a number n as two\narguments (the number should be such that it exactly divides the length of string). And we have\nto return an array of n strings of equal length." }, { "code": null, "e": 1313, "s": 1299, "text": "For example −" }, { "code": null, "e": 1400, "s": 1313, "text": "If the string is \"helloo\" and the number is 3\nOur output should be:\n[\"ho\", \"eo\", \"ll\"]" }, { "code": null, "e": 1574, "s": 1400, "text": "Here, each substring exactly contains (length of array/n) characters. And each substring is\nformed by taking corresponding first and last letters of the string alternatively" }, { "code": null, "e": 1615, "s": 1574, "text": "Let's write the code for this function −" }, { "code": null, "e": 2155, "s": 1615, "text": "const str = 'helloo';\nconst splitEqual = (str, n) => {\n if(str.length % n !== 0){\n return false;\n }\n const len = str.length / n;\n const strArray = str.split(\"\");\n const arr = [];\n let i = 0, char;\n while(strArray.length){\n if(i % 2 === 0){\n char = strArray.shift();\n }else{\n char = strArray.pop();\n };\n if(i % len === 0){\n arr[i / len] = char;\n }else{\n arr[Math.floor(i / len)] += char;\n };\n i++;\n };\n return arr;\n};\nconsole.log(splitEqual(str, 3));" }, { "code": null, "e": 2191, "s": 2155, "text": "The output in the console will be −" }, { "code": null, "e": 2212, "s": 2191, "text": "[ 'ho', 'eo', 'll' ]" } ]
Date after() method in Java - GeeksforGeeks
07 Nov, 2019 The java.util.Date.after() method is used to check whether the current instance of the date is after the specified date. Syntax: dateObject.after(Date specifiedDate) Parameter: It takes only one parameter specifiedDate of data type Date. This is the date which is to be checked in comparison to the instance of the date calling the function. Return Value: The return type of this function is boolean. It returns true if current instance of the date is strictly larger than the specifiedDate. Otherwise it returns false. Exceptions: If the specifiedDate is null, this method will throw NullPointerException when called upon. Below programs illustrate after() method in Date class: Program 1: // Java code to demonstrate// after() function of Date class import java.util.Date;import java.util.Calendar;public class GfG { // main method public static void main(String[] args) { // creating a Calendar object Calendar c = Calendar.getInstance(); // set Month // MONTH starts with 0 i.e. ( 0 - Jan) c.set(Calendar.MONTH, 11); // set Date c.set(Calendar.DATE, 05); // set Year c.set(Calendar.YEAR, 1996); // creating a date object with specified time. Date dateOne = c.getTime(); // creating a date of object // storing the current date Date currentDate = new Date(); System.out.print("Is currentDate after date one : "); // if currentDate is after dateOne System.out.println(currentDate.after(dateOne)); }} Is currentDate after date one : true Program 2: To demonstrate java.lang.NullPointerException // Java code to demonstrate// after() function of Date class import java.util.Date; public class GfG { // main method public static void main(String[] args) { // creating a date of object // storing the current date Date currentDate = new Date(); // specifiedDate is assigned to null. Date specifiedDate = null; System.out.println("Passing null as parameter : "); try { // throws NullPointerException System.out.println(currentDate.after(specifiedDate)); } catch (Exception e) { System.out.println("Exception: " + e); } }} Passing null as parameter : Exception: java.lang.NullPointerException ManasChhabra2 Java - util package Java-Date-Time Java-Functions Java-util-Date Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments HashMap in Java with Examples Interfaces in Java Object Oriented Programming (OOPs) Concept in Java ArrayList in Java How to iterate any Map in Java Initialize an ArrayList in Java Singleton Class in Java Overriding in Java Collections in Java Multithreading in Java
[ { "code": null, "e": 24214, "s": 24186, "text": "\n07 Nov, 2019" }, { "code": null, "e": 24335, "s": 24214, "text": "The java.util.Date.after() method is used to check whether the current instance of the date is after the specified date." }, { "code": null, "e": 24343, "s": 24335, "text": "Syntax:" }, { "code": null, "e": 24381, "s": 24343, "text": "dateObject.after(Date specifiedDate)\n" }, { "code": null, "e": 24557, "s": 24381, "text": "Parameter: It takes only one parameter specifiedDate of data type Date. This is the date which is to be checked in comparison to the instance of the date calling the function." }, { "code": null, "e": 24735, "s": 24557, "text": "Return Value: The return type of this function is boolean. It returns true if current instance of the date is strictly larger than the specifiedDate. Otherwise it returns false." }, { "code": null, "e": 24839, "s": 24735, "text": "Exceptions: If the specifiedDate is null, this method will throw NullPointerException when called upon." }, { "code": null, "e": 24895, "s": 24839, "text": "Below programs illustrate after() method in Date class:" }, { "code": null, "e": 24906, "s": 24895, "text": "Program 1:" }, { "code": "// Java code to demonstrate// after() function of Date class import java.util.Date;import java.util.Calendar;public class GfG { // main method public static void main(String[] args) { // creating a Calendar object Calendar c = Calendar.getInstance(); // set Month // MONTH starts with 0 i.e. ( 0 - Jan) c.set(Calendar.MONTH, 11); // set Date c.set(Calendar.DATE, 05); // set Year c.set(Calendar.YEAR, 1996); // creating a date object with specified time. Date dateOne = c.getTime(); // creating a date of object // storing the current date Date currentDate = new Date(); System.out.print(\"Is currentDate after date one : \"); // if currentDate is after dateOne System.out.println(currentDate.after(dateOne)); }}", "e": 25765, "s": 24906, "text": null }, { "code": null, "e": 25803, "s": 25765, "text": "Is currentDate after date one : true\n" }, { "code": null, "e": 25860, "s": 25803, "text": "Program 2: To demonstrate java.lang.NullPointerException" }, { "code": "// Java code to demonstrate// after() function of Date class import java.util.Date; public class GfG { // main method public static void main(String[] args) { // creating a date of object // storing the current date Date currentDate = new Date(); // specifiedDate is assigned to null. Date specifiedDate = null; System.out.println(\"Passing null as parameter : \"); try { // throws NullPointerException System.out.println(currentDate.after(specifiedDate)); } catch (Exception e) { System.out.println(\"Exception: \" + e); } }}", "e": 26506, "s": 25860, "text": null }, { "code": null, "e": 26578, "s": 26506, "text": "Passing null as parameter : \nException: java.lang.NullPointerException\n" }, { "code": null, "e": 26592, "s": 26578, "text": "ManasChhabra2" }, { "code": null, "e": 26612, "s": 26592, "text": "Java - util package" }, { "code": null, "e": 26627, "s": 26612, "text": "Java-Date-Time" }, { "code": null, "e": 26642, "s": 26627, "text": "Java-Functions" }, { "code": null, "e": 26657, "s": 26642, "text": "Java-util-Date" }, { "code": null, "e": 26662, "s": 26657, "text": "Java" }, { "code": null, "e": 26667, "s": 26662, "text": "Java" }, { "code": null, "e": 26765, "s": 26667, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26774, "s": 26765, "text": "Comments" }, { "code": null, "e": 26787, "s": 26774, "text": "Old Comments" }, { "code": null, "e": 26817, "s": 26787, "text": "HashMap in Java with Examples" }, { "code": null, "e": 26836, "s": 26817, "text": "Interfaces in Java" }, { "code": null, "e": 26887, "s": 26836, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 26905, "s": 26887, "text": "ArrayList in Java" }, { "code": null, "e": 26936, "s": 26905, "text": "How to iterate any Map in Java" }, { "code": null, "e": 26968, "s": 26936, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 26992, "s": 26968, "text": "Singleton Class in Java" }, { "code": null, "e": 27011, "s": 26992, "text": "Overriding in Java" }, { "code": null, "e": 27031, "s": 27011, "text": "Collections in Java" } ]
JavaScript String - lastIndexOf() Method
This method returns the index within the calling String object of the last occurrence of the specified value, starting the search at fromIndex or -1 if the value is not found. Its syntax is as follows − string.lastIndexOf(searchValue[, fromIndex]) searchValue − A string representing the value to search for. searchValue − A string representing the value to search for. fromIndex − The location within the calling string to start the search from. It can be any integer between 0 and the length of the string. The default value is 0. fromIndex − The location within the calling string to start the search from. It can be any integer between 0 and the length of the string. The default value is 0. Returns the index of the last found occurrence, otherwise -1 if not found. Try the following example. <html> <head> <title>JavaScript String lastIndexOf() Method</title> </head> <body> <script type = "text/javascript"> var str1 = new String( "This is string one and again string" ); var index = str1.lastIndexOf( "string" ); document.write("lastIndexOf found String :" + index ); document.write("<br />"); var index = str1.lastIndexOf( "one" ); document.write("lastIndexOf found String :" + index ); </script> </body> </html> lastIndexOf found String :29 lastIndexOf found String :15 25 Lectures 2.5 hours Anadi Sharma 74 Lectures 10 hours Lets Kode It 72 Lectures 4.5 hours Frahaan Hussain 70 Lectures 4.5 hours Frahaan Hussain 46 Lectures 6 hours Eduonix Learning Solutions 88 Lectures 14 hours Eduonix Learning Solutions Print Add Notes Bookmark this page
[ { "code": null, "e": 2642, "s": 2466, "text": "This method returns the index within the calling String object of the last occurrence of the specified value, starting the search at fromIndex or -1 if the value is not found." }, { "code": null, "e": 2669, "s": 2642, "text": "Its syntax is as follows −" }, { "code": null, "e": 2715, "s": 2669, "text": "string.lastIndexOf(searchValue[, fromIndex])\n" }, { "code": null, "e": 2776, "s": 2715, "text": "searchValue − A string representing the value to search for." }, { "code": null, "e": 2837, "s": 2776, "text": "searchValue − A string representing the value to search for." }, { "code": null, "e": 3000, "s": 2837, "text": "fromIndex − The location within the calling string to start the search from. It can be any integer between 0 and the length of the string. The default value is 0." }, { "code": null, "e": 3163, "s": 3000, "text": "fromIndex − The location within the calling string to start the search from. It can be any integer between 0 and the length of the string. The default value is 0." }, { "code": null, "e": 3238, "s": 3163, "text": "Returns the index of the last found occurrence, otherwise -1 if not found." }, { "code": null, "e": 3265, "s": 3238, "text": "Try the following example." }, { "code": null, "e": 3807, "s": 3265, "text": "<html>\n <head>\n <title>JavaScript String lastIndexOf() Method</title>\n </head>\n \n <body> \n <script type = \"text/javascript\">\n var str1 = new String( \"This is string one and again string\" );\n var index = str1.lastIndexOf( \"string\" );\n document.write(\"lastIndexOf found String :\" + index ); \n \n document.write(\"<br />\"); \n var index = str1.lastIndexOf( \"one\" );\n document.write(\"lastIndexOf found String :\" + index ); \n </script> \n </body>\n</html>" }, { "code": null, "e": 3868, "s": 3807, "text": "lastIndexOf found String :29\nlastIndexOf found String :15 \n" }, { "code": null, "e": 3903, "s": 3868, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3917, "s": 3903, "text": " Anadi Sharma" }, { "code": null, "e": 3951, "s": 3917, "text": "\n 74 Lectures \n 10 hours \n" }, { "code": null, "e": 3965, "s": 3951, "text": " Lets Kode It" }, { "code": null, "e": 4000, "s": 3965, "text": "\n 72 Lectures \n 4.5 hours \n" }, { "code": null, "e": 4017, "s": 4000, "text": " Frahaan Hussain" }, { "code": null, "e": 4052, "s": 4017, "text": "\n 70 Lectures \n 4.5 hours \n" }, { "code": null, "e": 4069, "s": 4052, "text": " Frahaan Hussain" }, { "code": null, "e": 4102, "s": 4069, "text": "\n 46 Lectures \n 6 hours \n" }, { "code": null, "e": 4130, "s": 4102, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 4164, "s": 4130, "text": "\n 88 Lectures \n 14 hours \n" }, { "code": null, "e": 4192, "s": 4164, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 4199, "s": 4192, "text": " Print" }, { "code": null, "e": 4210, "s": 4199, "text": " Add Notes" } ]
Predicting MS Admission. It’s almost admission season and I’ve... | by Naman Doshi | Towards Data Science
It’s almost admission season and I’ve couple of friends who are in panic mode waiting for a call from the universities they’ve applied at.This made me think — How can we predict whether a student will get an admit or not? What are the parameters for selection? Can it be mathematically expressed? All of these questions started popping up, so I decided to work out this problem and help my friend calm his nerves. (This is the first technical tutorial I’m ever writing so please go easy on me). In order to solve this problem, I’m going to take you through what I call a “Data Science Pipeline”. Given any problem statement, follow this pipeline so that your approach is structured. Define the problem - Define the problem - Write down the problem statement and understand what you’re trying to solve. In this case, our objective is to predict whether a student will get an admit or not. So it means, that this is a binary classification problem. 2. Generate your own hypothesis - Next, list down all the things that you think can affect our objective viz. List down all the possible features with respect to our target feature.In our case, we got ask this question — What are the factors that can affect a student’s admission?Take a piece of paper and write down your own hypothesis. I spent some time and came up with the following features- GRE Score- TOEFL Score- Statement of Purpose (SOP)- Letter of Recommendation (LOR)- Academic Performance (GPA)- Extra Curricular Activities (Sports, Math Olympiad etc..)- Outstanding Achievements- Projects and Research Make sure that you write down at least 10–20 for any problem statement. This helps us get a deeper understand of what we are trying to solve and prompts us to think beyond the available dataset. 3. Get the Dataset - Next step is to get the data. We’re using UCLA hypothetical data for graduate admissions. You can download the dataset here.You can now map your hypothesis with the given dataset. See how many features you can add or modify in order to improve the quality of the dataset. Identify each feature as either (a) Continous Variable or (b) Categorical Variable 4. Data Cleaning - Most of the time, the dataset will have lot of anomalies like missing values, outliers and so on. Always preprocess the data before moving on to the next step.- Missing Value Treatment: You can use Mean-imputation (for continous variables) or Mode-imputation (for categorical variables) - Outlier treatment: An outlier is an observation that lies an abnormal distance from other values in a random sample. There are four ways to treat it — Deleting observations, Imputing, Creating Bins and Treat Separately.- Feature Engineering: Combining, adding, deleting, splitting, scaling features in order to increase the accuracy of the model 5. Exploratory Data Analysis (EDA) - Now its time to get our hands dirty. Let us explore the data and understand the given features.This dataset has a binary response (outcome, dependent) variable called admit. There are three predictor variables: gre, gpa and rank. We will treat the variables gre and gpa as continuous. The variable ranktakes on the values 1 through 4. Institutions with a rank of 1 have the highest prestige, while those with a rank of 4 have the lowest. EDA helps us get a clear idea about our features. It also helps us capture any trend or seasonality of data points.In our case, we can see that Higher the GRE score and GPA, more the chances of getting admit. 6. Predictive Modeling -This is a binary classification problem. The output has only two possibilities either Yes (1) or No (0). There are lot of classification algorithms out there so how do we know which one is the best?We don’t. This is something that comes with experience and expertise. But not to worry, we do have a work around. We can fit multiple algorithms onto our data points and then evaluate the model. This way we can choose the best model which has the least error.First, let us import all the necessary libraries from matplotlib import pyplotfrom sklearn.model_selection import train_test_splitfrom sklearn.metrics import classification_reportfrom sklearn.metrics import confusion_matrixfrom sklearn.metrics import accuracy_scorefrom sklearn.model_selection import KFoldfrom sklearn.model_selection import cross_val_scorefrom sklearn.linear_model import LogisticRegressionfrom sklearn.tree import DecisionTreeClassifierfrom sklearn.neighbors import KNeighborsClassifierfrom sklearn.ensemble import RandomForestClassifierfrom sklearn.discriminant_analysis import LinearDiscriminantAnalysisfrom sklearn.naive_bayes import GaussianNBfrom sklearn.svm import SVC We’ll be using Cross Validation as an evaluation metric where in we will split our dataset into Train and Test. #Step 1: Convert Dataframe into matrixdataArray = dataset.values#Step 2: Splitting Input features & Output VariablesX = dataArray[:,1:4]y = dataArray[:,0:1]#Step 3: Splitting training & testingvalidation_size = 0.10seed = 9X_train, X_test, Y_train, Y_test = train_test_split(X,y,test_size=validation_size, random_state = seed)print(X_train.shape)print(X_test.shape)print(Y_train.shape)print(Y_test.shape) Next we are going to apply the following Machine Learning algorithms on our Training data- Logistic Regression (LR)- Linear Discriminant Analysis (LDA)- K Nearest Neighbours (KNN)- Decision Tree (CART)- Random Forest (RF)- Gaussian Naive Bayes (NB)- Support Vector Machines (SVM)Initialize max number of features and number of trees. num_trees = 200max_features = 3models = []models.append(('LR', LogisticRegression()))models.append(('LDA', LinearDiscriminantAnalysis()))models.append(('KNN', KNeighborsClassifier()))models.append(('CART', DecisionTreeClassifier()))models.append(('RF', RandomForestClassifier(n_estimators=num_trees, max_features=max_features)))models.append(('NB', GaussianNB()))models.append(('SVM', SVC()))#Fit Models and Evaulateresults = []names = []scoring = 'accuracy'#Cross Validationfor name, model in models: kfold = KFold(n_splits = 10, random_state=7) cv_results = cross_val_score(model, X_train, Y_train, cv=kfold, scoring = scoring) results.append(cv_results) names.append(name) msg = "%s: %f (%f)" % (name,cv_results.mean(), cv_results.std()) print(msg) What we have done here is run all 7 algorithms on our data point and tried to evaluate it. As you can see LR and LDA perform the best.We can also implement a comparison plot So now we have fit the ML algorithm onto our dataset. Next, we have to create a predictive model using the best algorithm.For the sake of simplicity, I’m going to pick LR. #Step 1 - Create prediction modelmodel = LogisticRegression()#Step 2 - Fit modelmodel.fit(X_train, Y_train)#Step 3 - Predictions predictions = model.predict(X_test)#Step 4 - Check Accuracyprint("Model --- LogisticRegression")print("Accuracy: {} ".format(accuracy_score(Y_test,predictions) * 100))print(classification_report(Y_test, predictions)) I love to make plots. So lets make an another one ;) #plotting confusion matrix on heatmapcm = confusion_matrix(Y_test, predictions)sns.heatmap(cm, annot=True, xticklabels=['reject','admit'], yticklabels=['reject','admit'])plt.figure(figsize=(3,3))plt.show() Congratulations! You made our very own predictive model with an accuracy of 77.5(Not bad at all for beginners)You can try to increase this score by fitting different classification algorithms or by doing a little bit of feature engineering. Best way is to use Ensembling methods, but that is for some other tutorial. But wait...How do we know that this works? Yes, exactly right? We have come this far, how can we not let our model make some predictions! #Making predictions on some new data#Like a bossnew_data = [(720,4,1), (300,2,3) , (400,3,4) ]#Convert to numpy arraynew_array = np.asarray(new_data)#Output Labelslabels=["reject","admit"]#Let's make some kickass predictionsprediction=model.predict(new_array)#Get number of test cases usedno_of_test_cases, cols = new_array.shapefor i in range(no_of_test_cases): print("Status of Student with GRE scores = {}, GPA grade = {}, Rank = {} will be ----- {}".format(new_data[i][0],new_data[i][1],new_data[i][2], labels[int(prediction[i])])) AND THAT’S IT. Our very own predictive model that can decide your friend’s future (actually no, it cant)But our model can definitely predict whether he/she will get an admit or not! Motives behind DSW — I’ve been learning and doing data science from about a year now. During this time I have worked on lot of problem statements. But the thing is sometimes the dataset is pretty interesting but other times its not. You have to care about the problem you’re trying to solve, only then you’ll be able to do a good job. So find a problem that you wanna solve and use data to solve it. You can find the code for this tutorial here on Github — I’ll be writing down some kickass tutorials every week so if you’re someone who can learn only by doing, follow my publication here. You can also connect with on LinkedIn. I hope you have a productive week ahead. Until then, keep hustling!
[ { "code": null, "e": 666, "s": 171, "text": "It’s almost admission season and I’ve couple of friends who are in panic mode waiting for a call from the universities they’ve applied at.This made me think — How can we predict whether a student will get an admit or not? What are the parameters for selection? Can it be mathematically expressed? All of these questions started popping up, so I decided to work out this problem and help my friend calm his nerves. (This is the first technical tutorial I’m ever writing so please go easy on me)." }, { "code": null, "e": 854, "s": 666, "text": "In order to solve this problem, I’m going to take you through what I call a “Data Science Pipeline”. Given any problem statement, follow this pipeline so that your approach is structured." }, { "code": null, "e": 875, "s": 854, "text": "Define the problem -" }, { "code": null, "e": 896, "s": 875, "text": "Define the problem -" }, { "code": null, "e": 1118, "s": 896, "text": "Write down the problem statement and understand what you’re trying to solve. In this case, our objective is to predict whether a student will get an admit or not. So it means, that this is a binary classification problem." }, { "code": null, "e": 1152, "s": 1118, "text": "2. Generate your own hypothesis -" }, { "code": null, "e": 1929, "s": 1152, "text": "Next, list down all the things that you think can affect our objective viz. List down all the possible features with respect to our target feature.In our case, we got ask this question — What are the factors that can affect a student’s admission?Take a piece of paper and write down your own hypothesis. I spent some time and came up with the following features- GRE Score- TOEFL Score- Statement of Purpose (SOP)- Letter of Recommendation (LOR)- Academic Performance (GPA)- Extra Curricular Activities (Sports, Math Olympiad etc..)- Outstanding Achievements- Projects and Research Make sure that you write down at least 10–20 for any problem statement. This helps us get a deeper understand of what we are trying to solve and prompts us to think beyond the available dataset." }, { "code": null, "e": 1950, "s": 1929, "text": "3. Get the Dataset -" }, { "code": null, "e": 2305, "s": 1950, "text": "Next step is to get the data. We’re using UCLA hypothetical data for graduate admissions. You can download the dataset here.You can now map your hypothesis with the given dataset. See how many features you can add or modify in order to improve the quality of the dataset. Identify each feature as either (a) Continous Variable or (b) Categorical Variable" }, { "code": null, "e": 2324, "s": 2305, "text": "4. Data Cleaning -" }, { "code": null, "e": 2611, "s": 2324, "text": "Most of the time, the dataset will have lot of anomalies like missing values, outliers and so on. Always preprocess the data before moving on to the next step.- Missing Value Treatment: You can use Mean-imputation (for continous variables) or Mode-imputation (for categorical variables)" }, { "code": null, "e": 2730, "s": 2611, "text": "- Outlier treatment: An outlier is an observation that lies an abnormal distance from other values in a random sample." }, { "code": null, "e": 2959, "s": 2730, "text": "There are four ways to treat it — Deleting observations, Imputing, Creating Bins and Treat Separately.- Feature Engineering: Combining, adding, deleting, splitting, scaling features in order to increase the accuracy of the model" }, { "code": null, "e": 2996, "s": 2959, "text": "5. Exploratory Data Analysis (EDA) -" }, { "code": null, "e": 3434, "s": 2996, "text": "Now its time to get our hands dirty. Let us explore the data and understand the given features.This dataset has a binary response (outcome, dependent) variable called admit. There are three predictor variables: gre, gpa and rank. We will treat the variables gre and gpa as continuous. The variable ranktakes on the values 1 through 4. Institutions with a rank of 1 have the highest prestige, while those with a rank of 4 have the lowest." }, { "code": null, "e": 3643, "s": 3434, "text": "EDA helps us get a clear idea about our features. It also helps us capture any trend or seasonality of data points.In our case, we can see that Higher the GRE score and GPA, more the chances of getting admit." }, { "code": null, "e": 4173, "s": 3643, "text": "6. Predictive Modeling -This is a binary classification problem. The output has only two possibilities either Yes (1) or No (0). There are lot of classification algorithms out there so how do we know which one is the best?We don’t. This is something that comes with experience and expertise. But not to worry, we do have a work around. We can fit multiple algorithms onto our data points and then evaluate the model. This way we can choose the best model which has the least error.First, let us import all the necessary libraries" }, { "code": null, "e": 4818, "s": 4173, "text": "from matplotlib import pyplotfrom sklearn.model_selection import train_test_splitfrom sklearn.metrics import classification_reportfrom sklearn.metrics import confusion_matrixfrom sklearn.metrics import accuracy_scorefrom sklearn.model_selection import KFoldfrom sklearn.model_selection import cross_val_scorefrom sklearn.linear_model import LogisticRegressionfrom sklearn.tree import DecisionTreeClassifierfrom sklearn.neighbors import KNeighborsClassifierfrom sklearn.ensemble import RandomForestClassifierfrom sklearn.discriminant_analysis import LinearDiscriminantAnalysisfrom sklearn.naive_bayes import GaussianNBfrom sklearn.svm import SVC" }, { "code": null, "e": 4930, "s": 4818, "text": "We’ll be using Cross Validation as an evaluation metric where in we will split our dataset into Train and Test." }, { "code": null, "e": 5335, "s": 4930, "text": "#Step 1: Convert Dataframe into matrixdataArray = dataset.values#Step 2: Splitting Input features & Output VariablesX = dataArray[:,1:4]y = dataArray[:,0:1]#Step 3: Splitting training & testingvalidation_size = 0.10seed = 9X_train, X_test, Y_train, Y_test = train_test_split(X,y,test_size=validation_size, random_state = seed)print(X_train.shape)print(X_test.shape)print(Y_train.shape)print(Y_test.shape)" }, { "code": null, "e": 5669, "s": 5335, "text": "Next we are going to apply the following Machine Learning algorithms on our Training data- Logistic Regression (LR)- Linear Discriminant Analysis (LDA)- K Nearest Neighbours (KNN)- Decision Tree (CART)- Random Forest (RF)- Gaussian Naive Bayes (NB)- Support Vector Machines (SVM)Initialize max number of features and number of trees." }, { "code": null, "e": 6421, "s": 5669, "text": "num_trees = 200max_features = 3models = []models.append(('LR', LogisticRegression()))models.append(('LDA', LinearDiscriminantAnalysis()))models.append(('KNN', KNeighborsClassifier()))models.append(('CART', DecisionTreeClassifier()))models.append(('RF', RandomForestClassifier(n_estimators=num_trees, max_features=max_features)))models.append(('NB', GaussianNB()))models.append(('SVM', SVC()))#Fit Models and Evaulateresults = []names = []scoring = 'accuracy'#Cross Validationfor name, model in models: kfold = KFold(n_splits = 10, random_state=7) cv_results = cross_val_score(model, X_train, Y_train, cv=kfold, scoring = scoring) results.append(cv_results) names.append(name) msg = \"%s: %f (%f)\" % (name,cv_results.mean(), cv_results.std()) print(msg)" }, { "code": null, "e": 6595, "s": 6421, "text": "What we have done here is run all 7 algorithms on our data point and tried to evaluate it. As you can see LR and LDA perform the best.We can also implement a comparison plot" }, { "code": null, "e": 6767, "s": 6595, "text": "So now we have fit the ML algorithm onto our dataset. Next, we have to create a predictive model using the best algorithm.For the sake of simplicity, I’m going to pick LR." }, { "code": null, "e": 7113, "s": 6767, "text": "#Step 1 - Create prediction modelmodel = LogisticRegression()#Step 2 - Fit modelmodel.fit(X_train, Y_train)#Step 3 - Predictions predictions = model.predict(X_test)#Step 4 - Check Accuracyprint(\"Model --- LogisticRegression\")print(\"Accuracy: {} \".format(accuracy_score(Y_test,predictions) * 100))print(classification_report(Y_test, predictions))" }, { "code": null, "e": 7166, "s": 7113, "text": "I love to make plots. So lets make an another one ;)" }, { "code": null, "e": 7372, "s": 7166, "text": "#plotting confusion matrix on heatmapcm = confusion_matrix(Y_test, predictions)sns.heatmap(cm, annot=True, xticklabels=['reject','admit'], yticklabels=['reject','admit'])plt.figure(figsize=(3,3))plt.show()" }, { "code": null, "e": 7689, "s": 7372, "text": "Congratulations! You made our very own predictive model with an accuracy of 77.5(Not bad at all for beginners)You can try to increase this score by fitting different classification algorithms or by doing a little bit of feature engineering. Best way is to use Ensembling methods, but that is for some other tutorial." }, { "code": null, "e": 7827, "s": 7689, "text": "But wait...How do we know that this works? Yes, exactly right? We have come this far, how can we not let our model make some predictions!" }, { "code": null, "e": 8363, "s": 7827, "text": "#Making predictions on some new data#Like a bossnew_data = [(720,4,1), (300,2,3) , (400,3,4) ]#Convert to numpy arraynew_array = np.asarray(new_data)#Output Labelslabels=[\"reject\",\"admit\"]#Let's make some kickass predictionsprediction=model.predict(new_array)#Get number of test cases usedno_of_test_cases, cols = new_array.shapefor i in range(no_of_test_cases): print(\"Status of Student with GRE scores = {}, GPA grade = {}, Rank = {} will be ----- {}\".format(new_data[i][0],new_data[i][1],new_data[i][2], labels[int(prediction[i])]))" }, { "code": null, "e": 8545, "s": 8363, "text": "AND THAT’S IT. Our very own predictive model that can decide your friend’s future (actually no, it cant)But our model can definitely predict whether he/she will get an admit or not!" }, { "code": null, "e": 8566, "s": 8545, "text": "Motives behind DSW —" }, { "code": null, "e": 8880, "s": 8566, "text": "I’ve been learning and doing data science from about a year now. During this time I have worked on lot of problem statements. But the thing is sometimes the dataset is pretty interesting but other times its not. You have to care about the problem you’re trying to solve, only then you’ll be able to do a good job." }, { "code": null, "e": 8945, "s": 8880, "text": "So find a problem that you wanna solve and use data to solve it." }, { "code": null, "e": 9002, "s": 8945, "text": "You can find the code for this tutorial here on Github —" }, { "code": null, "e": 9135, "s": 9002, "text": "I’ll be writing down some kickass tutorials every week so if you’re someone who can learn only by doing, follow my publication here." }, { "code": null, "e": 9174, "s": 9135, "text": "You can also connect with on LinkedIn." }, { "code": null, "e": 9215, "s": 9174, "text": "I hope you have a productive week ahead." } ]
Creating Convolutional Neural Network From Scratch | by Himanshu Sharma | Towards Data Science
Image classification basically helps us in classifying images into different labels. It is like bucketing different images into the bucket they belong to. For, e.g. a model trained to identify the image of a cat and a dog will help in segregating different images of cats and dogs respectively. There are multiple deep learning frameworks like Tensorflow, Keras, Theano, etc that can be used to create image classification models. Today we will create an image classification model from scratch using Keras and Tensorflow. For creating image-related modeling can be done using CNN. Convolutional Neural Networks are mainly used for image-related modeling. It is one of the easiest ways to perform image classification, image detection, image segmentation, etc. It contains different types of convolutional layers that help in filtering out the most important features of the image using kernels of different sizes. Some of the most important layers are: Conv2D Conv2D It is used to create a Convolutional kernel that is convolved with the input layer to produce the output tensor. 2. MaxPooling2D It is a downsampling technique that takes the maximum value by pool size. 3. Flatten It flattens the input and creates an1-D output. There are multiple hyper-parameters that can be used accordingly to improve the model performance. These hyper-parameters may include a number of neurons, kernel size, pool size, activation function, etc. In this article, we will create a network using CNN from scratch. I will show you how you can load data from online sources, preprocess that data and make it ready for modeling, and finally design the model architecture. Let’s get started... We will start by installing all required libraries. We will install Keras, TensorFlow and will also install TensorBay(SDK on Graviti data platform) that we will use for loading the dataset. The command given below will do that. !pip install tensorflow!pip install tensorbay!pip install keras In this step, we will import all the required libraries and functions to load the data, preprocess it and create the model. # Library importsfrom tensorbay import GASfrom PIL import Imageimport matplotlib.pyplot as pltfrom tensorbay.dataset import Data, Datasetimport numpy as npimport pandas as pdimport matplotlib.pyplot as pltfrom matplotlib.image import imreadimport cv2import randomfrom os import listdirfrom sklearn.preprocessing import LabelBinarizerfrom keras.preprocessing import imagefrom keras.preprocessing.image import img_to_array, array_to_imgfrom tensorflow.keras.optimizers import Adamfrom keras.models import Sequentialfrom keras.layers import Conv2D, MaxPooling2D, Activation, Flatten, Dropout, Densefrom sklearn.model_selection import train_test_split This is the initial step, where we will load the data from TensorBay. In order to download a dataset from TensorBay, we need to create an account and fork a dataset on which we want to work, it contains a large variety of image datasets. For loading the dataset in our Jupyter notebook we need to have the access key to TensorBay that we can download from developer tools in our account. gas = GAS("<Your Key>")dataset = Dataset("Flower17–1", gas)segment = dataset[1] For this article, I am using the Flower 17 Dataset, as you can see I have loaded it above using TensorBay. In this step, we will preprocess the data and make it ready for modelling. We will start by creating the image and labels list and loading data into it. image_list, label_list = [], []for data in segment:with data.open() as fp:image_list.append(img_to_array(Image.open(fp).resize((500, 500))))label_list.append(data.label.classification.category) Next, let us visualize the number of classes that we have in this dataset. # Visualize the number of classes countlabel_counts = pd.DataFrame(label_list).value_counts()label_counts Next, we will split the dataset, normalize it and also binarize the labels. # Splitting datasetx_train, x_test, y_train, y_test = train_test_split(image_list, label_list, test_size=0.2, random_state = 10)# Normalize and reshape datax_train = np.array(x_train, dtype=np.float16) / 225.0x_train = x_train.reshape( -1,500,500,3)x_test = np.array(x_test, dtype=np.float16) / 225.0x_test = x_test.reshape( -1,500,500,3)# Label binarizinglb = LabelBinarizer()y_train = lb.fit_transform(y_train)y_test = lb.fit_transform(y_test)print(lb.classes_) This is the final step, where we will create the model architecture, compile the model and train it. Before creating the model architecture, let’s split the training data into train and validation. # Splitting the training data set into training and validation data setsx_train, x_val, y_train, y_val = train_test_split(x_train, y_train, test_size = 0.2)# Building model architecturemodel = Sequential()model.add(Conv2D(8, (3, 3), padding="same",input_shape=(500,500,3), activation="relu"))model.add(MaxPooling2D(pool_size=(3, 3)))model.add(Conv2D(16, (3, 3), padding="same", activation="relu"))model.add(MaxPooling2D(pool_size=(2, 2)))model.add(Conv2D(32, (3, 3), padding="same", activation="relu"))model.add(MaxPooling2D(pool_size=(2, 2)))model.add(Flatten())model.add(Dense(32, activation="relu"))model.add(Dense(num_classes, activation="softmax"))model.summary() # Compiling modelmodel.compile(loss = 'categorical_crossentropy', optimizer = Adam(0.0005),metrics=['accuracy'])# Training the modelepochs = 20batch_size = 128history = model.fit(x_train, y_train, batch_size = batch_size, epochs = epochs, validation_data = (x_val, y_val)) As you can see above we have created and trained the model using some hyper-parameters, model accuracy is not that good but you can always tune the hyper-parameters to increase the performance. We can also save the model by using the command given below. # Saving modelmodel.save("/content/flower_species.h5")Let's visualize the model training and loss history.#Plot the training historyplt.figure(figsize=(12, 5))plt.plot(history.history['accuracy'], color='r')plt.plot(history.history['val_accuracy'], color='b')plt.title('Model Accuracy')plt.ylabel('Accuracy')plt.xlabel('Epochs')plt.legend(['train', 'val'])plt.show() #Plot the loss historyplt.figure(figsize=(12, 5))plt.plot(history.history['loss'], color='r')plt.plot(history.history['val_loss'], color='b')plt.title('Model Loss')plt.ylabel('Loss')plt.xlabel('Epochs')plt.legend(['train', 'val'])plt.show() In the end, let us also create some predictions using the model. # Storing predictionsy_pred = model.predict(x_test)Let's verify one of the predictions.# Plotting image to compareimg = array_to_img(x_test[4])img # Finding max value from prediction list and comparing original value vs predictedlabels = lb.classes_print(labels)print("Originally : ",labels[np.argmax(y_test[4])])print("Predicted : ",labels[np.argmax(y_pred[4])]) Go ahead, try this with different datasets and create CNN models easily by following this article. In case you find any difficulty please let me know in the response section. Thanks for reading! If you want to get in touch with me, feel free to reach me at [email protected] or my LinkedIn Profile. You can view my Github profile for different data science projects and packages tutorials. Also, feel free to explore my profile and read different articles I have written related to Data Science.
[ { "code": null, "e": 694, "s": 171, "text": "Image classification basically helps us in classifying images into different labels. It is like bucketing different images into the bucket they belong to. For, e.g. a model trained to identify the image of a cat and a dog will help in segregating different images of cats and dogs respectively. There are multiple deep learning frameworks like Tensorflow, Keras, Theano, etc that can be used to create image classification models. Today we will create an image classification model from scratch using Keras and Tensorflow." }, { "code": null, "e": 1125, "s": 694, "text": "For creating image-related modeling can be done using CNN. Convolutional Neural Networks are mainly used for image-related modeling. It is one of the easiest ways to perform image classification, image detection, image segmentation, etc. It contains different types of convolutional layers that help in filtering out the most important features of the image using kernels of different sizes. Some of the most important layers are:" }, { "code": null, "e": 1132, "s": 1125, "text": "Conv2D" }, { "code": null, "e": 1139, "s": 1132, "text": "Conv2D" }, { "code": null, "e": 1252, "s": 1139, "text": "It is used to create a Convolutional kernel that is convolved with the input layer to produce the output tensor." }, { "code": null, "e": 1268, "s": 1252, "text": "2. MaxPooling2D" }, { "code": null, "e": 1342, "s": 1268, "text": "It is a downsampling technique that takes the maximum value by pool size." }, { "code": null, "e": 1353, "s": 1342, "text": "3. Flatten" }, { "code": null, "e": 1401, "s": 1353, "text": "It flattens the input and creates an1-D output." }, { "code": null, "e": 1606, "s": 1401, "text": "There are multiple hyper-parameters that can be used accordingly to improve the model performance. These hyper-parameters may include a number of neurons, kernel size, pool size, activation function, etc." }, { "code": null, "e": 1827, "s": 1606, "text": "In this article, we will create a network using CNN from scratch. I will show you how you can load data from online sources, preprocess that data and make it ready for modeling, and finally design the model architecture." }, { "code": null, "e": 1848, "s": 1827, "text": "Let’s get started..." }, { "code": null, "e": 2076, "s": 1848, "text": "We will start by installing all required libraries. We will install Keras, TensorFlow and will also install TensorBay(SDK on Graviti data platform) that we will use for loading the dataset. The command given below will do that." }, { "code": null, "e": 2140, "s": 2076, "text": "!pip install tensorflow!pip install tensorbay!pip install keras" }, { "code": null, "e": 2264, "s": 2140, "text": "In this step, we will import all the required libraries and functions to load the data, preprocess it and create the model." }, { "code": null, "e": 2912, "s": 2264, "text": "# Library importsfrom tensorbay import GASfrom PIL import Imageimport matplotlib.pyplot as pltfrom tensorbay.dataset import Data, Datasetimport numpy as npimport pandas as pdimport matplotlib.pyplot as pltfrom matplotlib.image import imreadimport cv2import randomfrom os import listdirfrom sklearn.preprocessing import LabelBinarizerfrom keras.preprocessing import imagefrom keras.preprocessing.image import img_to_array, array_to_imgfrom tensorflow.keras.optimizers import Adamfrom keras.models import Sequentialfrom keras.layers import Conv2D, MaxPooling2D, Activation, Flatten, Dropout, Densefrom sklearn.model_selection import train_test_split" }, { "code": null, "e": 3300, "s": 2912, "text": "This is the initial step, where we will load the data from TensorBay. In order to download a dataset from TensorBay, we need to create an account and fork a dataset on which we want to work, it contains a large variety of image datasets. For loading the dataset in our Jupyter notebook we need to have the access key to TensorBay that we can download from developer tools in our account." }, { "code": null, "e": 3380, "s": 3300, "text": "gas = GAS(\"<Your Key>\")dataset = Dataset(\"Flower17–1\", gas)segment = dataset[1]" }, { "code": null, "e": 3487, "s": 3380, "text": "For this article, I am using the Flower 17 Dataset, as you can see I have loaded it above using TensorBay." }, { "code": null, "e": 3640, "s": 3487, "text": "In this step, we will preprocess the data and make it ready for modelling. We will start by creating the image and labels list and loading data into it." }, { "code": null, "e": 3834, "s": 3640, "text": "image_list, label_list = [], []for data in segment:with data.open() as fp:image_list.append(img_to_array(Image.open(fp).resize((500, 500))))label_list.append(data.label.classification.category)" }, { "code": null, "e": 3909, "s": 3834, "text": "Next, let us visualize the number of classes that we have in this dataset." }, { "code": null, "e": 4015, "s": 3909, "text": "# Visualize the number of classes countlabel_counts = pd.DataFrame(label_list).value_counts()label_counts" }, { "code": null, "e": 4091, "s": 4015, "text": "Next, we will split the dataset, normalize it and also binarize the labels." }, { "code": null, "e": 4555, "s": 4091, "text": "# Splitting datasetx_train, x_test, y_train, y_test = train_test_split(image_list, label_list, test_size=0.2, random_state = 10)# Normalize and reshape datax_train = np.array(x_train, dtype=np.float16) / 225.0x_train = x_train.reshape( -1,500,500,3)x_test = np.array(x_test, dtype=np.float16) / 225.0x_test = x_test.reshape( -1,500,500,3)# Label binarizinglb = LabelBinarizer()y_train = lb.fit_transform(y_train)y_test = lb.fit_transform(y_test)print(lb.classes_)" }, { "code": null, "e": 4753, "s": 4555, "text": "This is the final step, where we will create the model architecture, compile the model and train it. Before creating the model architecture, let’s split the training data into train and validation." }, { "code": null, "e": 5422, "s": 4753, "text": "# Splitting the training data set into training and validation data setsx_train, x_val, y_train, y_val = train_test_split(x_train, y_train, test_size = 0.2)# Building model architecturemodel = Sequential()model.add(Conv2D(8, (3, 3), padding=\"same\",input_shape=(500,500,3), activation=\"relu\"))model.add(MaxPooling2D(pool_size=(3, 3)))model.add(Conv2D(16, (3, 3), padding=\"same\", activation=\"relu\"))model.add(MaxPooling2D(pool_size=(2, 2)))model.add(Conv2D(32, (3, 3), padding=\"same\", activation=\"relu\"))model.add(MaxPooling2D(pool_size=(2, 2)))model.add(Flatten())model.add(Dense(32, activation=\"relu\"))model.add(Dense(num_classes, activation=\"softmax\"))model.summary()" }, { "code": null, "e": 5695, "s": 5422, "text": "# Compiling modelmodel.compile(loss = 'categorical_crossentropy', optimizer = Adam(0.0005),metrics=['accuracy'])# Training the modelepochs = 20batch_size = 128history = model.fit(x_train, y_train, batch_size = batch_size, epochs = epochs, validation_data = (x_val, y_val))" }, { "code": null, "e": 5950, "s": 5695, "text": "As you can see above we have created and trained the model using some hyper-parameters, model accuracy is not that good but you can always tune the hyper-parameters to increase the performance. We can also save the model by using the command given below." }, { "code": null, "e": 6317, "s": 5950, "text": "# Saving modelmodel.save(\"/content/flower_species.h5\")Let's visualize the model training and loss history.#Plot the training historyplt.figure(figsize=(12, 5))plt.plot(history.history['accuracy'], color='r')plt.plot(history.history['val_accuracy'], color='b')plt.title('Model Accuracy')plt.ylabel('Accuracy')plt.xlabel('Epochs')plt.legend(['train', 'val'])plt.show()" }, { "code": null, "e": 6558, "s": 6317, "text": "#Plot the loss historyplt.figure(figsize=(12, 5))plt.plot(history.history['loss'], color='r')plt.plot(history.history['val_loss'], color='b')plt.title('Model Loss')plt.ylabel('Loss')plt.xlabel('Epochs')plt.legend(['train', 'val'])plt.show()" }, { "code": null, "e": 6623, "s": 6558, "text": "In the end, let us also create some predictions using the model." }, { "code": null, "e": 6770, "s": 6623, "text": "# Storing predictionsy_pred = model.predict(x_test)Let's verify one of the predictions.# Plotting image to compareimg = array_to_img(x_test[4])img" }, { "code": null, "e": 6987, "s": 6770, "text": "# Finding max value from prediction list and comparing original value vs predictedlabels = lb.classes_print(labels)print(\"Originally : \",labels[np.argmax(y_test[4])])print(\"Predicted : \",labels[np.argmax(y_pred[4])])" }, { "code": null, "e": 7162, "s": 6987, "text": "Go ahead, try this with different datasets and create CNN models easily by following this article. In case you find any difficulty please let me know in the response section." } ]
Creating curved edges with NetworkX in Python3 (Matplotlib)
To create curved edges with NetworkX in Python3, we can use connectionstyle="arc3, rad=0.4". Set the figure size and adjust the padding between and around the subplots. Initialize a graph with edges, name, and graph attributes. Add nodes to the created graph. Add edges from one node to another. Draw the graph G with Matplotlib, with connectionstyle="arc3, rad=0.4". To display the figure, use show() method. import matplotlib.pylab as plt import networkx as nx plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True G = nx.DiGraph() pos = nx.spring_layout(G) G.add_nodes_from([1, 2, 3, 4]) G.add_edges_from([(1, 2), (2, 4), (2, 3), (4, 1)]) nx.draw(G, with_labels=True, connectionstyle="arc3,rad=0.4") plt.show()
[ { "code": null, "e": 1155, "s": 1062, "text": "To create curved edges with NetworkX in Python3, we can use connectionstyle=\"arc3, rad=0.4\"." }, { "code": null, "e": 1231, "s": 1155, "text": "Set the figure size and adjust the padding between and around the subplots." }, { "code": null, "e": 1290, "s": 1231, "text": "Initialize a graph with edges, name, and graph attributes." }, { "code": null, "e": 1322, "s": 1290, "text": "Add nodes to the created graph." }, { "code": null, "e": 1358, "s": 1322, "text": "Add edges from one node to another." }, { "code": null, "e": 1430, "s": 1358, "text": "Draw the graph G with Matplotlib, with connectionstyle=\"arc3, rad=0.4\"." }, { "code": null, "e": 1472, "s": 1430, "text": "To display the figure, use show() method." }, { "code": null, "e": 1814, "s": 1472, "text": "import matplotlib.pylab as plt\nimport networkx as nx\n\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\nG = nx.DiGraph()\n\npos = nx.spring_layout(G)\nG.add_nodes_from([1, 2, 3, 4])\nG.add_edges_from([(1, 2), (2, 4), (2, 3), (4, 1)])\n\nnx.draw(G, with_labels=True, connectionstyle=\"arc3,rad=0.4\")\n\nplt.show()" } ]
Get the Component Type of an Array Object in Java
In order to get the component type of an Array Object in Java, we use the getComponentType() method. The getComponentType() method returns the Class denoting the component type of an array. If the class is not an array class this method returns null. Declaration − The java.lang.Class.getComponentType() method is declared as follows - public Class<?> getComponentType() Let us see a program to the get the component type of an Array Object in Java - Live Demo public class Example { public static void main(String[] args) { int[] array = new int[] {1,2,3}; // obtain the Class of the component type Class arrayClass = array.getClass(); // obtaining the component type Class component = arrayClass.getComponentType(); if (component != null) { System.out.println("Component type is " + component.getName()); } else { System.out.println("Component type is null"); } } } Component type is int
[ { "code": null, "e": 1313, "s": 1062, "text": "In order to get the component type of an Array Object in Java, we use the getComponentType() method. The getComponentType() method returns the Class denoting the component type of an array. If the class is not an array class this method returns null." }, { "code": null, "e": 1398, "s": 1313, "text": "Declaration − The java.lang.Class.getComponentType() method is declared as follows -" }, { "code": null, "e": 1433, "s": 1398, "text": "public Class<?> getComponentType()" }, { "code": null, "e": 1513, "s": 1433, "text": "Let us see a program to the get the component type of an Array Object in Java -" }, { "code": null, "e": 1524, "s": 1513, "text": " Live Demo" }, { "code": null, "e": 2003, "s": 1524, "text": "public class Example {\n public static void main(String[] args) {\n int[] array = new int[] {1,2,3};\n // obtain the Class of the component type\n Class arrayClass = array.getClass();\n // obtaining the component type\n Class component = arrayClass.getComponentType();\n if (component != null) {\n System.out.println(\"Component type is \" + component.getName());\n } else {\n System.out.println(\"Component type is null\");\n }\n }\n}" }, { "code": null, "e": 2025, "s": 2003, "text": "Component type is int" } ]