title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Python 3 - os.makedirs() Method
The method makedirs() is recursive directory creation function. Like mkdir(), but makes all intermediate-level directories needed to contain the leaf directory. The default mode is 0o777 (octal). On some systems, mode is ignored. Where it is used, the current umask value is first masked out. If exist_ok is False (the default), an OSError is raised if the target directory already exists. Following is the syntax for makedirs() method − os.makedirs(path[, mode]) path − This is the path, which needs to be created recursively. path − This is the path, which needs to be created recursively. mode − This is the Mode of the directories to be given. mode − This is the Mode of the directories to be given. This method does not return any value. The following example shows the usage of makedirs() method. #!/usr/bin/python3 import os, sys # Path to be created path = "d:/tmp/home/monthly/daily" os.makedirs( path, 493 ) #decimal equivalent of 0755 used on Windows print ("Path is created") When we run the above program, it produces the following result − Path is created 187 Lectures 17.5 hours Malhar Lathkar 55 Lectures 8 hours Arnab Chakraborty 136 Lectures 11 hours In28Minutes Official 75 Lectures 13 hours Eduonix Learning Solutions 70 Lectures 8.5 hours Lets Kode It 63 Lectures 6 hours Abhilash Nelson Print Add Notes Bookmark this page
[ { "code": null, "e": 2501, "s": 2340, "text": "The method makedirs() is recursive directory creation function. Like mkdir(), but makes all intermediate-level directories needed to contain the leaf directory." }, { "code": null, "e": 2633, "s": 2501, "text": "The default mode is 0o777 (octal). On some systems, mode is ignored. Where it is used, the current umask value is first masked out." }, { "code": null, "e": 2730, "s": 2633, "text": "If exist_ok is False (the default), an OSError is raised if the target directory already exists." }, { "code": null, "e": 2778, "s": 2730, "text": "Following is the syntax for makedirs() method −" }, { "code": null, "e": 2805, "s": 2778, "text": "os.makedirs(path[, mode])\n" }, { "code": null, "e": 2869, "s": 2805, "text": "path − This is the path, which needs to be created recursively." }, { "code": null, "e": 2933, "s": 2869, "text": "path − This is the path, which needs to be created recursively." }, { "code": null, "e": 2989, "s": 2933, "text": "mode − This is the Mode of the directories to be given." }, { "code": null, "e": 3045, "s": 2989, "text": "mode − This is the Mode of the directories to be given." }, { "code": null, "e": 3084, "s": 3045, "text": "This method does not return any value." }, { "code": null, "e": 3144, "s": 3084, "text": "The following example shows the usage of makedirs() method." }, { "code": null, "e": 3332, "s": 3144, "text": "#!/usr/bin/python3\nimport os, sys\n\n# Path to be created\npath = \"d:/tmp/home/monthly/daily\"\n\nos.makedirs( path, 493 ) #decimal equivalent of 0755 used on Windows\n\nprint (\"Path is created\")" }, { "code": null, "e": 3398, "s": 3332, "text": "When we run the above program, it produces the following result −" }, { "code": null, "e": 3415, "s": 3398, "text": "Path is created\n" }, { "code": null, "e": 3452, "s": 3415, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 3468, "s": 3452, "text": " Malhar Lathkar" }, { "code": null, "e": 3501, "s": 3468, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 3520, "s": 3501, "text": " Arnab Chakraborty" }, { "code": null, "e": 3555, "s": 3520, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 3577, "s": 3555, "text": " In28Minutes Official" }, { "code": null, "e": 3611, "s": 3577, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 3639, "s": 3611, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3674, "s": 3639, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 3688, "s": 3674, "text": " Lets Kode It" }, { "code": null, "e": 3721, "s": 3688, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 3738, "s": 3721, "text": " Abhilash Nelson" }, { "code": null, "e": 3745, "s": 3738, "text": " Print" }, { "code": null, "e": 3756, "s": 3745, "text": " Add Notes" } ]
Find maximum sum of triplets in an array such than i < j < k and a[i] < a[j] < a[k] in C++
With respect of a given array of positive integers of size n, our task to determine the maximum sum of triplet ( ai + aj + ak ) such that 0 <= i < j < k < n and ai< aj< ak. a[] = 3 6 4 2 5 10 19 All possible triplets are:- 3 4 5 => sum = 12 3 6 10 => sum = 19 3 4 10 => sum = 17 4 5 10 => sum = 19 2 5 10 => sum = 17 Maximum sum = 19 Now, a simple approach is to visit for every triplet with three nested ‘for loops’ and determine update the sum of all triplets one by one. Here, time complexity of this method is O(n^3) which is not enough for higher value of ‘n’. Again, we can apply a better approach for making further optimization in above approach. In this method, instead of visiting through every triplet with three nested loops, we can visit through two nested loops. At the time of visiting through each number(let as middle element(aj )), determine maximum number(ai) less than aj preceding it and maximum number(ak ) larger than aj beyond it. Finally, now, update the maximum answer with calculated sum of ai + aj + ak Live Demo // C++ program to find maximum triplet sum #include <bits/stdc++.h> using namespace std; // Shows function to calculate maximum triplet sum int maxTripletSum(int arr1[], int n1){ // Used to initialize the answer int ans1 = 0; for (int i = 1; i < n1 - 1; ++i) { int max1 = 0, max2 = 0; // Determine maximum value(less than arr1[i]) // from i+1 to n1-1 for (int j = 0; j < i; ++j) if (arr1[j] < arr1[i]) max1 = max(max1, arr1[j]); // Determine maximum value(greater than arr1[i]) // from i+1 to n1-1 for (int j = i + 1; j < n1; ++j) if (arr1[j] > arr1[i]) max2 = max(max2, arr1[j]); // store maximum answer if(max1 && max2) ans1=max(ans1,max1+arr1[i]+max2); } return ans1; } // Driver code int main(){ int Arr[] = { 3, 6, 4, 2, 5, 10 }; int N = sizeof(Arr) / sizeof(Arr[0]); cout << maxTripletSum(Arr, N); return 0; } 19
[ { "code": null, "e": 1235, "s": 1062, "text": "With respect of a given array of positive integers of size n, our task to determine the maximum\nsum of triplet ( ai + aj + ak ) such that 0 <= i < j < k < n and ai< aj< ak." }, { "code": null, "e": 1254, "s": 1235, "text": "a[] = 3 6 4 2 5 10" }, { "code": null, "e": 1257, "s": 1254, "text": "19" }, { "code": null, "e": 1396, "s": 1257, "text": "All possible triplets are:-\n3 4 5 => sum = 12\n3 6 10 => sum = 19\n3 4 10 => sum = 17\n4 5 10 => sum = 19\n2 5 10 => sum = 17\nMaximum sum = 19" }, { "code": null, "e": 1628, "s": 1396, "text": "Now, a simple approach is to visit for every triplet with three nested ‘for loops’ and determine update the sum of all triplets one by one. Here, time complexity of this method is O(n^3) which is not enough for higher value of ‘n’." }, { "code": null, "e": 1839, "s": 1628, "text": "Again, we can apply a better approach for making further optimization in above approach. In this method, instead of visiting through every triplet with three nested loops, we can visit through two nested loops." }, { "code": null, "e": 2093, "s": 1839, "text": "At the time of visiting through each number(let as middle element(aj )), determine maximum number(ai) less than aj preceding it and maximum number(ak ) larger than aj beyond it. Finally, now, update the maximum answer with calculated sum of ai + aj + ak" }, { "code": null, "e": 2104, "s": 2093, "text": " Live Demo" }, { "code": null, "e": 3052, "s": 2104, "text": "// C++ program to find maximum triplet sum\n#include <bits/stdc++.h>\nusing namespace std;\n// Shows function to calculate maximum triplet sum\nint maxTripletSum(int arr1[], int n1){\n // Used to initialize the answer\n int ans1 = 0;\n for (int i = 1; i < n1 - 1; ++i) {\n int max1 = 0, max2 = 0;\n // Determine maximum value(less than arr1[i])\n // from i+1 to n1-1\n for (int j = 0; j < i; ++j)\n if (arr1[j] < arr1[i])\n max1 = max(max1, arr1[j]);\n // Determine maximum value(greater than arr1[i])\n // from i+1 to n1-1\n for (int j = i + 1; j < n1; ++j)\n if (arr1[j] > arr1[i])\n max2 = max(max2, arr1[j]);\n // store maximum answer\n if(max1 && max2)\n ans1=max(ans1,max1+arr1[i]+max2);\n }\n return ans1;\n}\n// Driver code\nint main(){\n int Arr[] = { 3, 6, 4, 2, 5, 10 };\n int N = sizeof(Arr) / sizeof(Arr[0]);\n cout << maxTripletSum(Arr, N);\n return 0;\n}" }, { "code": null, "e": 3055, "s": 3052, "text": "19" } ]
How to close or hide the virtual keyboard on Android?
In Android there are some situations, we should close android default keyboard forcefully. For that this example is help for you. 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"?> <android.support.constraint.ConstraintLayout xmlns:android ="http://schemas.android.com/apk/res/android" xmlns:app = "http://schemas.android.com/apk/res-auto" xmlns:tools = "http://schemas.android.com/tools" android:layout_width = "match_parent" android:layout_height = "match_parent" tools:context = ".MainActivity"> <EditText android:id = "@+id/editext" android:layout_width = "match_parent" android:layout_height = "wrap_content"> </EditText> <Button android:id = "@+id/button" android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:text = "Click here to hide" app:layout_constraintBottom_toBottomOf = "parent" app:layout_constraintLeft_toLeftOf = "parent" app:layout_constraintRight_toRightOf = "parent" app:layout_constraintTop_toTopOf = "parent" /> </android.support.constraint.ConstraintLayout> Step 3Add the following code to src/MainActivity.java import android.app.ProgressDialog; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.support.annotation.RequiresApi; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.view.inputmethod.InputMethodManager; import android.widget.Button; import android.widget.EditText; import android.widget.ProgressBar; public class MainActivity extends AppCompatActivity implements View.OnClickListener { Handler mHandler; ProgressDialog mProgressBar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button button = findViewById(R.id.button); EditText editext = findViewById(R.id.editext); editext.requestFocus(); button.setOnClickListener(this); } @RequiresApi(api = Build.VERSION_CODES.O) @Override public void onClick(View v) { switch (v.getId()) { case R.id.button: hideKeybaord(v); break; } } private void hideKeybaord(View v) { InputMethodManager inputMethodManager = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE); inputMethodManager.hideSoftInputFromWindow(v.getApplicationWindowToken(),0); } } In the above code when you click on the button it will hide keyboard. To hide keyboard, use the following code. InputMethodManager inputMethodManager = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE); inputMethodManager.hideSoftInputFromWindow(v.getApplicationWindowToken(),0); Step 5 − Add the following code to manifest file as shown below. <?xml version = "1.0" encoding = "utf-8"?> <manifest xmlns:android = "http://schemas.android.com/apk/res/android" package = "com.example.andy.myapplication"> <application android:allowBackup = "true" android:icon = "@mipmap/ic_launcher" android:label = "@string/app_name" android:roundIcon = "@mipmap/ic_launcher_round" android:supportsRtl = "true" android:theme = "@style/AppTheme"> <activity android:name = ".MainActivity" android:windowSoftInputMode = "stateAlwaysVisible"> <intent-filter> <action android:name = "android.intent.action.MAIN" /> <category android:name = "android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> In the above code it contains windowSoftInputMode, it means it will show keyboard always when edit text is request focused. Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen − Now click on the button. it will hide keyboard as shown below −
[ { "code": null, "e": 1192, "s": 1062, "text": "In Android there are some situations, we should close android default keyboard forcefully. For that this example is help for you." }, { "code": null, "e": 1321, "s": 1192, "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": 1386, "s": 1321, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2353, "s": 1386, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<android.support.constraint.ConstraintLayout xmlns:android =\"http://schemas.android.com/apk/res/android\"\n xmlns:app = \"http://schemas.android.com/apk/res-auto\"\n xmlns:tools = \"http://schemas.android.com/tools\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\"\n tools:context = \".MainActivity\">\n <EditText \n android:id = \"@+id/editext\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\">\n </EditText>\n <Button\n android:id = \"@+id/button\"\n android:layout_width = \"wrap_content\"\n android:layout_height = \"wrap_content\"\n android:text = \"Click here to hide\"\n app:layout_constraintBottom_toBottomOf = \"parent\"\n app:layout_constraintLeft_toLeftOf = \"parent\"\n app:layout_constraintRight_toRightOf = \"parent\"\n app:layout_constraintTop_toTopOf = \"parent\" />\n</android.support.constraint.ConstraintLayout>" }, { "code": null, "e": 2407, "s": 2353, "text": "Step 3Add the following code to src/MainActivity.java" }, { "code": null, "e": 3704, "s": 2407, "text": "import android.app.ProgressDialog;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.os.Handler;\nimport android.support.annotation.RequiresApi;\nimport android.support.v7.app.AppCompatActivity;\nimport android.view.View;\nimport android.view.inputmethod.InputMethodManager;\nimport android.widget.Button;\nimport android.widget.EditText;\nimport android.widget.ProgressBar;\npublic class MainActivity extends AppCompatActivity implements View.OnClickListener {\n Handler mHandler;\n ProgressDialog mProgressBar;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n Button button = findViewById(R.id.button);\n EditText editext = findViewById(R.id.editext);\n editext.requestFocus();\n button.setOnClickListener(this);\n }\n @RequiresApi(api = Build.VERSION_CODES.O)\n @Override\n public void onClick(View v) {\n switch (v.getId()) {\n case R.id.button:\n hideKeybaord(v);\n break;\n }\n }\n private void hideKeybaord(View v) {\n InputMethodManager inputMethodManager = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);\n inputMethodManager.hideSoftInputFromWindow(v.getApplicationWindowToken(),0);\n }\n}" }, { "code": null, "e": 3816, "s": 3704, "text": "In the above code when you click on the button it will hide keyboard. To hide keyboard, use the following code." }, { "code": null, "e": 3993, "s": 3816, "text": "InputMethodManager inputMethodManager = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);\ninputMethodManager.hideSoftInputFromWindow(v.getApplicationWindowToken(),0);" }, { "code": null, "e": 4058, "s": 3993, "text": "Step 5 − Add the following code to manifest file as shown below." }, { "code": null, "e": 4821, "s": 4058, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<manifest xmlns:android = \"http://schemas.android.com/apk/res/android\" package = \"com.example.andy.myapplication\">\n <application\n android:allowBackup = \"true\"\n android:icon = \"@mipmap/ic_launcher\"\n android:label = \"@string/app_name\"\n android:roundIcon = \"@mipmap/ic_launcher_round\"\n android:supportsRtl = \"true\"\n android:theme = \"@style/AppTheme\">\n <activity android:name = \".MainActivity\" android:windowSoftInputMode = \"stateAlwaysVisible\">\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": 4945, "s": 4821, "text": "In the above code it contains windowSoftInputMode, it means it will show keyboard always when edit text is request focused." }, { "code": null, "e": 5293, "s": 4945, "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": 5357, "s": 5293, "text": "Now click on the button. it will hide keyboard as shown below −" } ]
Vectors with Uniformly Spaced Elements
MATLAB allows you to create a vector with uniformly spaced elements. To create a vector v with the first element f, last element l, and the difference between elements is any real number n, we write − v = [f : n : l] Create a script file with the following code − v = [1: 2: 20]; sqv = v.^2; disp(v); disp(sqv); When you run the file, it displays the following result − 1 3 5 7 9 11 13 15 17 19 1 9 25 49 81 121 169 225 289 361 30 Lectures 4 hours Nouman Azam 127 Lectures 12 hours Nouman Azam 17 Lectures 3 hours Sanjeev 37 Lectures 5 hours TELCOMA Global 22 Lectures 4 hours TELCOMA Global 18 Lectures 3 hours Phinite Academy Print Add Notes Bookmark this page
[ { "code": null, "e": 2210, "s": 2141, "text": "MATLAB allows you to create a vector with uniformly spaced elements." }, { "code": null, "e": 2342, "s": 2210, "text": "To create a vector v with the first element f, last element l, and the difference between elements is any real number n, we write −" }, { "code": null, "e": 2359, "s": 2342, "text": "v = [f : n : l]\n" }, { "code": null, "e": 2406, "s": 2359, "text": "Create a script file with the following code −" }, { "code": null, "e": 2454, "s": 2406, "text": "v = [1: 2: 20];\nsqv = v.^2;\ndisp(v);\ndisp(sqv);" }, { "code": null, "e": 2512, "s": 2454, "text": "When you run the file, it displays the following result −" }, { "code": null, "e": 2619, "s": 2512, "text": "1 3 5 7 9 11 13 15 17 19\n 1 9 25 49 81 121 169 225 289 361\n" }, { "code": null, "e": 2652, "s": 2619, "text": "\n 30 Lectures \n 4 hours \n" }, { "code": null, "e": 2665, "s": 2652, "text": " Nouman Azam" }, { "code": null, "e": 2700, "s": 2665, "text": "\n 127 Lectures \n 12 hours \n" }, { "code": null, "e": 2713, "s": 2700, "text": " Nouman Azam" }, { "code": null, "e": 2746, "s": 2713, "text": "\n 17 Lectures \n 3 hours \n" }, { "code": null, "e": 2755, "s": 2746, "text": " Sanjeev" }, { "code": null, "e": 2788, "s": 2755, "text": "\n 37 Lectures \n 5 hours \n" }, { "code": null, "e": 2804, "s": 2788, "text": " TELCOMA Global" }, { "code": null, "e": 2837, "s": 2804, "text": "\n 22 Lectures \n 4 hours \n" }, { "code": null, "e": 2853, "s": 2837, "text": " TELCOMA Global" }, { "code": null, "e": 2886, "s": 2853, "text": "\n 18 Lectures \n 3 hours \n" }, { "code": null, "e": 2903, "s": 2886, "text": " Phinite Academy" }, { "code": null, "e": 2910, "s": 2903, "text": " Print" }, { "code": null, "e": 2921, "s": 2910, "text": " Add Notes" } ]
Abstract base classes and how to use them in your data science project | by Sebastian Dick | Towards Data Science
Have you ever encountered code like this and wondered what’s so abstract about these classes and methods? Well, I’m about to show you! If you stick around long enough I will also share a little trick that you can use to automate unit testing across your classes. One key concept of object-oriented programming (OOP) is inheritance. Inheritance means that we base one (child-)class on another (parent-)class. The child class thereby inherits certain properties from its parent while at the same time implementing new ones. Let’s look at an example. Imagine you want to write a software library about the animal world. You would perhaps start by defining a class Animal: class Animal: def __init__(self, height, weight): self.height = height self.weight = weight Animal is a very general term, which is why you would like to create more specific classes: class Dog(Animal): def make_sound(self): print('woof!')class Cat(Animal): def make_sound(self): print('meow!') def pounce(self): print('Pouncing at prey!') Writing Animal in parentheses indicates that Dog and Cat inherit from the Animal class. This means that, without having to write it out, both animals automatically implement the __init__ method. In addition, both child classes implement their own methods: “make_sound” and “pounce”. As a rule of thumb, inheritance makes sense if your two classes fit the sentence “A is a B”: “Dog is an Animal”. Let’s say you want to implement a lion class. Lions are cats, so we would want the class to inherit from Cat. Doing so, the methods that Cat inherited from Animal carry over to Lion as well class Lion(Cat): def make_sound(self): print('roar!') The class Lion now has three methods: __init__, pounce and make_sound. By redefining make_sound in the Lion class we have overwritten the version inherited from Cat. Abstract base classes (ABC) provide a way to regulate this inheritance and at the same time structure your code. An ABC can be seen as the scaffolding or template (not to be confused with actual templates, think: C++!) for all classes inheriting from it. In Python, one can define an ABC by inheriting from abc.ABC: import abc class Animal(abc.ABC): An ABC is not meant to be instantiated, i.e. one should not (and in certain cases cannot) create objects of an ABC. my_animal = Animal(height=100, weight=80) #Don't do this! So, why bother using abstract base classes at all? Because, as I said before, they add structure and safety to your project. The ABC “Animal” tells future developers working on your code (or future you) how any class inheriting from Animal should operate. To do so, ABCs have a tool at their disposal: Abstract Methods An abstract method is a method that has to be implemented by any class inheriting from the ABC. We could, e.g. decide that every animal in our code has to be able to make some kind of sound. We can then define: from abc import ABC, abstractmethodclass Animal(ABC): def __init__(self, height, weight): self.height = height self.weight = weight @abstractmethod def make_sound(self): passclass Bird(Animal): def fly(self): print('I am flying') If we try to instantiate any child-class that does not implement the abstract method, we get the following error: tweetie = Bird(height=5, weight=1)>>> TypeError: Can't instantiate abstract class Bird with abstract methods make_sound At the beginning of a new project, a developer should pause and consider which methods are absolutely necessary for a class to operate properly. These methods should be declared abstract methods to avoid unexpected runtime errors in the future. In my opinion this is especially important in non-compiled languages such as Python, which can be notoriously fragile to these errors. Many popular data science and machine learning library use abstract base classes. One of those libraries is scikit-learn. The code snippet at the beginning of this post contains scikit-learn’s implementation of a “Kernel” base class. Kernels are used in Support Vector Machines, Kernel Ridge and Gaussian Process methods among others. They can be seen as a distance metric between two vectors. You might be familiar with the Radial Basis Function (RBF) or squared exponential kernel but many others exist and are implemented in scikit-learn. What all these kernels have in common, is that (in scikit-learn) they inherit from the Kernel ABC: By making __call__, and is_stationary abstract methods, scikit-learn ensures that every new kernel will implement theses methods. At least in the case of __call__(self, X, Y), this is very reasonable, as a function to evaluate the kernel on two input matrices is absolutely necessary. Without it, the kernel would not have much use. Wouldn’t it be great to automatically generate unit-tests for every new child of the Kernel class? Thankfully, there is! By creating a so-called registry we only need to implement a single unit-test once to apply it across our classes (one can do other fun things with registries, but I won’t get into any details here). A registry simply keeps track of all the classes you create. To implement a registry in Python, we need to use meta-classes. What are meta-classes? One way to look at it is the following: While a class tells Python how an instance of a class behaves, a meta-class defines the behavior of the class itself. [1] So, by using a meta-class we can tell Python: “Create a new entry in the registry whenever a new class is implemented” If all this sounds very confusing, you can also just copy paste the following code into your project: (Note that in principle the registry does not have to inherit from ABCMeta but it usually makes sense to combine the two.) Let’s go back to our Kernel example. Instead of inheriting from ABC, we now write class Kernel(metaclass=ABCRegistry): _registry_name = 'kernel' ...class RBF(Kernel): _registry_name = 'rbf' ...class DotProduct(Kernel): _registry_name = 'dotproduct' ... By creating the attribute _registry_name, we tell our registry how to call the classes. Accessing the registry will produce the following output: Kernel.get_registry()>>> {'kernel': Kernel, 'rbf': RBF, 'dot': Dot} Let’s say we want to test whether the kernels we implemented are symmetric: K(X, Y) = K(Y, X) Every valid kernel has to obey this condition, so it makes perfect sense to test for it. Using pytest and its parametrize functionality we can now automatically apply the test to every class that inherits from “Kernel”: Of course, one could always explicitly loop over all relevant classes. The use of a registry has the advantage that contributors adding new classes don’t need to worry about adding entries to the appropriate tests as well. If you enjoyed this article please feel free to follow me here, on twitter or connect on LinkedIn. References [1] Loosely based on Thomas Wouters’ explanation on stackoverflow.
[ { "code": null, "e": 307, "s": 172, "text": "Have you ever encountered code like this and wondered what’s so abstract about these classes and methods? Well, I’m about to show you!" }, { "code": null, "e": 435, "s": 307, "text": "If you stick around long enough I will also share a little trick that you can use to automate unit testing across your classes." }, { "code": null, "e": 694, "s": 435, "text": "One key concept of object-oriented programming (OOP) is inheritance. Inheritance means that we base one (child-)class on another (parent-)class. The child class thereby inherits certain properties from its parent while at the same time implementing new ones." }, { "code": null, "e": 841, "s": 694, "text": "Let’s look at an example. Imagine you want to write a software library about the animal world. You would perhaps start by defining a class Animal:" }, { "code": null, "e": 950, "s": 841, "text": "class Animal: def __init__(self, height, weight): self.height = height self.weight = weight" }, { "code": null, "e": 1042, "s": 950, "text": "Animal is a very general term, which is why you would like to create more specific classes:" }, { "code": null, "e": 1242, "s": 1042, "text": "class Dog(Animal): def make_sound(self): print('woof!')class Cat(Animal): def make_sound(self): print('meow!') def pounce(self): print('Pouncing at prey!')" }, { "code": null, "e": 1638, "s": 1242, "text": "Writing Animal in parentheses indicates that Dog and Cat inherit from the Animal class. This means that, without having to write it out, both animals automatically implement the __init__ method. In addition, both child classes implement their own methods: “make_sound” and “pounce”. As a rule of thumb, inheritance makes sense if your two classes fit the sentence “A is a B”: “Dog is an Animal”." }, { "code": null, "e": 1828, "s": 1638, "text": "Let’s say you want to implement a lion class. Lions are cats, so we would want the class to inherit from Cat. Doing so, the methods that Cat inherited from Animal carry over to Lion as well" }, { "code": null, "e": 1897, "s": 1828, "text": "class Lion(Cat): def make_sound(self): print('roar!')" }, { "code": null, "e": 2063, "s": 1897, "text": "The class Lion now has three methods: __init__, pounce and make_sound. By redefining make_sound in the Lion class we have overwritten the version inherited from Cat." }, { "code": null, "e": 2318, "s": 2063, "text": "Abstract base classes (ABC) provide a way to regulate this inheritance and at the same time structure your code. An ABC can be seen as the scaffolding or template (not to be confused with actual templates, think: C++!) for all classes inheriting from it." }, { "code": null, "e": 2379, "s": 2318, "text": "In Python, one can define an ABC by inheriting from abc.ABC:" }, { "code": null, "e": 2413, "s": 2379, "text": "import abc class Animal(abc.ABC):" }, { "code": null, "e": 2529, "s": 2413, "text": "An ABC is not meant to be instantiated, i.e. one should not (and in certain cases cannot) create objects of an ABC." }, { "code": null, "e": 2587, "s": 2529, "text": "my_animal = Animal(height=100, weight=80) #Don't do this!" }, { "code": null, "e": 2889, "s": 2587, "text": "So, why bother using abstract base classes at all? Because, as I said before, they add structure and safety to your project. The ABC “Animal” tells future developers working on your code (or future you) how any class inheriting from Animal should operate. To do so, ABCs have a tool at their disposal:" }, { "code": null, "e": 2906, "s": 2889, "text": "Abstract Methods" }, { "code": null, "e": 3002, "s": 2906, "text": "An abstract method is a method that has to be implemented by any class inheriting from the ABC." }, { "code": null, "e": 3117, "s": 3002, "text": "We could, e.g. decide that every animal in our code has to be able to make some kind of sound. We can then define:" }, { "code": null, "e": 3387, "s": 3117, "text": "from abc import ABC, abstractmethodclass Animal(ABC): def __init__(self, height, weight): self.height = height self.weight = weight @abstractmethod def make_sound(self): passclass Bird(Animal): def fly(self): print('I am flying')" }, { "code": null, "e": 3501, "s": 3387, "text": "If we try to instantiate any child-class that does not implement the abstract method, we get the following error:" }, { "code": null, "e": 3621, "s": 3501, "text": "tweetie = Bird(height=5, weight=1)>>> TypeError: Can't instantiate abstract class Bird with abstract methods make_sound" }, { "code": null, "e": 3866, "s": 3621, "text": "At the beginning of a new project, a developer should pause and consider which methods are absolutely necessary for a class to operate properly. These methods should be declared abstract methods to avoid unexpected runtime errors in the future." }, { "code": null, "e": 4001, "s": 3866, "text": "In my opinion this is especially important in non-compiled languages such as Python, which can be notoriously fragile to these errors." }, { "code": null, "e": 4484, "s": 4001, "text": "Many popular data science and machine learning library use abstract base classes. One of those libraries is scikit-learn. The code snippet at the beginning of this post contains scikit-learn’s implementation of a “Kernel” base class. Kernels are used in Support Vector Machines, Kernel Ridge and Gaussian Process methods among others. They can be seen as a distance metric between two vectors. You might be familiar with the Radial Basis Function (RBF) or squared exponential kernel" }, { "code": null, "e": 4543, "s": 4484, "text": "but many others exist and are implemented in scikit-learn." }, { "code": null, "e": 4642, "s": 4543, "text": "What all these kernels have in common, is that (in scikit-learn) they inherit from the Kernel ABC:" }, { "code": null, "e": 4975, "s": 4642, "text": "By making __call__, and is_stationary abstract methods, scikit-learn ensures that every new kernel will implement theses methods. At least in the case of __call__(self, X, Y), this is very reasonable, as a function to evaluate the kernel on two input matrices is absolutely necessary. Without it, the kernel would not have much use." }, { "code": null, "e": 5074, "s": 4975, "text": "Wouldn’t it be great to automatically generate unit-tests for every new child of the Kernel class?" }, { "code": null, "e": 5096, "s": 5074, "text": "Thankfully, there is!" }, { "code": null, "e": 5296, "s": 5096, "text": "By creating a so-called registry we only need to implement a single unit-test once to apply it across our classes (one can do other fun things with registries, but I won’t get into any details here)." }, { "code": null, "e": 5421, "s": 5296, "text": "A registry simply keeps track of all the classes you create. To implement a registry in Python, we need to use meta-classes." }, { "code": null, "e": 5444, "s": 5421, "text": "What are meta-classes?" }, { "code": null, "e": 5484, "s": 5444, "text": "One way to look at it is the following:" }, { "code": null, "e": 5606, "s": 5484, "text": "While a class tells Python how an instance of a class behaves, a meta-class defines the behavior of the class itself. [1]" }, { "code": null, "e": 5725, "s": 5606, "text": "So, by using a meta-class we can tell Python: “Create a new entry in the registry whenever a new class is implemented”" }, { "code": null, "e": 5827, "s": 5725, "text": "If all this sounds very confusing, you can also just copy paste the following code into your project:" }, { "code": null, "e": 5950, "s": 5827, "text": "(Note that in principle the registry does not have to inherit from ABCMeta but it usually makes sense to combine the two.)" }, { "code": null, "e": 6032, "s": 5950, "text": "Let’s go back to our Kernel example. Instead of inheriting from ABC, we now write" }, { "code": null, "e": 6224, "s": 6032, "text": "class Kernel(metaclass=ABCRegistry): _registry_name = 'kernel' ...class RBF(Kernel): _registry_name = 'rbf' ...class DotProduct(Kernel): _registry_name = 'dotproduct' ..." }, { "code": null, "e": 6370, "s": 6224, "text": "By creating the attribute _registry_name, we tell our registry how to call the classes. Accessing the registry will produce the following output:" }, { "code": null, "e": 6438, "s": 6370, "text": "Kernel.get_registry()>>> {'kernel': Kernel, 'rbf': RBF, 'dot': Dot}" }, { "code": null, "e": 6514, "s": 6438, "text": "Let’s say we want to test whether the kernels we implemented are symmetric:" }, { "code": null, "e": 6532, "s": 6514, "text": "K(X, Y) = K(Y, X)" }, { "code": null, "e": 6621, "s": 6532, "text": "Every valid kernel has to obey this condition, so it makes perfect sense to test for it." }, { "code": null, "e": 6752, "s": 6621, "text": "Using pytest and its parametrize functionality we can now automatically apply the test to every class that inherits from “Kernel”:" }, { "code": null, "e": 6975, "s": 6752, "text": "Of course, one could always explicitly loop over all relevant classes. The use of a registry has the advantage that contributors adding new classes don’t need to worry about adding entries to the appropriate tests as well." }, { "code": null, "e": 7074, "s": 6975, "text": "If you enjoyed this article please feel free to follow me here, on twitter or connect on LinkedIn." }, { "code": null, "e": 7085, "s": 7074, "text": "References" } ]
How to count the number of columns in a table in Selenium with python?
We can count the number of columns in a table in Selenium. The headers of a table are represented by <th> tag in html and always in the first row of the table. The rows are identified with <tr> tag in html. The total count of the number of column headers is mostly equal to the total number of columns. A <th> tag’s parent is always a <tr> tag. The logic is to get all the headers. We shall use the locator xpath and then use find_elements_by_xpath method. The list of headers will be returned. Next we need to compute the size of the list with the help of len method. driver.find_elements_by_xpath("//table/tbody/tr[1]/th") The html code snippet of a table column count is as described below − Code Implementation for getting total column count. from selenium import webdriver #browser exposes an executable file #Through Selenium test we will invoke the executable file which will then #invoke actual browser driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe") # to maximize the browser window driver.maximize_window() #get method to launch the URL driver.get("https://www.tutorialspoint.com/plsql/plsql_basic_syntax.htm") #to refresh the browser driver.refresh() # identifying the header from row1 having <th> tag cols = driver.find_elements_by_xpath("//table/tbody/tr[1]/th") # len method is used to get the size of that list print(len(cols)) #to close the browser driver.close()
[ { "code": null, "e": 1407, "s": 1062, "text": "We can count the number of columns in a table in Selenium. The headers\nof a table are represented by <th> tag in html and always in the first row of the\ntable. The rows are identified with <tr> tag in html. The total count of the number\nof column headers is mostly equal to the total number of columns. A <th> tag’s\nparent is always a <tr> tag." }, { "code": null, "e": 1631, "s": 1407, "text": "The logic is to get all the headers. We shall use the locator xpath and then use find_elements_by_xpath method. The list of headers will be returned. Next we need to compute the size of the list with the help of len method." }, { "code": null, "e": 1687, "s": 1631, "text": "driver.find_elements_by_xpath(\"//table/tbody/tr[1]/th\")" }, { "code": null, "e": 1757, "s": 1687, "text": "The html code snippet of a table column count is as described below −" }, { "code": null, "e": 1809, "s": 1757, "text": "Code Implementation for getting total column count." }, { "code": null, "e": 2460, "s": 1809, "text": "from selenium import webdriver\n#browser exposes an executable file\n#Through Selenium test we will invoke the executable file which will then\n#invoke actual browser\ndriver = webdriver.Chrome(executable_path=\"C:\\\\chromedriver.exe\")\n# to maximize the browser window\ndriver.maximize_window()\n#get method to launch the URL\ndriver.get(\"https://www.tutorialspoint.com/plsql/plsql_basic_syntax.htm\")\n#to refresh the browser\ndriver.refresh()\n# identifying the header from row1 having <th> tag\ncols = driver.find_elements_by_xpath(\"//table/tbody/tr[1]/th\")\n# len method is used to get the size of that list\nprint(len(cols))\n#to close the browser\ndriver.close()" } ]
Jackson Annotations - Mixin
Mixin Annotation is a way to associate annotations without modifying the target class. See the example below − import java.io.IOException; import com.fasterxml.jackson.annotation.JsonIgnoreType; import com.fasterxml.jackson.databind.MapperFeature; import com.fasterxml.jackson.databind.ObjectMapper; public class JacksonTester { public static void main(String args[]) { ObjectMapper mapper = new ObjectMapper(); try { Student student = new Student(1,11,"1ab","Mark"); String jsonString = mapper .writerWithDefaultPrettyPrinter() .writeValueAsString(student); System.out.println(jsonString); ObjectMapper mapper1 = new ObjectMapper(); mapper1.addMixIn(Name.class, MixInForIgnoreType.class); jsonString = mapper1 .writerWithDefaultPrettyPrinter() .writeValueAsString(student); System.out.println(jsonString); } catch (IOException e) { e.printStackTrace(); } } } class Student { public int id; public String systemId; public int rollNo; public Name nameObj; Student(int id, int rollNo, String systemId, String name) { this.id = id; this.systemId = systemId; this.rollNo = rollNo; nameObj = new Name(name); } } class Name { public String name; Name(String name){ this.name = name; } } @JsonIgnoreType class MixInForIgnoreType {} { "id" : 1, "systemId" : "1ab", "rollNo" : 11, "nameObj" : { "name" : "Mark" } } { "id" : 1, "systemId" : "1ab", "rollNo" : 11 } Print Add Notes Bookmark this page
[ { "code": null, "e": 2586, "s": 2475, "text": "Mixin Annotation is a way to associate annotations without modifying the target class. See the example below −" }, { "code": null, "e": 3937, "s": 2586, "text": "import java.io.IOException;\n\nimport com.fasterxml.jackson.annotation.JsonIgnoreType;\nimport com.fasterxml.jackson.databind.MapperFeature;\nimport com.fasterxml.jackson.databind.ObjectMapper;\n\npublic class JacksonTester {\n public static void main(String args[]) {\n ObjectMapper mapper = new ObjectMapper();\n try {\n Student student = new Student(1,11,\"1ab\",\"Mark\"); \n String jsonString = mapper\n .writerWithDefaultPrettyPrinter()\n .writeValueAsString(student);\n System.out.println(jsonString);\n\n ObjectMapper mapper1 = new ObjectMapper();\n mapper1.addMixIn(Name.class, MixInForIgnoreType.class);\n jsonString = mapper1\n .writerWithDefaultPrettyPrinter()\n .writeValueAsString(student);\n System.out.println(jsonString);\n }\n catch (IOException e) { \n e.printStackTrace();\n } \n }\n}\nclass Student {\n public int id;\n public String systemId;\n public int rollNo;\n public Name nameObj;\n\n Student(int id, int rollNo, String systemId, String name) {\n this.id = id;\n this.systemId = systemId;\n this.rollNo = rollNo;\n nameObj = new Name(name);\n }\n}\nclass Name {\n public String name;\n Name(String name){\n this.name = name;\n } \n}\n@JsonIgnoreType\nclass MixInForIgnoreType {}" }, { "code": null, "e": 4097, "s": 3937, "text": "{\n \"id\" : 1,\n \"systemId\" : \"1ab\",\n \"rollNo\" : 11,\n \"nameObj\" : {\n \"name\" : \"Mark\"\n }\n}\n{\n \"id\" : 1,\n \"systemId\" : \"1ab\",\n \"rollNo\" : 11\n}\n" }, { "code": null, "e": 4104, "s": 4097, "text": " Print" }, { "code": null, "e": 4115, "s": 4104, "text": " Add Notes" } ]
How to Share Image of Your App with Another App in Android? - GeeksforGeeks
12 Mar, 2021 Most of the time while using an app we want to share images from the app to another app. While using Many Social Media Platforms we find this feature to be very useful when we want to share information from one app to another. The Android Intent resolver is used when sending data to another app as part of a well-defined task flow. To use the Android intent resolver, create an intent and add extras. Here we are going to understand how to do that. Note: If you want to share the Text of Your App with Another App in Android then please refer to this. Step 1: Create a new Project To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language. Step 2: Working with the AndroidManifest.xml file Add the following permission to the AndroidManifest.xml file <uses-permission android:name=”android.permission.READ_EXTERNAL_STORAGE” /> <uses-permission android:name=”android.permission.WRITE_EXTERNAL_STORAGE” /> Add the following lines inside the <application> tag and after the </acticty> tag. XML <provider android:name="androidx.core.content.FileProvider" <!-- Write down your package name --> android:authorities="com.anni.shareimage.fileprovider" android:exported="false" android:grantUriPermissions="true"> <!-- we intend to request content URIs for the images/subdirectory of your private file area --> <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/paths" /></provider> Below is the complete code for the AndroidManifest.xml file XML <?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.anni.shareimage"> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <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=".ViewPdfActivity"></activity> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <provider android:name="androidx.core.content.FileProvider" android:authorities="com.anni.shareimage.fileprovider" android:exported="false" android:grantUriPermissions="true"> <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/paths" /> </provider> </application> </manifest> Step 3: Create a new XML file Create an XML directory in res and then create a paths.xml file in it. A file Provider can only generate a content URI for files in directories that we specify beforehand. We specify a directory, specify its storage area and path in XML, using child elements of the <paths> element. Below is the video of creating the XML file. XML <?xml version="1.0" encoding="utf-8"?><paths> <cache-path name="shared_images" path="images/" /></paths> Step 4: Working with the activity_main.xml file Go to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file. Reference article: How to Add Image to Drawable Folder in Android Studio? XML <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:orientation="vertical" tools:context=".MainActivity"> <!-- Here we will attach our image to share --> <ImageView android:id="@+id/shareimage" android:layout_width="200dp" android:layout_height="200dp" android:src="@drawable/image" /> <!-- We will click on it then shareonlytext function will be called--> <Button android:id="@+id/share" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:background="@color/colorPrimary" android:padding="10dp" android:text="Click here to Share " android:textSize="10dp" /> </LinearLayout> Step 5: Working with the MainActivity.java file Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail. Java import android.content.Intent;import android.graphics.Bitmap;import android.graphics.drawable.BitmapDrawable;import android.net.Uri;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.ImageView;import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity;import androidx.core.content.FileProvider; import java.io.File;import java.io.FileOutputStream; public class MainActivity extends AppCompatActivity { Button share; ImageView imageView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); share = findViewById(R.id.share); imageView = findViewById(R.id.shareimage); // initialising text field where we will enter data share.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // Now share image function will be called // here we will be passing the text to share // Getting drawable value from image BitmapDrawable bitmapDrawable = (BitmapDrawable) imageView.getDrawable(); Bitmap bitmap = bitmapDrawable.getBitmap(); shareImageandText(bitmap); } }); } private void shareImageandText(Bitmap bitmap) { Uri uri = getmageToShare(bitmap); Intent intent = new Intent(Intent.ACTION_SEND); // putting uri of image to be shared intent.putExtra(Intent.EXTRA_STREAM, uri); // adding text to share intent.putExtra(Intent.EXTRA_TEXT, "Sharing Image"); // Add subject Here intent.putExtra(Intent.EXTRA_SUBJECT, "Subject Here"); // setting type to image intent.setType("image/png"); // calling startactivity() to share startActivity(Intent.createChooser(intent, "Share Via")); } // Retrieving the url to share private Uri getmageToShare(Bitmap bitmap) { File imagefolder = new File(getCacheDir(), "images"); Uri uri = null; try { imagefolder.mkdirs(); File file = new File(imagefolder, "shared_image.png"); FileOutputStream outputStream = new FileOutputStream(file); bitmap.compress(Bitmap.CompressFormat.PNG, 90, outputStream); outputStream.flush(); outputStream.close(); uri = FileProvider.getUriForFile(this, "com.anni.shareimage.fileprovider", file); } catch (Exception e) { Toast.makeText(this, "" + e.getMessage(), Toast.LENGTH_LONG).show(); } return uri; }} Output: Android Java Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Flutter - Custom Bottom Navigation Bar Retrofit with Kotlin Coroutine in Android GridView in Android with Example How to Change the Background Color After Clicking the Button in Android? Android Listview in Java with Example Arrays in Java Split() String method in Java with examples For-each loop in Java Arrays.sort() in Java with examples Reverse a string in Java
[ { "code": null, "e": 25140, "s": 25112, "text": "\n12 Mar, 2021" }, { "code": null, "e": 25590, "s": 25140, "text": "Most of the time while using an app we want to share images from the app to another app. While using Many Social Media Platforms we find this feature to be very useful when we want to share information from one app to another. The Android Intent resolver is used when sending data to another app as part of a well-defined task flow. To use the Android intent resolver, create an intent and add extras. Here we are going to understand how to do that." }, { "code": null, "e": 25693, "s": 25590, "text": "Note: If you want to share the Text of Your App with Another App in Android then please refer to this." }, { "code": null, "e": 25722, "s": 25693, "text": "Step 1: Create a new Project" }, { "code": null, "e": 25886, "s": 25722, "text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language. " }, { "code": null, "e": 25936, "s": 25886, "text": "Step 2: Working with the AndroidManifest.xml file" }, { "code": null, "e": 25997, "s": 25936, "text": "Add the following permission to the AndroidManifest.xml file" }, { "code": null, "e": 26073, "s": 25997, "text": "<uses-permission android:name=”android.permission.READ_EXTERNAL_STORAGE” />" }, { "code": null, "e": 26150, "s": 26073, "text": "<uses-permission android:name=”android.permission.WRITE_EXTERNAL_STORAGE” />" }, { "code": null, "e": 26233, "s": 26150, "text": "Add the following lines inside the <application> tag and after the </acticty> tag." }, { "code": null, "e": 26237, "s": 26233, "text": "XML" }, { "code": "<provider android:name=\"androidx.core.content.FileProvider\" <!-- Write down your package name --> android:authorities=\"com.anni.shareimage.fileprovider\" android:exported=\"false\" android:grantUriPermissions=\"true\"> <!-- we intend to request content URIs for the images/subdirectory of your private file area --> <meta-data android:name=\"android.support.FILE_PROVIDER_PATHS\" android:resource=\"@xml/paths\" /></provider>", "e": 26699, "s": 26237, "text": null }, { "code": null, "e": 26759, "s": 26699, "text": "Below is the complete code for the AndroidManifest.xml file" }, { "code": null, "e": 26763, "s": 26759, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"com.anni.shareimage\"> <uses-permission android:name=\"android.permission.READ_EXTERNAL_STORAGE\" /> <uses-permission android:name=\"android.permission.WRITE_EXTERNAL_STORAGE\" /> <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=\".ViewPdfActivity\"></activity> <activity android:name=\".MainActivity\"> <intent-filter> <action android:name=\"android.intent.action.MAIN\" /> <category android:name=\"android.intent.category.LAUNCHER\" /> </intent-filter> </activity> <provider android:name=\"androidx.core.content.FileProvider\" android:authorities=\"com.anni.shareimage.fileprovider\" android:exported=\"false\" android:grantUriPermissions=\"true\"> <meta-data android:name=\"android.support.FILE_PROVIDER_PATHS\" android:resource=\"@xml/paths\" /> </provider> </application> </manifest>", "e": 28069, "s": 26763, "text": null }, { "code": null, "e": 28099, "s": 28069, "text": "Step 3: Create a new XML file" }, { "code": null, "e": 28427, "s": 28099, "text": "Create an XML directory in res and then create a paths.xml file in it. A file Provider can only generate a content URI for files in directories that we specify beforehand. We specify a directory, specify its storage area and path in XML, using child elements of the <paths> element. Below is the video of creating the XML file." }, { "code": null, "e": 28431, "s": 28427, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><paths> <cache-path name=\"shared_images\" path=\"images/\" /></paths>", "e": 28553, "s": 28431, "text": null }, { "code": null, "e": 28601, "s": 28553, "text": "Step 4: Working with the activity_main.xml file" }, { "code": null, "e": 28717, "s": 28601, "text": "Go to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file." }, { "code": null, "e": 28791, "s": 28717, "text": "Reference article: How to Add Image to Drawable Folder in Android Studio?" }, { "code": null, "e": 28795, "s": 28791, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:gravity=\"center\" android:orientation=\"vertical\" tools:context=\".MainActivity\"> <!-- Here we will attach our image to share --> <ImageView android:id=\"@+id/shareimage\" android:layout_width=\"200dp\" android:layout_height=\"200dp\" android:src=\"@drawable/image\" /> <!-- We will click on it then shareonlytext function will be called--> <Button android:id=\"@+id/share\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"10dp\" android:background=\"@color/colorPrimary\" android:padding=\"10dp\" android:text=\"Click here to Share \" android:textSize=\"10dp\" /> </LinearLayout>", "e": 29780, "s": 28795, "text": null }, { "code": null, "e": 29828, "s": 29780, "text": "Step 5: Working with the MainActivity.java file" }, { "code": null, "e": 30018, "s": 29828, "text": "Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 30023, "s": 30018, "text": "Java" }, { "code": "import android.content.Intent;import android.graphics.Bitmap;import android.graphics.drawable.BitmapDrawable;import android.net.Uri;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.ImageView;import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity;import androidx.core.content.FileProvider; import java.io.File;import java.io.FileOutputStream; public class MainActivity extends AppCompatActivity { Button share; ImageView imageView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); share = findViewById(R.id.share); imageView = findViewById(R.id.shareimage); // initialising text field where we will enter data share.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // Now share image function will be called // here we will be passing the text to share // Getting drawable value from image BitmapDrawable bitmapDrawable = (BitmapDrawable) imageView.getDrawable(); Bitmap bitmap = bitmapDrawable.getBitmap(); shareImageandText(bitmap); } }); } private void shareImageandText(Bitmap bitmap) { Uri uri = getmageToShare(bitmap); Intent intent = new Intent(Intent.ACTION_SEND); // putting uri of image to be shared intent.putExtra(Intent.EXTRA_STREAM, uri); // adding text to share intent.putExtra(Intent.EXTRA_TEXT, \"Sharing Image\"); // Add subject Here intent.putExtra(Intent.EXTRA_SUBJECT, \"Subject Here\"); // setting type to image intent.setType(\"image/png\"); // calling startactivity() to share startActivity(Intent.createChooser(intent, \"Share Via\")); } // Retrieving the url to share private Uri getmageToShare(Bitmap bitmap) { File imagefolder = new File(getCacheDir(), \"images\"); Uri uri = null; try { imagefolder.mkdirs(); File file = new File(imagefolder, \"shared_image.png\"); FileOutputStream outputStream = new FileOutputStream(file); bitmap.compress(Bitmap.CompressFormat.PNG, 90, outputStream); outputStream.flush(); outputStream.close(); uri = FileProvider.getUriForFile(this, \"com.anni.shareimage.fileprovider\", file); } catch (Exception e) { Toast.makeText(this, \"\" + e.getMessage(), Toast.LENGTH_LONG).show(); } return uri; }}", "e": 32706, "s": 30023, "text": null }, { "code": null, "e": 32714, "s": 32706, "text": "Output:" }, { "code": null, "e": 32722, "s": 32714, "text": "Android" }, { "code": null, "e": 32727, "s": 32722, "text": "Java" }, { "code": null, "e": 32732, "s": 32727, "text": "Java" }, { "code": null, "e": 32740, "s": 32732, "text": "Android" }, { "code": null, "e": 32838, "s": 32740, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32847, "s": 32838, "text": "Comments" }, { "code": null, "e": 32860, "s": 32847, "text": "Old Comments" }, { "code": null, "e": 32899, "s": 32860, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 32941, "s": 32899, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 32974, "s": 32941, "text": "GridView in Android with Example" }, { "code": null, "e": 33047, "s": 32974, "text": "How to Change the Background Color After Clicking the Button in Android?" }, { "code": null, "e": 33085, "s": 33047, "text": "Android Listview in Java with Example" }, { "code": null, "e": 33100, "s": 33085, "text": "Arrays in Java" }, { "code": null, "e": 33144, "s": 33100, "text": "Split() String method in Java with examples" }, { "code": null, "e": 33166, "s": 33144, "text": "For-each loop in Java" }, { "code": null, "e": 33202, "s": 33166, "text": "Arrays.sort() in Java with examples" } ]
Difference between "blank" and "_blank" target attributes in HTML - GeeksforGeeks
03 Aug, 2021 If you have ever noticed on the website that few links got opened either in a new tab or in a new window or sometimes, it might also happen that in some websites, click on the link, for the first time, it will open in a new tab & that particular open tab will update & reused every time whenever we click to the link. Both these scenarios can be possible by using the HTML target attribute. In this article, we will see how to use of target=”blank” & target=”_blank” attribute to open a hyperlink in another tab. If you don’t know, please refer to How to open a hyperlink in another window or tab in HTML?. We will discuss both attributes one-by-one. Let’s first see target=”blank”. 1. target=”blank”: if we set the target as “blank” then after clicking on a link or after submitting a form, it’s going to open a browser tab for the first time and it will be reused the same tab. The purpose of using this attribute is to keep the user engagement on your website without much effort to search & visit the offsite link every time in a separate tab. It also helps the user’s browser light to use as too many open tabs might hamper the performance of the overall browser as well as affect the system & it is also possible that the browser may get hanged up. Example: HTML <!DOCTYPE html><html> <head> <title>target="blank"</title></head> <body> <!-- It will open a new browser tab for the first time and after that it will reuse that open tab --> <p>Using target="blank"</p> <a href="https://www.geeksforgeeks.org/" target="blank"> Open GFG </a></body> </html> Output: Using target=”blank” From the above output, we can see that on click the link for the first time, it will open in the new tab & every time whenever we click on the same link, it will redirect to that particular open tab. 2. target=”_blank”: if we set the target as “_blank” then after clicking on a link or after submitting a form it’s going to open a new browser tab every time. The purpose of using this attribute is to keep the users engaged on your site for a long time that will improve most of your metrics: bounce rate, conversion, pages visited etc. Example: HTML <!DOCTYPE html><html> <head> <title>target="_blank"</title></head> <body> <!-- It will open a new browser tab every time --> <p>Using target="_blank"</p> <a href="https://www.geeksforgeeks.org/" target="_blank"> Open GFG </a></body> </html> Output: Using target=”_blank” From the above output, we can see that whenever on click the link, it is targeting the new tab for each click. To open the offsite link in a separate tab for the first time & keep on reuse the same tab whenever linked is clicked. To open the offsite link in the separate tab or window. Opens a new browser tab for the first time & after it will be reused. For this reason, the browser may work efficiently. Opens a new browser tab every time. This may affect the overall performance of the browser as well as affect the system also. Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. HTML-Attributes HTML-Questions HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments REST API (Introduction) Design a web page using HTML and CSS Angular File Upload Form validation using jQuery How to auto-resize an image to fit a div container using CSS? Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Convert a string to an integer in JavaScript How to calculate the number of days between two dates in javascript?
[ { "code": null, "e": 24919, "s": 24891, "text": "\n03 Aug, 2021" }, { "code": null, "e": 25602, "s": 24919, "text": "If you have ever noticed on the website that few links got opened either in a new tab or in a new window or sometimes, it might also happen that in some websites, click on the link, for the first time, it will open in a new tab & that particular open tab will update & reused every time whenever we click to the link. Both these scenarios can be possible by using the HTML target attribute. In this article, we will see how to use of target=”blank” & target=”_blank” attribute to open a hyperlink in another tab. If you don’t know, please refer to How to open a hyperlink in another window or tab in HTML?. We will discuss both attributes one-by-one. Let’s first see target=”blank”." }, { "code": null, "e": 26174, "s": 25602, "text": "1. target=”blank”: if we set the target as “blank” then after clicking on a link or after submitting a form, it’s going to open a browser tab for the first time and it will be reused the same tab. The purpose of using this attribute is to keep the user engagement on your website without much effort to search & visit the offsite link every time in a separate tab. It also helps the user’s browser light to use as too many open tabs might hamper the performance of the overall browser as well as affect the system & it is also possible that the browser may get hanged up." }, { "code": null, "e": 26183, "s": 26174, "text": "Example:" }, { "code": null, "e": 26188, "s": 26183, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>target=\"blank\"</title></head> <body> <!-- It will open a new browser tab for the first time and after that it will reuse that open tab --> <p>Using target=\"blank\"</p> <a href=\"https://www.geeksforgeeks.org/\" target=\"blank\"> Open GFG </a></body> </html>", "e": 26538, "s": 26188, "text": null }, { "code": null, "e": 26546, "s": 26538, "text": "Output:" }, { "code": null, "e": 26567, "s": 26546, "text": "Using target=”blank”" }, { "code": null, "e": 26767, "s": 26567, "text": "From the above output, we can see that on click the link for the first time, it will open in the new tab & every time whenever we click on the same link, it will redirect to that particular open tab." }, { "code": null, "e": 27105, "s": 26767, "text": "2. target=”_blank”: if we set the target as “_blank” then after clicking on a link or after submitting a form it’s going to open a new browser tab every time. The purpose of using this attribute is to keep the users engaged on your site for a long time that will improve most of your metrics: bounce rate, conversion, pages visited etc." }, { "code": null, "e": 27114, "s": 27105, "text": "Example:" }, { "code": null, "e": 27119, "s": 27114, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>target=\"_blank\"</title></head> <body> <!-- It will open a new browser tab every time --> <p>Using target=\"_blank\"</p> <a href=\"https://www.geeksforgeeks.org/\" target=\"_blank\"> Open GFG </a></body> </html>", "e": 27405, "s": 27119, "text": null }, { "code": null, "e": 27413, "s": 27405, "text": "Output:" }, { "code": null, "e": 27435, "s": 27413, "text": "Using target=”_blank”" }, { "code": null, "e": 27546, "s": 27435, "text": "From the above output, we can see that whenever on click the link, it is targeting the new tab for each click." }, { "code": null, "e": 27666, "s": 27546, "text": "To open the offsite link in a separate tab for the first time & keep on reuse the same tab whenever linked is clicked. " }, { "code": null, "e": 27723, "s": 27666, "text": "To open the offsite link in the separate tab or window. " }, { "code": null, "e": 27844, "s": 27723, "text": "Opens a new browser tab for the first time & after it will be reused. For this reason, the browser may work efficiently." }, { "code": null, "e": 27970, "s": 27844, "text": "Opens a new browser tab every time. This may affect the overall performance of the browser as well as affect the system also." }, { "code": null, "e": 28107, "s": 27970, "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": 28123, "s": 28107, "text": "HTML-Attributes" }, { "code": null, "e": 28138, "s": 28123, "text": "HTML-Questions" }, { "code": null, "e": 28143, "s": 28138, "text": "HTML" }, { "code": null, "e": 28160, "s": 28143, "text": "Web Technologies" }, { "code": null, "e": 28165, "s": 28160, "text": "HTML" }, { "code": null, "e": 28263, "s": 28165, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28272, "s": 28263, "text": "Comments" }, { "code": null, "e": 28285, "s": 28272, "text": "Old Comments" }, { "code": null, "e": 28309, "s": 28285, "text": "REST API (Introduction)" }, { "code": null, "e": 28346, "s": 28309, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 28366, "s": 28346, "text": "Angular File Upload" }, { "code": null, "e": 28395, "s": 28366, "text": "Form validation using jQuery" }, { "code": null, "e": 28457, "s": 28395, "text": "How to auto-resize an image to fit a div container using CSS?" }, { "code": null, "e": 28499, "s": 28457, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 28532, "s": 28499, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28575, "s": 28532, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 28620, "s": 28575, "text": "Convert a string to an integer in JavaScript" } ]
R - CSV Files
In R, we can read data from files stored outside the R environment. We can also write data into files which will be stored and accessed by the operating system. R can read and write into various file formats like csv, excel, xml etc. In this chapter we will learn to read data from a csv file and then write data into a csv file. The file should be present in current working directory so that R can read it. Of course we can also set our own directory and read files from there. You can check which directory the R workspace is pointing to using the getwd() function. You can also set a new working directory using setwd()function. # Get and print current working directory. print(getwd()) # Set current working directory. setwd("/web/com") # Get and print current working directory. print(getwd()) When we execute the above code, it produces the following result − [1] "/web/com/1441086124_2016" [1] "/web/com" This result depends on your OS and your current directory where you are working. The csv file is a text file in which the values in the columns are separated by a comma. Let's consider the following data present in the file named input.csv. You can create this file using windows notepad by copying and pasting this data. Save the file as input.csv using the save As All files(*.*) option in notepad. id,name,salary,start_date,dept 1,Rick,623.3,2012-01-01,IT 2,Dan,515.2,2013-09-23,Operations 3,Michelle,611,2014-11-15,IT 4,Ryan,729,2014-05-11,HR 5,Gary,843.25,2015-03-27,Finance 6,Nina,578,2013-05-21,IT 7,Simon,632.8,2013-07-30,Operations 8,Guru,722.5,2014-06-17,Finance Following is a simple example of read.csv() function to read a CSV file available in your current working directory − data <- read.csv("input.csv") print(data) When we execute the above code, it produces the following result − id, name, salary, start_date, dept 1 1 Rick 623.30 2012-01-01 IT 2 2 Dan 515.20 2013-09-23 Operations 3 3 Michelle 611.00 2014-11-15 IT 4 4 Ryan 729.00 2014-05-11 HR 5 NA Gary 843.25 2015-03-27 Finance 6 6 Nina 578.00 2013-05-21 IT 7 7 Simon 632.80 2013-07-30 Operations 8 8 Guru 722.50 2014-06-17 Finance By default the read.csv() function gives the output as a data frame. This can be easily checked as follows. Also we can check the number of columns and rows. data <- read.csv("input.csv") print(is.data.frame(data)) print(ncol(data)) print(nrow(data)) When we execute the above code, it produces the following result − [1] TRUE [1] 5 [1] 8 Once we read data in a data frame, we can apply all the functions applicable to data frames as explained in subsequent section. # Create a data frame. data <- read.csv("input.csv") # Get the max salary from data frame. sal <- max(data$salary) print(sal) When we execute the above code, it produces the following result − [1] 843.25 We can fetch rows meeting specific filter criteria similar to a SQL where clause. # Create a data frame. data <- read.csv("input.csv") # Get the max salary from data frame. sal <- max(data$salary) # Get the person detail having max salary. retval <- subset(data, salary == max(salary)) print(retval) When we execute the above code, it produces the following result − id name salary start_date dept 5 NA Gary 843.25 2015-03-27 Finance # Create a data frame. data <- read.csv("input.csv") retval <- subset( data, dept == "IT") print(retval) When we execute the above code, it produces the following result − id name salary start_date dept 1 1 Rick 623.3 2012-01-01 IT 3 3 Michelle 611.0 2014-11-15 IT 6 6 Nina 578.0 2013-05-21 IT # Create a data frame. data <- read.csv("input.csv") info <- subset(data, salary > 600 & dept == "IT") print(info) When we execute the above code, it produces the following result − id name salary start_date dept 1 1 Rick 623.3 2012-01-01 IT 3 3 Michelle 611.0 2014-11-15 IT # Create a data frame. data <- read.csv("input.csv") retval <- subset(data, as.Date(start_date) > as.Date("2014-01-01")) print(retval) When we execute the above code, it produces the following result − id name salary start_date dept 3 3 Michelle 611.00 2014-11-15 IT 4 4 Ryan 729.00 2014-05-11 HR 5 NA Gary 843.25 2015-03-27 Finance 8 8 Guru 722.50 2014-06-17 Finance R can create csv file form existing data frame. The write.csv() function is used to create the csv file. This file gets created in the working directory. # Create a data frame. data <- read.csv("input.csv") retval <- subset(data, as.Date(start_date) > as.Date("2014-01-01")) # Write filtered data into a new file. write.csv(retval,"output.csv") newdata <- read.csv("output.csv") print(newdata) When we execute the above code, it produces the following result − X id name salary start_date dept 1 3 3 Michelle 611.00 2014-11-15 IT 2 4 4 Ryan 729.00 2014-05-11 HR 3 5 NA Gary 843.25 2015-03-27 Finance 4 8 8 Guru 722.50 2014-06-17 Finance Here the column X comes from the data set newper. This can be dropped using additional parameters while writing the file. # Create a data frame. data <- read.csv("input.csv") retval <- subset(data, as.Date(start_date) > as.Date("2014-01-01")) # Write filtered data into a new file. write.csv(retval,"output.csv", row.names = FALSE) newdata <- read.csv("output.csv") print(newdata) When we execute the above code, it produces the following result − id name salary start_date dept 1 3 Michelle 611.00 2014-11-15 IT 2 4 Ryan 729.00 2014-05-11 HR 3 NA Gary 843.25 2015-03-27 Finance 4 8 Guru 722.50 2014-06-17 Finance 12 Lectures 2 hours Nishant Malik 10 Lectures 1.5 hours Nishant Malik 12 Lectures 2.5 hours Nishant Malik 20 Lectures 2 hours Asif Hussain 10 Lectures 1.5 hours Nishant Malik 48 Lectures 6.5 hours Asif Hussain Print Add Notes Bookmark this page
[ { "code": null, "e": 2636, "s": 2402, "text": "In R, we can read data from files stored outside the R environment. We can also write data into files which will be stored and accessed by the operating system. R can read and write into various file formats like csv, excel, xml etc." }, { "code": null, "e": 2882, "s": 2636, "text": "In this chapter we will learn to read data from a csv file and then write data into a csv file. The file should be present in current working directory so that R can read it. Of course we can also set our own directory and read files from there." }, { "code": null, "e": 3035, "s": 2882, "text": "You can check which directory the R workspace is pointing to using the getwd() function. You can also set a new working directory using setwd()function." }, { "code": null, "e": 3204, "s": 3035, "text": "# Get and print current working directory.\nprint(getwd())\n\n# Set current working directory.\nsetwd(\"/web/com\")\n\n# Get and print current working directory.\nprint(getwd())" }, { "code": null, "e": 3271, "s": 3204, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 3318, "s": 3271, "text": "[1] \"/web/com/1441086124_2016\"\n[1] \"/web/com\"\n" }, { "code": null, "e": 3399, "s": 3318, "text": "This result depends on your OS and your current directory where you are working." }, { "code": null, "e": 3559, "s": 3399, "text": "The csv file is a text file in which the values in the columns are separated by a comma. Let's consider the following data present in the file named input.csv." }, { "code": null, "e": 3719, "s": 3559, "text": "You can create this file using windows notepad by copying and pasting this data. Save the file as input.csv using the save As All files(*.*) option in notepad." }, { "code": null, "e": 3991, "s": 3719, "text": "id,name,salary,start_date,dept\n1,Rick,623.3,2012-01-01,IT\n2,Dan,515.2,2013-09-23,Operations\n3,Michelle,611,2014-11-15,IT\n4,Ryan,729,2014-05-11,HR\n5,Gary,843.25,2015-03-27,Finance\n6,Nina,578,2013-05-21,IT\n7,Simon,632.8,2013-07-30,Operations\n8,Guru,722.5,2014-06-17,Finance" }, { "code": null, "e": 4109, "s": 3991, "text": "Following is a simple example of read.csv() function to read a CSV file available in your current working directory −" }, { "code": null, "e": 4151, "s": 4109, "text": "data <- read.csv(\"input.csv\")\nprint(data)" }, { "code": null, "e": 4218, "s": 4151, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 4697, "s": 4218, "text": " id, name, salary, start_date, dept\n1 1 Rick 623.30 2012-01-01 IT\n2 2 Dan 515.20 2013-09-23 Operations\n3 3 Michelle 611.00 2014-11-15 IT\n4 4 Ryan 729.00 2014-05-11 HR\n5 NA Gary 843.25 2015-03-27 Finance\n6 6 Nina 578.00 2013-05-21 IT\n7 7 Simon 632.80 2013-07-30 Operations\n8 8 Guru 722.50 2014-06-17 Finance\n" }, { "code": null, "e": 4855, "s": 4697, "text": "By default the read.csv() function gives the output as a data frame. This can be easily checked as follows. Also we can check the number of columns and rows." }, { "code": null, "e": 4949, "s": 4855, "text": "data <- read.csv(\"input.csv\")\n\nprint(is.data.frame(data))\nprint(ncol(data))\nprint(nrow(data))" }, { "code": null, "e": 5016, "s": 4949, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 5038, "s": 5016, "text": "[1] TRUE\n[1] 5\n[1] 8\n" }, { "code": null, "e": 5166, "s": 5038, "text": "Once we read data in a data frame, we can apply all the functions applicable to data frames as explained in subsequent section." }, { "code": null, "e": 5293, "s": 5166, "text": "# Create a data frame.\ndata <- read.csv(\"input.csv\")\n\n# Get the max salary from data frame.\nsal <- max(data$salary)\nprint(sal)" }, { "code": null, "e": 5360, "s": 5293, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 5372, "s": 5360, "text": "[1] 843.25\n" }, { "code": null, "e": 5454, "s": 5372, "text": "We can fetch rows meeting specific filter criteria similar to a SQL where clause." }, { "code": null, "e": 5674, "s": 5454, "text": "# Create a data frame.\ndata <- read.csv(\"input.csv\")\n\n# Get the max salary from data frame.\nsal <- max(data$salary)\n\n# Get the person detail having max salary.\nretval <- subset(data, salary == max(salary))\nprint(retval)" }, { "code": null, "e": 5741, "s": 5674, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 5835, "s": 5741, "text": " id name salary start_date dept\n5 NA Gary 843.25 2015-03-27 Finance\n" }, { "code": null, "e": 5941, "s": 5835, "text": "# Create a data frame.\ndata <- read.csv(\"input.csv\")\n\nretval <- subset( data, dept == \"IT\")\nprint(retval)" }, { "code": null, "e": 6008, "s": 5941, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 6199, "s": 6008, "text": " id name salary start_date dept\n1 1 Rick 623.3 2012-01-01 IT\n3 3 Michelle 611.0 2014-11-15 IT\n6 6 Nina 578.0 2013-05-21 IT\n" }, { "code": null, "e": 6315, "s": 6199, "text": "# Create a data frame.\ndata <- read.csv(\"input.csv\")\n\ninfo <- subset(data, salary > 600 & dept == \"IT\")\nprint(info)" }, { "code": null, "e": 6382, "s": 6315, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 6526, "s": 6382, "text": " id name salary start_date dept\n1 1 Rick 623.3 2012-01-01 IT\n3 3 Michelle 611.0 2014-11-15 IT\n" }, { "code": null, "e": 6662, "s": 6526, "text": "# Create a data frame.\ndata <- read.csv(\"input.csv\")\n\nretval <- subset(data, as.Date(start_date) > as.Date(\"2014-01-01\"))\nprint(retval)" }, { "code": null, "e": 6729, "s": 6662, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 6977, "s": 6729, "text": " id name salary start_date dept\n3 3 Michelle 611.00 2014-11-15 IT\n4 4 Ryan 729.00 2014-05-11 HR\n5 NA Gary 843.25 2015-03-27 Finance\n8 8 Guru 722.50 2014-06-17 Finance\n" }, { "code": null, "e": 7131, "s": 6977, "text": "R can create csv file form existing data frame. The write.csv() function is used to create the csv file. This file gets created in the working directory." }, { "code": null, "e": 7372, "s": 7131, "text": "# Create a data frame.\ndata <- read.csv(\"input.csv\")\nretval <- subset(data, as.Date(start_date) > as.Date(\"2014-01-01\"))\n\n# Write filtered data into a new file.\nwrite.csv(retval,\"output.csv\")\nnewdata <- read.csv(\"output.csv\")\nprint(newdata)" }, { "code": null, "e": 7439, "s": 7372, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 7702, "s": 7439, "text": " X id name salary start_date dept\n1 3 3 Michelle 611.00 2014-11-15 IT\n2 4 4 Ryan 729.00 2014-05-11 HR\n3 5 NA Gary 843.25 2015-03-27 Finance\n4 8 8 Guru 722.50 2014-06-17 Finance\n" }, { "code": null, "e": 7824, "s": 7702, "text": "Here the column X comes from the data set newper. This can be dropped using additional parameters while writing the file." }, { "code": null, "e": 8084, "s": 7824, "text": "# Create a data frame.\ndata <- read.csv(\"input.csv\")\nretval <- subset(data, as.Date(start_date) > as.Date(\"2014-01-01\"))\n\n# Write filtered data into a new file.\nwrite.csv(retval,\"output.csv\", row.names = FALSE)\nnewdata <- read.csv(\"output.csv\")\nprint(newdata)" }, { "code": null, "e": 8151, "s": 8084, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 8404, "s": 8151, "text": " id name salary start_date dept\n1 3 Michelle 611.00 2014-11-15 IT\n2 4 Ryan 729.00 2014-05-11 HR\n3 NA Gary 843.25 2015-03-27 Finance\n4 8 Guru 722.50 2014-06-17 Finance\n" }, { "code": null, "e": 8437, "s": 8404, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 8452, "s": 8437, "text": " Nishant Malik" }, { "code": null, "e": 8487, "s": 8452, "text": "\n 10 Lectures \n 1.5 hours \n" }, { "code": null, "e": 8502, "s": 8487, "text": " Nishant Malik" }, { "code": null, "e": 8537, "s": 8502, "text": "\n 12 Lectures \n 2.5 hours \n" }, { "code": null, "e": 8552, "s": 8537, "text": " Nishant Malik" }, { "code": null, "e": 8585, "s": 8552, "text": "\n 20 Lectures \n 2 hours \n" }, { "code": null, "e": 8599, "s": 8585, "text": " Asif Hussain" }, { "code": null, "e": 8634, "s": 8599, "text": "\n 10 Lectures \n 1.5 hours \n" }, { "code": null, "e": 8649, "s": 8634, "text": " Nishant Malik" }, { "code": null, "e": 8684, "s": 8649, "text": "\n 48 Lectures \n 6.5 hours \n" }, { "code": null, "e": 8698, "s": 8684, "text": " Asif Hussain" }, { "code": null, "e": 8705, "s": 8698, "text": " Print" }, { "code": null, "e": 8716, "s": 8705, "text": " Add Notes" } ]
Groovy - pop()
Removes the last item from this List. Object pop() None The popped value from the list. Following is an example of the usage of this method − class Example { static void main(String[] args) { def lst = [11, 12, 13, 14]; println(lst.pop()); println(lst); } } When we run the above program, we will get the following result − 14 [11, 12, 13] 52 Lectures 8 hours Krishna Sakinala 49 Lectures 2.5 hours Packt Publishing Print Add Notes Bookmark this page
[ { "code": null, "e": 2276, "s": 2238, "text": "Removes the last item from this List." }, { "code": null, "e": 2291, "s": 2276, "text": "Object pop() \n" }, { "code": null, "e": 2296, "s": 2291, "text": "None" }, { "code": null, "e": 2328, "s": 2296, "text": "The popped value from the list." }, { "code": null, "e": 2382, "s": 2328, "text": "Following is an example of the usage of this method −" }, { "code": null, "e": 2529, "s": 2382, "text": "class Example { \n static void main(String[] args) { \n def lst = [11, 12, 13, 14]; \n\n println(lst.pop()); \n println(lst); \n } \n}" }, { "code": null, "e": 2595, "s": 2529, "text": "When we run the above program, we will get the following result −" }, { "code": null, "e": 2613, "s": 2595, "text": "14 \n[11, 12, 13]\n" }, { "code": null, "e": 2646, "s": 2613, "text": "\n 52 Lectures \n 8 hours \n" }, { "code": null, "e": 2664, "s": 2646, "text": " Krishna Sakinala" }, { "code": null, "e": 2699, "s": 2664, "text": "\n 49 Lectures \n 2.5 hours \n" }, { "code": null, "e": 2717, "s": 2699, "text": " Packt Publishing" }, { "code": null, "e": 2724, "s": 2717, "text": " Print" }, { "code": null, "e": 2735, "s": 2724, "text": " Add Notes" } ]
Create your Professional/Educational resume using LaTeX | by Ridham Dave | Towards Data Science
A resume can be considered your first impression in front of your employer. A resume is the most suitable means of announcing your claim that you are the perfect choice for the position to your prospects employer. In this tutorial, I would like to demonstrate the use of the LaTeX environment to create a well organized and professional resume for your future endeavors. The primary motive behind a compelling resume is to showcase your essential assets like your Qualifications, Experience, Achievements, Capabilities, and Qualities. Based on the typical mentality of hiring managers(employers), it has been observed that the employer takes just a few seconds to decide whether to call the person for the interview or not. As commonly experienced in the corporate world, the scenario, of a person with the necessary skills and appropriate experience not getting the interview call, is observed frequently. This is because the person applying for the job has failed to advertise himself clearly in the resume. Hence, to prepare a compelling resume, a certain standard should be followed in the professional ecosystem. Following a predefined rule does not imply that a specific format should be followed in each application/resume. Each resume can be different from the another based on the applicant’s way of representing himself/herself, to the employer. A resume is a way of portraying a professional/educational profile effectively to compel the scrutineer. Using a general-purpose text editor like Microsoft Word or Google Docs can serve the preliminary purpose of maintaining draft copies of your resume. These editors maintain the “what you see is what you get” approach to format the work. However, it takes plenty of unnecessary efforts to follow a particular formatting/editing standard throughout the resume using such an editor. Due to such issues, it motivates me to introduce the LaTeX environment to the reader. LaTeX is a document preparation system used by academic and research communities for the publication of their work. Specifically, the writer uses markup tagging conventions to stylize text throughout a document, add citations and cross-references, and to define the structure of the document. LaTeX uses a TeX distribution such as TeX Live or MikTeX to produce an output file (PDF) suitable for printing or digital distribution. Preparing a resume in LaTeX can decrease the overall complexity required for formatting the document; hence, it is utmost necessary for every professional to know the basic LaTeX syntax for resume building. In this tutorial, I would cover several aspects for creating a powerful and effective resume which would cover mostly each element of an application. To begin with, each LaTeX file can contain a specific Style Class file commonly know as .cls which defines all the styling rules for the documents. This class file function similar to the CSS files in web designing. Multiple class files are readily available on the web for resume building, out of which I prefer the file provided by Trey Hunner for styling. This file is a simple yet effective way to represent your self. Download the class file from the link provided below: ridhamdave/resume-latex/blob/master/resume.cls Each LaTeX file start and ends as a “document” object. For demonstration: \documentclass{resume} % The style class\begin{document}...\end{document} Let’s start creating the resume, where the first task is to provide the personal details on top of the page, which is also known as the Address section. This section will be present on top of the document containing detailed information regarding your name, address, phone number, and e-mail address. Here the provided class file defines certain tags(markups) for the title and other contact information. Add this line before the document beginning to reflect the introduction section. \name{John Snow} % Your name\address{North of the Wall, Outside the reach of every kingdom} \address{(+0)9999999999 \\ [email protected]} The next section is the most important for every fresher coming out of a college, i.e., the educational background. This section must cover the degree perused, educational institute, its affiliated university, and the overall CGPA/marks. This class file provides a predefined “rSection” tag for differentiating each section of your resume. The curly braces for the part contain the section’s name, and the entries between the \begin and \end represent actual content required. Here, \bf represents Bold, while \em represents italics and \hfill command is used to provide appropriate formatting space between the right and side of the page. The Education section is as provided below, which is entered inside the actual document: \begin{rSection}{Education}{\bf Massachusetts Institute of Technology, Cambridge} \hfill {\em July 2016 - May 2020} \\ Bachelor of Engineering, Computer.\hfill { Overall CGPA: 9.05 }\end{rSection} The next section can be considered as a primary career goal professionally as well as personally. This section can be defined as “Career Objective” which is presented below: \begin{rSection}{Career Objective} To work for an organization which provides me the opportunity to improve my skills and knowledge to grow along with the organization objective.\end{rSection} From an academic perspective, projects play a crucial role in learning practical skills. Hence I consider placing “Projects” section in this position of the document. This is an aspect which can be tinkered as personal preferences go. For this section, general convention goes as the project’s name is provided in Bold styling, while the summary is presented from the next line in normal texts as described below. Here double slash(\\) represents new line. I have repeated the same project twice to demonstrate the exact spacing between projects. \begin{rSection}{Projects}{\bf GitHub Notifier}\\This project aims at providing real time information of events from GitHub and notify you accordingly. The project is in ready-to-deployment stage on a demo server as a cron-job. The notification engine used for real time tracking is completely based on the python implementation assembled in an Android App with firebase cloud support.{\bf GitHub Notifier}\\This project aims at providing real time information of events from GitHub and notify you accordingly. The project is in ready-to-deployment stage on a demo server as a cron-job. The notification engine used for real time tracking is completely based on the python implementation assembled in an Android App with firebase cloud support.\end{rSection} The next step in the resume is to demonstrate the skills and technical strengths you possess shortly and straightforwardly. Hence, a borderless table is mostly preferred for such visual aesthetics. A tabular section is used for creating table as shown below. An “&” operator is used for diversification of each column, and a “\\” operator is used for new line attachment. \begin{rSection}{Technical Strengths}\begin{tabular}{ @{} >{\bfseries}l @{\hspace{6ex}} l }Languages \ & C, C++, Python, Java, C\# \\Technologies & MVC, HTML5, CSS, Latex\\Tools & MikTex, Kile, Netbeans \\Databases & MySql, Oracle, Sqlite, NoSql\\Cloud Technologies & Firebase, AWS, Google Cloud\\Version Control & Github\end{tabular}\end{rSection} The next section is considered as one of the most import aspects of your profile, which is the “Work Experience” section. This section needs to describe in brief the contribution you presented to the company in which you previously worked. In the case of an internship, the person should mention the same and accordingly summarize the role in the company. The class file provides a “rSubsection” template for such entries which can require multiple tags to represent the employee designation, company’s name, work duration, etc.. A section would contain a subsection for each entry of work profiling as shown below. Here each summary point is declared with a \item tag for equal spacing and design. \begin{rSection}{Work Experience}\begin{rSubsection}{Reversible Alphabet Pvt. Ltd., India}{Jun 2017 - Dec 2018}{Data Scientist}{} \item Created classification models for e-commerce websites using neural networks. \item Achieved exposure towards classification optimaization techniques for further specialization. \item Worked under an experenced Data Scientist and got deep insights related to optimization algorithms.\end{rSubsection}\begin{rSubsection}{Irreversible Alphabet Pvt. Ltd., India}{Jun 2016 - Dec 2016}{Data Scientist}{} \item Created classification models for e-commerce websites using neural networks. \item Achieved exposure towards classification optimaization techniques for further specialization. \item Worked under an experenced Data Scientist and got deep insights related to optimization algorithms.\end{rSubsection}\end{rSection} Similarly, the sections as academic achievements, Extracurricular Activities, and Research Profile can be added in the following manner. Each section can be added just as given below as an example: \begin{rSection}{Academic Achievements} \item Project 'XYZ' won Best Project under Environmental Solver category under AICTE, Government of India\item Recieved Scholarship For Higher Education(She) Component Under Inspire Scheme worth INR 4,00,000\item Achived A Grade in Diploma in Computer Science from IBM\item Won First Prize in Zonal technical quiz Competition Organized by IIT, Mumbai.\item Project 'XYZ' won Best Project under Environmental Solver category under AICTE, Government of India\item Recieved Scholarship For Higher Education(She) Component Under Inspire Scheme worth INR 4,00,000\item Achived A Grade in Diploma in Computer Science from IBM\item Won First Prize in Zonal technical quiz Competition Organized by IIT, Mumbai.\end{rSection} \begin{rSection}{Extra-Cirrucular} \item Attended a workshop on Machine Learning and artificial intelligence from faculties of IIT Roorkee in 2019 and won zonal round for the challenge presented.\item Member of the Institute of Engineers since 2017.\item Completed Basic Leadership Training under Project NSS, Gujarat\item Attended a workshop on Machine Learning and artificial intelligence from faculties of IIT Roorkee in 2019 and won zonal round for the challenge presented.\item Member of the Institute of Engineers since 2017.\item Completed Basic Leadership Training under Project NSS, Gujarat\item Attended a workshop on Machine Learning and artificial intelligence from faculties of IIT Roorkee in 2019 and won zonal round for the challenge presented.\item Member of the Institute of Engineers since 2017.\item Completed Basic Leadership Training under Project NSS, Gujarat\end{rSection} Similarly, the research section needs to be on the presented with the papers adequately documented and cited, for example(With Journal/conference name): \begin{rSection}{Research Profile} \item Student President, Technology and Research, IIT Gandhinagar \item Publication : ABC, IOT IEEE Transactions (Impact Factor: 9.3, Status: Published) \item Student President, Technology and Research, IIT Gandhinagar \item Publication : ABC, IOT IEEE Transactions (Impact Factor: 9.3, Status: Published) \item Student President, Technology and Research, IIT Gandhinagar \item Publication : ABC, IOT IEEE Transactions (Impact Factor: 9.3, Status: Published)\end{rSection} Finally, after the addition of all the aspects of the profile, final proofreading of the document is required and a final draft needs to be prepared. It should be a general practice to let some colleague rectify the mistakes or ambiguities if any. Resume building is an iterative task, which required constant tuning and twerking, which can only be achieved by adequate efforts. All the LaTeX code for the resume is provided in the GitHub link below. https://github.com/ridhamdave/resume-latex/blob/master/resume.tex The final PDF can be seen as follows: To conclude, you now have a great resume in your hand, which needs to be updated regularly in order to make it better. Just two words should always be kept in mind for resume building which are: Precise and Concise Hope you learned new techniques for efficient resume construction and are more familiar with the LaTeX environment for such professional tasks. Thank you for your attention. Also follow me on LinkedIn for networking.
[ { "code": null, "e": 543, "s": 172, "text": "A resume can be considered your first impression in front of your employer. A resume is the most suitable means of announcing your claim that you are the perfect choice for the position to your prospects employer. In this tutorial, I would like to demonstrate the use of the LaTeX environment to create a well organized and professional resume for your future endeavors." }, { "code": null, "e": 1182, "s": 543, "text": "The primary motive behind a compelling resume is to showcase your essential assets like your Qualifications, Experience, Achievements, Capabilities, and Qualities. Based on the typical mentality of hiring managers(employers), it has been observed that the employer takes just a few seconds to decide whether to call the person for the interview or not. As commonly experienced in the corporate world, the scenario, of a person with the necessary skills and appropriate experience not getting the interview call, is observed frequently. This is because the person applying for the job has failed to advertise himself clearly in the resume." }, { "code": null, "e": 1633, "s": 1182, "text": "Hence, to prepare a compelling resume, a certain standard should be followed in the professional ecosystem. Following a predefined rule does not imply that a specific format should be followed in each application/resume. Each resume can be different from the another based on the applicant’s way of representing himself/herself, to the employer. A resume is a way of portraying a professional/educational profile effectively to compel the scrutineer." }, { "code": null, "e": 2527, "s": 1633, "text": "Using a general-purpose text editor like Microsoft Word or Google Docs can serve the preliminary purpose of maintaining draft copies of your resume. These editors maintain the “what you see is what you get” approach to format the work. However, it takes plenty of unnecessary efforts to follow a particular formatting/editing standard throughout the resume using such an editor. Due to such issues, it motivates me to introduce the LaTeX environment to the reader. LaTeX is a document preparation system used by academic and research communities for the publication of their work. Specifically, the writer uses markup tagging conventions to stylize text throughout a document, add citations and cross-references, and to define the structure of the document. LaTeX uses a TeX distribution such as TeX Live or MikTeX to produce an output file (PDF) suitable for printing or digital distribution." }, { "code": null, "e": 2884, "s": 2527, "text": "Preparing a resume in LaTeX can decrease the overall complexity required for formatting the document; hence, it is utmost necessary for every professional to know the basic LaTeX syntax for resume building. In this tutorial, I would cover several aspects for creating a powerful and effective resume which would cover mostly each element of an application." }, { "code": null, "e": 3361, "s": 2884, "text": "To begin with, each LaTeX file can contain a specific Style Class file commonly know as .cls which defines all the styling rules for the documents. This class file function similar to the CSS files in web designing. Multiple class files are readily available on the web for resume building, out of which I prefer the file provided by Trey Hunner for styling. This file is a simple yet effective way to represent your self. Download the class file from the link provided below:" }, { "code": null, "e": 3408, "s": 3361, "text": "ridhamdave/resume-latex/blob/master/resume.cls" }, { "code": null, "e": 3482, "s": 3408, "text": "Each LaTeX file start and ends as a “document” object. For demonstration:" }, { "code": null, "e": 3556, "s": 3482, "text": "\\documentclass{resume} % The style class\\begin{document}...\\end{document}" }, { "code": null, "e": 4042, "s": 3556, "text": "Let’s start creating the resume, where the first task is to provide the personal details on top of the page, which is also known as the Address section. This section will be present on top of the document containing detailed information regarding your name, address, phone number, and e-mail address. Here the provided class file defines certain tags(markups) for the title and other contact information. Add this line before the document beginning to reflect the introduction section." }, { "code": null, "e": 4185, "s": 4042, "text": "\\name{John Snow} % Your name\\address{North of the Wall, Outside the reach of every kingdom} \\address{(+0)9999999999 \\\\ [email protected]}" }, { "code": null, "e": 4662, "s": 4185, "text": "The next section is the most important for every fresher coming out of a college, i.e., the educational background. This section must cover the degree perused, educational institute, its affiliated university, and the overall CGPA/marks. This class file provides a predefined “rSection” tag for differentiating each section of your resume. The curly braces for the part contain the section’s name, and the entries between the \\begin and \\end represent actual content required." }, { "code": null, "e": 4914, "s": 4662, "text": "Here, \\bf represents Bold, while \\em represents italics and \\hfill command is used to provide appropriate formatting space between the right and side of the page. The Education section is as provided below, which is entered inside the actual document:" }, { "code": null, "e": 5111, "s": 4914, "text": "\\begin{rSection}{Education}{\\bf Massachusetts Institute of Technology, Cambridge} \\hfill {\\em July 2016 - May 2020} \\\\ Bachelor of Engineering, Computer.\\hfill { Overall CGPA: 9.05 }\\end{rSection}" }, { "code": null, "e": 5285, "s": 5111, "text": "The next section can be considered as a primary career goal professionally as well as personally. This section can be defined as “Career Objective” which is presented below:" }, { "code": null, "e": 5478, "s": 5285, "text": "\\begin{rSection}{Career Objective} To work for an organization which provides me the opportunity to improve my skills and knowledge to grow along with the organization objective.\\end{rSection}" }, { "code": null, "e": 6025, "s": 5478, "text": "From an academic perspective, projects play a crucial role in learning practical skills. Hence I consider placing “Projects” section in this position of the document. This is an aspect which can be tinkered as personal preferences go. For this section, general convention goes as the project’s name is provided in Bold styling, while the summary is presented from the next line in normal texts as described below. Here double slash(\\\\) represents new line. I have repeated the same project twice to demonstrate the exact spacing between projects." }, { "code": null, "e": 6786, "s": 6025, "text": "\\begin{rSection}{Projects}{\\bf GitHub Notifier}\\\\This project aims at providing real time information of events from GitHub and notify you accordingly. The project is in ready-to-deployment stage on a demo server as a cron-job. The notification engine used for real time tracking is completely based on the python implementation assembled in an Android App with firebase cloud support.{\\bf GitHub Notifier}\\\\This project aims at providing real time information of events from GitHub and notify you accordingly. The project is in ready-to-deployment stage on a demo server as a cron-job. The notification engine used for real time tracking is completely based on the python implementation assembled in an Android App with firebase cloud support.\\end{rSection}" }, { "code": null, "e": 7158, "s": 6786, "text": "The next step in the resume is to demonstrate the skills and technical strengths you possess shortly and straightforwardly. Hence, a borderless table is mostly preferred for such visual aesthetics. A tabular section is used for creating table as shown below. An “&” operator is used for diversification of each column, and a “\\\\” operator is used for new line attachment." }, { "code": null, "e": 7508, "s": 7158, "text": "\\begin{rSection}{Technical Strengths}\\begin{tabular}{ @{} >{\\bfseries}l @{\\hspace{6ex}} l }Languages \\ & C, C++, Python, Java, C\\# \\\\Technologies & MVC, HTML5, CSS, Latex\\\\Tools & MikTex, Kile, Netbeans \\\\Databases & MySql, Oracle, Sqlite, NoSql\\\\Cloud Technologies & Firebase, AWS, Google Cloud\\\\Version Control & Github\\end{tabular}\\end{rSection}" }, { "code": null, "e": 8207, "s": 7508, "text": "The next section is considered as one of the most import aspects of your profile, which is the “Work Experience” section. This section needs to describe in brief the contribution you presented to the company in which you previously worked. In the case of an internship, the person should mention the same and accordingly summarize the role in the company. The class file provides a “rSubsection” template for such entries which can require multiple tags to represent the employee designation, company’s name, work duration, etc.. A section would contain a subsection for each entry of work profiling as shown below. Here each summary point is declared with a \\item tag for equal spacing and design." }, { "code": null, "e": 9061, "s": 8207, "text": "\\begin{rSection}{Work Experience}\\begin{rSubsection}{Reversible Alphabet Pvt. Ltd., India}{Jun 2017 - Dec 2018}{Data Scientist}{} \\item Created classification models for e-commerce websites using neural networks. \\item Achieved exposure towards classification optimaization techniques for further specialization. \\item Worked under an experenced Data Scientist and got deep insights related to optimization algorithms.\\end{rSubsection}\\begin{rSubsection}{Irreversible Alphabet Pvt. Ltd., India}{Jun 2016 - Dec 2016}{Data Scientist}{} \\item Created classification models for e-commerce websites using neural networks. \\item Achieved exposure towards classification optimaization techniques for further specialization. \\item Worked under an experenced Data Scientist and got deep insights related to optimization algorithms.\\end{rSubsection}\\end{rSection}" }, { "code": null, "e": 9259, "s": 9061, "text": "Similarly, the sections as academic achievements, Extracurricular Activities, and Research Profile can be added in the following manner. Each section can be added just as given below as an example:" }, { "code": null, "e": 10016, "s": 9259, "text": "\\begin{rSection}{Academic Achievements} \\item Project 'XYZ' won Best Project under Environmental Solver category under AICTE, Government of India\\item Recieved Scholarship For Higher Education(She) Component Under Inspire Scheme worth INR 4,00,000\\item Achived A Grade in Diploma in Computer Science from IBM\\item Won First Prize in Zonal technical quiz Competition Organized by IIT, Mumbai.\\item Project 'XYZ' won Best Project under Environmental Solver category under AICTE, Government of India\\item Recieved Scholarship For Higher Education(She) Component Under Inspire Scheme worth INR 4,00,000\\item Achived A Grade in Diploma in Computer Science from IBM\\item Won First Prize in Zonal technical quiz Competition Organized by IIT, Mumbai.\\end{rSection}" }, { "code": null, "e": 10915, "s": 10016, "text": "\\begin{rSection}{Extra-Cirrucular} \\item Attended a workshop on Machine Learning and artificial intelligence from faculties of IIT Roorkee in 2019 and won zonal round for the challenge presented.\\item Member of the Institute of Engineers since 2017.\\item Completed Basic Leadership Training under Project NSS, Gujarat\\item Attended a workshop on Machine Learning and artificial intelligence from faculties of IIT Roorkee in 2019 and won zonal round for the challenge presented.\\item Member of the Institute of Engineers since 2017.\\item Completed Basic Leadership Training under Project NSS, Gujarat\\item Attended a workshop on Machine Learning and artificial intelligence from faculties of IIT Roorkee in 2019 and won zonal round for the challenge presented.\\item Member of the Institute of Engineers since 2017.\\item Completed Basic Leadership Training under Project NSS, Gujarat\\end{rSection}" }, { "code": null, "e": 11068, "s": 10915, "text": "Similarly, the research section needs to be on the presented with the papers adequately documented and cited, for example(With Journal/conference name):" }, { "code": null, "e": 11576, "s": 11068, "text": "\\begin{rSection}{Research Profile} \\item Student President, Technology and Research, IIT Gandhinagar \\item Publication : ABC, IOT IEEE Transactions (Impact Factor: 9.3, Status: Published) \\item Student President, Technology and Research, IIT Gandhinagar \\item Publication : ABC, IOT IEEE Transactions (Impact Factor: 9.3, Status: Published) \\item Student President, Technology and Research, IIT Gandhinagar \\item Publication : ABC, IOT IEEE Transactions (Impact Factor: 9.3, Status: Published)\\end{rSection}" }, { "code": null, "e": 12027, "s": 11576, "text": "Finally, after the addition of all the aspects of the profile, final proofreading of the document is required and a final draft needs to be prepared. It should be a general practice to let some colleague rectify the mistakes or ambiguities if any. Resume building is an iterative task, which required constant tuning and twerking, which can only be achieved by adequate efforts. All the LaTeX code for the resume is provided in the GitHub link below." }, { "code": null, "e": 12093, "s": 12027, "text": "https://github.com/ridhamdave/resume-latex/blob/master/resume.tex" }, { "code": null, "e": 12131, "s": 12093, "text": "The final PDF can be seen as follows:" }, { "code": null, "e": 12326, "s": 12131, "text": "To conclude, you now have a great resume in your hand, which needs to be updated regularly in order to make it better. Just two words should always be kept in mind for resume building which are:" }, { "code": null, "e": 12346, "s": 12326, "text": "Precise and Concise" }, { "code": null, "e": 12490, "s": 12346, "text": "Hope you learned new techniques for efficient resume construction and are more familiar with the LaTeX environment for such professional tasks." }, { "code": null, "e": 12520, "s": 12490, "text": "Thank you for your attention." } ]
GATE | GATE-CS-2009 | Question 33 - GeeksforGeeks
28 Jun, 2021 The enter_CS() and leave_CS() functions to implement critical section of a process are realized using test-and-set instruction as follows: void enter_CS(X) { while test-and-set(X) ; } void leave_CS(X) { X = 0; } In the above solution, X is a memory location associated with the CS and is initialized to 0. Now consider the following statements:I. The above solution to CS problem is deadlock-freeII. The solution is starvation free.III. The processes enter CS in FIFO order.IV More than one process can enter CS at the same time. Which of the above statements is TRUE? (A) I only(B) I and II(C) II and III(D) IV onlyAnswer: (A)Explanation: The above solution is a simple test-and-set solution that makes sure that deadlock doesn’t occur, but it doesn’t use any queue to avoid starvation or to have FIFO order.Quiz of this Question GATE-CS-2009 GATE-GATE-CS-2009 GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments GATE | GATE-IT-2004 | Question 71 GATE | GATE CS 2011 | Question 7 GATE | GATE-CS-2015 (Set 3) | Question 65 GATE | GATE-CS-2016 (Set 2) | Question 48 GATE | GATE-CS-2014-(Set-3) | Question 38 GATE | GATE CS 2018 | Question 37 GATE | GATE-CS-2016 (Set 1) | Question 65 GATE | GATE-IT-2004 | Question 83 GATE | GATE-CS-2016 (Set 1) | Question 63 GATE | GATE-CS-2014-(Set-2) | Question 65
[ { "code": null, "e": 24570, "s": 24542, "text": "\n28 Jun, 2021" }, { "code": null, "e": 24709, "s": 24570, "text": "The enter_CS() and leave_CS() functions to implement critical section of a process are realized using test-and-set instruction as follows:" }, { "code": null, "e": 24789, "s": 24709, "text": "void enter_CS(X)\n{\n while test-and-set(X) ;\n}\nvoid leave_CS(X)\n{\n X = 0;\n}" }, { "code": null, "e": 25107, "s": 24789, "text": "In the above solution, X is a memory location associated with the CS and is initialized to 0. Now consider the following statements:I. The above solution to CS problem is deadlock-freeII. The solution is starvation free.III. The processes enter CS in FIFO order.IV More than one process can enter CS at the same time." }, { "code": null, "e": 25146, "s": 25107, "text": "Which of the above statements is TRUE?" }, { "code": null, "e": 25408, "s": 25146, "text": "(A) I only(B) I and II(C) II and III(D) IV onlyAnswer: (A)Explanation: The above solution is a simple test-and-set solution that makes sure that deadlock doesn’t occur, but it doesn’t use any queue to avoid starvation or to have FIFO order.Quiz of this Question" }, { "code": null, "e": 25421, "s": 25408, "text": "GATE-CS-2009" }, { "code": null, "e": 25439, "s": 25421, "text": "GATE-GATE-CS-2009" }, { "code": null, "e": 25444, "s": 25439, "text": "GATE" }, { "code": null, "e": 25542, "s": 25444, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25551, "s": 25542, "text": "Comments" }, { "code": null, "e": 25564, "s": 25551, "text": "Old Comments" }, { "code": null, "e": 25598, "s": 25564, "text": "GATE | GATE-IT-2004 | Question 71" }, { "code": null, "e": 25631, "s": 25598, "text": "GATE | GATE CS 2011 | Question 7" }, { "code": null, "e": 25673, "s": 25631, "text": "GATE | GATE-CS-2015 (Set 3) | Question 65" }, { "code": null, "e": 25715, "s": 25673, "text": "GATE | GATE-CS-2016 (Set 2) | Question 48" }, { "code": null, "e": 25757, "s": 25715, "text": "GATE | GATE-CS-2014-(Set-3) | Question 38" }, { "code": null, "e": 25791, "s": 25757, "text": "GATE | GATE CS 2018 | Question 37" }, { "code": null, "e": 25833, "s": 25791, "text": "GATE | GATE-CS-2016 (Set 1) | Question 65" }, { "code": null, "e": 25867, "s": 25833, "text": "GATE | GATE-IT-2004 | Question 83" }, { "code": null, "e": 25909, "s": 25867, "text": "GATE | GATE-CS-2016 (Set 1) | Question 63" } ]
Polymer - Custom Elements
Polymer is a framework that allows creating custom elements using standard HTML elements. Custom web elements provide the following features − It provides custom element name with associating class. It provides custom element name with associating class. When you change the state of custom element instance, it will request the lifecycle callbacks. When you change the state of custom element instance, it will request the lifecycle callbacks. If you change the attributes on an instance, then callback will be requested. If you change the attributes on an instance, then callback will be requested. You can define the custom element using ES6 class and class can be associated with the custom element as shown in the following code. //ElementDemo class is extending the HTMLElement class ElementDemo extends HTMLElement { // code here }; //link the new class with an element name window.customElements.define('element-demo', ElementDemo); The custom element can be used as a standard element as shown below − <element-demo></element-demo> Note − Custom element name should start with a lower case letter and contain a dash between the names. Custom element lifecycle provides a set of custom element reactions which are responsible for change in element lifecycle and are defined in the following table. constructor When you create an element or define the previously-created element, this element reaction will be called. connectedCallback When you add an element to a document, this element reaction will be called. disconnectedCallback When you remove an element from a document, this element reaction will be called. attributeChangedCallback Whenever you change, append, remove, or replace an element from a document, this element reaction will be called. We can use custom elements before defining them by specification and any existing instances of an element will be upgraded to the custom class by adding a definition to that element. The custom element state contains the following values − uncustomized − The valid custom element name is either a built-in element or an unknown element, which cannot become a custom element. uncustomized − The valid custom element name is either a built-in element or an unknown element, which cannot become a custom element. undefined − The element can have a valid custom element name, but it cannot be defined. undefined − The element can have a valid custom element name, but it cannot be defined. custom − The element can have a valid custom element name, which can be defined and upgraded. custom − The element can have a valid custom element name, which can be defined and upgraded. failed − Trying to upgrade the failed element of an invalid class. failed − Trying to upgrade the failed element of an invalid class. A custom element can be defined by creating a class which extends Polymer.Element and it passes the class to customElements.define method. The class contains is getter method that returns a HTML tag name of the custom element. For instance − //ElementDemo class is extending the Polymer.Element class ElementDemo extends Polymer.Element { static get is() { return 'element-demo'; } static get properties() { . . . . . . } constructor(){ super(); . . . . . . } . . . . . . } //Associate the new class with an element name window.customElements.define(ElementDemo.is, ElementDemo); // create an instance with createElement var el1 = document.createElement('element-demo'); The Polymer elements can be defined by specifying the following three HTML imports − polymer-element.html − It specifies the Polymer.Element base class. polymer-element.html − It specifies the Polymer.Element base class. legacy-element.html − It extends Polymer.Element using Polymer.LegacyElement base class and adds 1.x compatible legacy API. It also creates hybrid elements by defining the legacy Polymer() factory method. legacy-element.html − It extends Polymer.Element using Polymer.LegacyElement base class and adds 1.x compatible legacy API. It also creates hybrid elements by defining the legacy Polymer() factory method. polymer.html − It comprises the Polymer base classes along with helper elements, which were included in the 1.x polymer.html. polymer.html − It comprises the Polymer base classes along with helper elements, which were included in the 1.x polymer.html. You can define an element in the main HTML document using HTMLImports.whenReady() function. The following example shows how to define an element in the main HTML document. Create an index.html file and add the following code. <!doctype html> <html lang = "en"> <head> <title>Polymer Example</title> <script src = "bower_components/webcomponentsjs/webcomponents-lite.js"></script> <link rel = "import" href = "bower_components/polymer/polymer.html"> <link rel = "import" href = "define-element.html"> </head> <body> <define-element></define-element> </body> </html> Now create a custom element called define-element.html and include the following code. <dom-module id = "define-element"> <template> <h2>Welcome to Tutorialspoint!!!</h2> </template> <script> HTMLImports.whenReady(function(){ Polymer ({ is: "define-element" }) }) </script> </dom-module> To run the application, navigate to the created project directory and run the following command. polymer serve Now open the browser and navigate to http://127.0.0.1:8081/. Following will be the output. Legacy element can be used to register an element using the Polymer function, which takes the prototype for a new element. The prototype should contain is which defines the HTML tag name for a custom element. //registering an element ElementDemo = Polymer ({ is: 'element-demo', //it is a legecy callback, called when the element has been created created: function() { this.textContent = 'Hello World!!!'; } }); //'createElement' is used to create an instance var myelement1 = document.createElement('element-demo'); //use the constructor create an instance var myelement2 = new ElementDemo(); Lifecycle callbacks are used to accomplish the tasks for built-in features of Polymer.Element class. Polymer uses ready callback, which will be invoked when Polymer completes creating and initializing DOM elements. Following is a list of legacy callbacks in Polymer.js. created − It is called when you create an element before setting the property values and initializing local DOM. created − It is called when you create an element before setting the property values and initializing local DOM. ready − It is called when you create an element after setting the property values and initializing local DOM. ready − It is called when you create an element after setting the property values and initializing local DOM. attached − It is called after attaching the element to the document and can be called more than one time throughout the lifetime of an element. attached − It is called after attaching the element to the document and can be called more than one time throughout the lifetime of an element. detached − It is called after detaching the element from the document and can be called more than once throughout the lifetime of an element. detached − It is called after detaching the element from the document and can be called more than once throughout the lifetime of an element. attributeChanged − It is called when there are changes in an element's attributes and it holds the attribute changes, which are not compatible with the declared properties. attributeChanged − It is called when there are changes in an element's attributes and it holds the attribute changes, which are not compatible with the declared properties. The properties can be declared on an element to add default value and other specific features in the data system and they can be used to specify the following features − It specifies the property type and default value. It specifies the property type and default value. It calls the observer method, when there are changes in the property value. It calls the observer method, when there are changes in the property value. It specifies the read-only status to stop the unexpected changes to the property value. It specifies the read-only status to stop the unexpected changes to the property value. It provides support for two-way data binding, which triggers an event when you change the property values. It provides support for two-way data binding, which triggers an event when you change the property values. It is a computed property, which calculates a value dynamically depending on the other properties. It is a computed property, which calculates a value dynamically depending on the other properties. It updates and reflects the corresponding attribute value, when you change the property values. It updates and reflects the corresponding attribute value, when you change the property values. The following table shows keys for each property, which are supported by the properties object. type It deserializes from an attribute whose property type is determined using the type's constructor. value It specifies the default value for the property and if it is a function, then it uses the return value as the default value of the property. reflectToAttribute If this key sets to true, then it sets the corresponding attribute on the host node. The attribute can be created as a standard HTML boolean attribute, if you set the property value as Boolean. readOnly You cannot set the property directly by assignment or data binding, if this key is set to true. notify You can use the property for two-way data binding, if this key is set to true and when you change the property, property-name-changed event will get triggered. computed You can calculate the value of an argument whenever it changes, by invoking the method and value will be simplified as method name and argument list. observer Invoke the method name, which is simplified by a value, when the property value changes. Deserialize the property name that matches an attribute on instance according to the type specified and the same property name on the element instance, if the property is configured in the properties object. You can set the specified type directly as the value of the property, if there are no other properties options defined in the properties object; otherwise, it will provide the value to the type key in the properties configuration object. The Boolean property can be configured from markup, by setting it to false and if it is set to true, then you cannot configure from markup because the attribute with or without a value is equalized to true. Therefore, it is known as a standard behavior for attributes in the web platform. The object and array properties can be configured by passing them in JSON format as − <element-demo player = '{ "name": "Sachin", "country": "India" }'></element-demo> The default property can be configured using the value field in the properties object and it may be either primitive value, or a function which returns a value. The following example depicts how to configure the default property values in properties object. <link rel = "import" href = "../../bower_components/polymer/polymer-element.html"> //it specifies the start of an element's local DOM <dom-module id="polymer-app"> <template> <style> :host { color:#33ACC9; } </style> <h2>Hello...[[myval]]!</h2> </template> <script> //cusom element extending the Polymer.Element class class PolymerApp extends Polymer.Element { static get is() { return 'polymer-app'; } static get properties() { return { myval: { type: String, //displaying this value on screen value: 'Welcome to Tutorialspoint;!!!' }, data: { type: Object, notify: true, value: function() { return {}; } } } } } window.customElements.define(PolymerApp.is, PolymerApp); </script> </dom-module> Run the application as shown in the previous example, and navigate to http://127.0.0.1:8000/. Following will be the output. You can avoid unexpected changes on produced data by setting the readOnly flag to true, in the properties object. Element uses the setter of the convention _setProperty(value), in order to change the property value. Following example depicts the use of read-only properties in the properties object. Create an index.html file and add the following code in it <!doctype html> <html> <head> <title>Polymer Example</title> <script src = "bower_components/webcomponentsjs/webcomponents-lite.js"></script> <link rel = "import" href = "bower_components/polymer/polymer.html"> <link rel = "import" href = "my-element.html"> </head> <body> <my-element></my-element> </body> </html> Now, create another file called my-element.html and include the following code. <link rel = "import" href = "bower_components/polymer/polymer-element.html"> <link rel = "import" href = "prop-element.html"> //it specifies the start of an element's local DOM <dom-module id = "my-element"> <template> <prop-element my-prop = "{{demoProp}}"></prop-element> <p>Present value: <span>{{demoProp}}</span></p> </template> <script> Polymer ({ is: "my-element", properties: { demoProp: String } }); </script> </dom-module> Next, create one more file called prop-element.html and add the following code. //it specifies the start of an element's local DOM <dom-module id="prop-element"> <template> <button on-click="onClickFunc">Change value</button> </template> <script> Polymer ({ is: "prop-element", properties: { myProp: { type: String, notify: true, readOnly: true, value: 'This is initial value...' } }, onClickFunc: function(){ this._setMyProp('This is new value after clicking the button...'); } }); </script> </dom-module> Run the application as shown in the previous example, and navigate to http://127.0.0.1:8081/. Following will be the output. After clicking the button, it will change the value as shown in the following screenshot. HTML attribute can be synchronized with the property value by setting the reflectToAttribute to true on a property in the properties configuration object. The property value can be serialized to the attribute, while reflecting or binding a property to an attribute, and by default values can be serialized depending on the value's current type. String − There is no need of serialization. String − There is no need of serialization. Date or Number − Use the toString to serialize the values. Date or Number − Use the toString to serialize the values. Boolean − Set the displayed non-valued attribute as either true or false. Boolean − Set the displayed non-valued attribute as either true or false. Array or Object − Use the JSON.stringify to serialize the value. Array or Object − Use the JSON.stringify to serialize the value. Print Add Notes Bookmark this page
[ { "code": null, "e": 1883, "s": 1740, "text": "Polymer is a framework that allows creating custom elements using standard HTML elements. Custom web elements provide the following features −" }, { "code": null, "e": 1939, "s": 1883, "text": "It provides custom element name with associating class." }, { "code": null, "e": 1995, "s": 1939, "text": "It provides custom element name with associating class." }, { "code": null, "e": 2090, "s": 1995, "text": "When you change the state of custom element instance, it will request the lifecycle callbacks." }, { "code": null, "e": 2185, "s": 2090, "text": "When you change the state of custom element instance, it will request the lifecycle callbacks." }, { "code": null, "e": 2263, "s": 2185, "text": "If you change the attributes on an instance, then callback will be requested." }, { "code": null, "e": 2341, "s": 2263, "text": "If you change the attributes on an instance, then callback will be requested." }, { "code": null, "e": 2475, "s": 2341, "text": "You can define the custom element using ES6 class and class can be associated with the custom element as shown in the following code." }, { "code": null, "e": 2688, "s": 2475, "text": "//ElementDemo class is extending the HTMLElement \nclass ElementDemo extends HTMLElement { \n // code here\n};\n\n//link the new class with an element name\nwindow.customElements.define('element-demo', ElementDemo);\n" }, { "code": null, "e": 2758, "s": 2688, "text": "The custom element can be used as a standard element as shown below −" }, { "code": null, "e": 2789, "s": 2758, "text": "<element-demo></element-demo>\n" }, { "code": null, "e": 2892, "s": 2789, "text": "Note − Custom element name should start with a lower case letter and contain a dash between the names." }, { "code": null, "e": 3054, "s": 2892, "text": "Custom element lifecycle provides a set of custom element reactions which are responsible for change in element lifecycle and are defined in the following table." }, { "code": null, "e": 3066, "s": 3054, "text": "constructor" }, { "code": null, "e": 3173, "s": 3066, "text": "When you create an element or define the previously-created element, this element reaction will be called." }, { "code": null, "e": 3191, "s": 3173, "text": "connectedCallback" }, { "code": null, "e": 3268, "s": 3191, "text": "When you add an element to a document, this element reaction will be called." }, { "code": null, "e": 3289, "s": 3268, "text": "disconnectedCallback" }, { "code": null, "e": 3371, "s": 3289, "text": "When you remove an element from a document, this element reaction will be called." }, { "code": null, "e": 3396, "s": 3371, "text": "attributeChangedCallback" }, { "code": null, "e": 3510, "s": 3396, "text": "Whenever you change, append, remove, or replace an element from a document, this element reaction will be called." }, { "code": null, "e": 3693, "s": 3510, "text": "We can use custom elements before defining them by specification and any existing instances of an element will be upgraded to the custom class by adding a definition to that element." }, { "code": null, "e": 3750, "s": 3693, "text": "The custom element state contains the following values −" }, { "code": null, "e": 3885, "s": 3750, "text": "uncustomized − The valid custom element name is either a built-in element or an unknown element, which cannot become a custom element." }, { "code": null, "e": 4020, "s": 3885, "text": "uncustomized − The valid custom element name is either a built-in element or an unknown element, which cannot become a custom element." }, { "code": null, "e": 4108, "s": 4020, "text": "undefined − The element can have a valid custom element name, but it cannot be defined." }, { "code": null, "e": 4196, "s": 4108, "text": "undefined − The element can have a valid custom element name, but it cannot be defined." }, { "code": null, "e": 4290, "s": 4196, "text": "custom − The element can have a valid custom element name, which can be defined and upgraded." }, { "code": null, "e": 4384, "s": 4290, "text": "custom − The element can have a valid custom element name, which can be defined and upgraded." }, { "code": null, "e": 4451, "s": 4384, "text": "failed − Trying to upgrade the failed element of an invalid class." }, { "code": null, "e": 4518, "s": 4451, "text": "failed − Trying to upgrade the failed element of an invalid class." }, { "code": null, "e": 4760, "s": 4518, "text": "A custom element can be defined by creating a class which extends Polymer.Element and it passes the class to customElements.define method. The class contains is getter method that returns a HTML tag name of the custom element. For instance −" }, { "code": null, "e": 5243, "s": 4760, "text": "//ElementDemo class is extending the Polymer.Element \nclass ElementDemo extends Polymer.Element {\n static get is() { return 'element-demo'; }\n static get properties() {\n . . .\n . . .\n }\n constructor(){\n super();\n . . .\n . . .\n }\n . . .\n . . .\n}\n\n//Associate the new class with an element name\nwindow.customElements.define(ElementDemo.is, ElementDemo);\n\n// create an instance with createElement\nvar el1 = document.createElement('element-demo');" }, { "code": null, "e": 5328, "s": 5243, "text": "The Polymer elements can be defined by specifying the following three HTML imports −" }, { "code": null, "e": 5396, "s": 5328, "text": "polymer-element.html − It specifies the Polymer.Element base class." }, { "code": null, "e": 5464, "s": 5396, "text": "polymer-element.html − It specifies the Polymer.Element base class." }, { "code": null, "e": 5669, "s": 5464, "text": "legacy-element.html − It extends Polymer.Element using Polymer.LegacyElement base class and adds 1.x compatible legacy API. It also creates hybrid elements by defining the legacy Polymer() factory method." }, { "code": null, "e": 5874, "s": 5669, "text": "legacy-element.html − It extends Polymer.Element using Polymer.LegacyElement base class and adds 1.x compatible legacy API. It also creates hybrid elements by defining the legacy Polymer() factory method." }, { "code": null, "e": 6000, "s": 5874, "text": "polymer.html − It comprises the Polymer base classes along with helper elements, which were included in the 1.x polymer.html." }, { "code": null, "e": 6126, "s": 6000, "text": "polymer.html − It comprises the Polymer base classes along with helper elements, which were included in the 1.x polymer.html." }, { "code": null, "e": 6218, "s": 6126, "text": "You can define an element in the main HTML document using HTMLImports.whenReady() function." }, { "code": null, "e": 6352, "s": 6218, "text": "The following example shows how to define an element in the main HTML document. Create an index.html file and add the following code." }, { "code": null, "e": 6737, "s": 6352, "text": "<!doctype html>\n<html lang = \"en\">\n <head>\n <title>Polymer Example</title>\n <script src = \"bower_components/webcomponentsjs/webcomponents-lite.js\"></script>\n <link rel = \"import\" href = \"bower_components/polymer/polymer.html\">\n <link rel = \"import\" href = \"define-element.html\">\n </head>\n \n <body>\n <define-element></define-element>\n </body>\n</html>" }, { "code": null, "e": 6824, "s": 6737, "text": "Now create a custom element called define-element.html and include the following code." }, { "code": null, "e": 7091, "s": 6824, "text": "<dom-module id = \"define-element\">\n <template>\n <h2>Welcome to Tutorialspoint!!!</h2>\n </template>\n \n <script>\n HTMLImports.whenReady(function(){\n Polymer ({\n is: \"define-element\"\n })\n }) \n </script>\n</dom-module>" }, { "code": null, "e": 7188, "s": 7091, "text": "To run the application, navigate to the created project directory and run the following command." }, { "code": null, "e": 7203, "s": 7188, "text": "polymer serve\n" }, { "code": null, "e": 7294, "s": 7203, "text": "Now open the browser and navigate to http://127.0.0.1:8081/. Following will be the output." }, { "code": null, "e": 7503, "s": 7294, "text": "Legacy element can be used to register an element using the Polymer function, which takes the prototype for a new element. The prototype should contain is which defines the HTML tag name for a custom element." }, { "code": null, "e": 7911, "s": 7503, "text": "//registering an element\nElementDemo = Polymer ({\n is: 'element-demo',\n \n //it is a legecy callback, called when the element has been created\n created: function() {\n this.textContent = 'Hello World!!!';\n }\n});\n\n//'createElement' is used to create an instance\nvar myelement1 = document.createElement('element-demo');\n\n//use the constructor create an instance\nvar myelement2 = new ElementDemo();" }, { "code": null, "e": 8126, "s": 7911, "text": "Lifecycle callbacks are used to accomplish the tasks for built-in features of Polymer.Element class. Polymer uses ready callback, which will be invoked when Polymer completes creating and initializing DOM elements." }, { "code": null, "e": 8181, "s": 8126, "text": "Following is a list of legacy callbacks in Polymer.js." }, { "code": null, "e": 8294, "s": 8181, "text": "created − It is called when you create an element before setting the property values and initializing local DOM." }, { "code": null, "e": 8407, "s": 8294, "text": "created − It is called when you create an element before setting the property values and initializing local DOM." }, { "code": null, "e": 8517, "s": 8407, "text": "ready − It is called when you create an element after setting the property values and initializing local DOM." }, { "code": null, "e": 8627, "s": 8517, "text": "ready − It is called when you create an element after setting the property values and initializing local DOM." }, { "code": null, "e": 8771, "s": 8627, "text": "attached − It is called after attaching the element to the document and can be called more than one time throughout the lifetime of an element." }, { "code": null, "e": 8915, "s": 8771, "text": "attached − It is called after attaching the element to the document and can be called more than one time throughout the lifetime of an element." }, { "code": null, "e": 9057, "s": 8915, "text": "detached − It is called after detaching the element from the document and can be called more than once throughout the lifetime of an element." }, { "code": null, "e": 9199, "s": 9057, "text": "detached − It is called after detaching the element from the document and can be called more than once throughout the lifetime of an element." }, { "code": null, "e": 9372, "s": 9199, "text": "attributeChanged − It is called when there are changes in an element's attributes and it holds the attribute changes, which are not compatible with the declared properties." }, { "code": null, "e": 9545, "s": 9372, "text": "attributeChanged − It is called when there are changes in an element's attributes and it holds the attribute changes, which are not compatible with the declared properties." }, { "code": null, "e": 9715, "s": 9545, "text": "The properties can be declared on an element to add default value and other specific features in the data system and they can be used to specify the following features −" }, { "code": null, "e": 9765, "s": 9715, "text": "It specifies the property type and default value." }, { "code": null, "e": 9815, "s": 9765, "text": "It specifies the property type and default value." }, { "code": null, "e": 9891, "s": 9815, "text": "It calls the observer method, when there are changes in the property value." }, { "code": null, "e": 9967, "s": 9891, "text": "It calls the observer method, when there are changes in the property value." }, { "code": null, "e": 10055, "s": 9967, "text": "It specifies the read-only status to stop the unexpected changes to the property value." }, { "code": null, "e": 10143, "s": 10055, "text": "It specifies the read-only status to stop the unexpected changes to the property value." }, { "code": null, "e": 10250, "s": 10143, "text": "It provides support for two-way data binding, which triggers an event when you change the property values." }, { "code": null, "e": 10357, "s": 10250, "text": "It provides support for two-way data binding, which triggers an event when you change the property values." }, { "code": null, "e": 10456, "s": 10357, "text": "It is a computed property, which calculates a value dynamically depending on the other properties." }, { "code": null, "e": 10555, "s": 10456, "text": "It is a computed property, which calculates a value dynamically depending on the other properties." }, { "code": null, "e": 10651, "s": 10555, "text": "It updates and reflects the corresponding attribute value, when you change the property values." }, { "code": null, "e": 10747, "s": 10651, "text": "It updates and reflects the corresponding attribute value, when you change the property values." }, { "code": null, "e": 10843, "s": 10747, "text": "The following table shows keys for each property, which are supported by the properties object." }, { "code": null, "e": 10848, "s": 10843, "text": "type" }, { "code": null, "e": 10946, "s": 10848, "text": "It deserializes from an attribute whose property type is determined using the type's constructor." }, { "code": null, "e": 10952, "s": 10946, "text": "value" }, { "code": null, "e": 11093, "s": 10952, "text": "It specifies the default value for the property and if it is a function, then it uses the return value as the default value of the property." }, { "code": null, "e": 11112, "s": 11093, "text": "reflectToAttribute" }, { "code": null, "e": 11306, "s": 11112, "text": "If this key sets to true, then it sets the corresponding attribute on the host node. The attribute can be created as a standard HTML boolean attribute, if you set the property value as Boolean." }, { "code": null, "e": 11315, "s": 11306, "text": "readOnly" }, { "code": null, "e": 11411, "s": 11315, "text": "You cannot set the property directly by assignment or data binding, if this key is set to true." }, { "code": null, "e": 11418, "s": 11411, "text": "notify" }, { "code": null, "e": 11578, "s": 11418, "text": "You can use the property for two-way data binding, if this key is set to true and when you change the property, property-name-changed event will get triggered." }, { "code": null, "e": 11587, "s": 11578, "text": "computed" }, { "code": null, "e": 11737, "s": 11587, "text": "You can calculate the value of an argument whenever it changes, by invoking the method and value will be simplified as method name and argument list." }, { "code": null, "e": 11746, "s": 11737, "text": "observer" }, { "code": null, "e": 11835, "s": 11746, "text": "Invoke the method name, which is simplified by a value, when the property value changes." }, { "code": null, "e": 12043, "s": 11835, "text": "Deserialize the property name that matches an attribute on instance according to the type specified and the same property name on the element instance, if the property is configured in the properties object." }, { "code": null, "e": 12281, "s": 12043, "text": "You can set the specified type directly as the value of the property, if there are no other properties options defined in the properties object; otherwise, it will provide the value to the type key in the properties configuration object." }, { "code": null, "e": 12570, "s": 12281, "text": "The Boolean property can be configured from markup, by setting it to false and if it is set to true, then you cannot configure from markup because the attribute with or without a value is equalized to true. Therefore, it is known as a standard behavior for attributes in the web platform." }, { "code": null, "e": 12656, "s": 12570, "text": "The object and array properties can be configured by passing them in JSON format as −" }, { "code": null, "e": 12739, "s": 12656, "text": "<element-demo player = '{ \"name\": \"Sachin\", \"country\": \"India\" }'></element-demo>\n" }, { "code": null, "e": 12900, "s": 12739, "text": "The default property can be configured using the value field in the properties object and it may be either primitive value, or a function which returns a value." }, { "code": null, "e": 12997, "s": 12900, "text": "The following example depicts how to configure the default property values in properties object." }, { "code": null, "e": 13998, "s": 12997, "text": "<link rel = \"import\" href = \"../../bower_components/polymer/polymer-element.html\">\n\n//it specifies the start of an element's local DOM\n<dom-module id=\"polymer-app\">\n <template>\n <style>\n :host {\n color:#33ACC9;\n }\n </style>\n <h2>Hello...[[myval]]!</h2>\t\n </template>\n\n <script>\n //cusom element extending the Polymer.Element class\n class PolymerApp extends Polymer.Element {\n static get is() { return 'polymer-app'; }\n static get properties() {\n return {\n myval: {\n type: String,\n //displaying this value on screen\n value: 'Welcome to Tutorialspoint;!!!'\n },\n data: {\n type: Object,\n notify: true,\n value: function() { return {}; }\n }\n }\n }\n }\n window.customElements.define(PolymerApp.is, PolymerApp);\n </script>\n</dom-module>" }, { "code": null, "e": 14122, "s": 13998, "text": "Run the application as shown in the previous example, and navigate to http://127.0.0.1:8000/. Following will be the output." }, { "code": null, "e": 14338, "s": 14122, "text": "You can avoid unexpected changes on produced data by setting the readOnly flag to true, in the properties object. Element uses the setter of the convention _setProperty(value), in order to change the property value." }, { "code": null, "e": 14481, "s": 14338, "text": "Following example depicts the use of read-only properties in the properties object. Create an index.html file and add the following code in it" }, { "code": null, "e": 14847, "s": 14481, "text": "<!doctype html>\n<html>\n <head>\n <title>Polymer Example</title>\n <script src = \"bower_components/webcomponentsjs/webcomponents-lite.js\"></script>\n \n <link rel = \"import\" href = \"bower_components/polymer/polymer.html\">\n <link rel = \"import\" href = \"my-element.html\">\n </head>\n \n <body>\n <my-element></my-element>\n </body>\n</html>" }, { "code": null, "e": 14927, "s": 14847, "text": "Now, create another file called my-element.html and include the following code." }, { "code": null, "e": 15428, "s": 14927, "text": "<link rel = \"import\" href = \"bower_components/polymer/polymer-element.html\">\n<link rel = \"import\" href = \"prop-element.html\">\n\n//it specifies the start of an element's local DOM\n<dom-module id = \"my-element\">\n <template>\n <prop-element my-prop = \"{{demoProp}}\"></prop-element>\n <p>Present value: <span>{{demoProp}}</span></p>\n </template>\n\n <script>\n Polymer ({\n is: \"my-element\", properties: {\n demoProp: String\n }\n });\n </script>\n</dom-module>" }, { "code": null, "e": 15508, "s": 15428, "text": "Next, create one more file called prop-element.html and add the following code." }, { "code": null, "e": 16101, "s": 15508, "text": "//it specifies the start of an element's local DOM\n<dom-module id=\"prop-element\">\n <template>\n <button on-click=\"onClickFunc\">Change value</button>\n </template>\n \n <script>\n Polymer ({\n is: \"prop-element\", properties: {\n myProp: {\n type: String,\n notify: true,\n readOnly: true,\n value: 'This is initial value...'\n }\n },\n onClickFunc: function(){\n this._setMyProp('This is new value after clicking the button...');\n }\n });\n </script>\n</dom-module>" }, { "code": null, "e": 16225, "s": 16101, "text": "Run the application as shown in the previous example, and navigate to http://127.0.0.1:8081/. Following will be the output." }, { "code": null, "e": 16315, "s": 16225, "text": "After clicking the button, it will change the value as shown in the following screenshot." }, { "code": null, "e": 16470, "s": 16315, "text": "HTML attribute can be synchronized with the property value by setting the reflectToAttribute to true on a property in the properties configuration object." }, { "code": null, "e": 16660, "s": 16470, "text": "The property value can be serialized to the attribute, while reflecting or binding a property to an attribute, and by default values can be serialized depending on the value's current type." }, { "code": null, "e": 16704, "s": 16660, "text": "String − There is no need of serialization." }, { "code": null, "e": 16748, "s": 16704, "text": "String − There is no need of serialization." }, { "code": null, "e": 16807, "s": 16748, "text": "Date or Number − Use the toString to serialize the values." }, { "code": null, "e": 16866, "s": 16807, "text": "Date or Number − Use the toString to serialize the values." }, { "code": null, "e": 16940, "s": 16866, "text": "Boolean − Set the displayed non-valued attribute as either true or false." }, { "code": null, "e": 17014, "s": 16940, "text": "Boolean − Set the displayed non-valued attribute as either true or false." }, { "code": null, "e": 17079, "s": 17014, "text": "Array or Object − Use the JSON.stringify to serialize the value." }, { "code": null, "e": 17144, "s": 17079, "text": "Array or Object − Use the JSON.stringify to serialize the value." }, { "code": null, "e": 17151, "s": 17144, "text": " Print" }, { "code": null, "e": 17162, "s": 17151, "text": " Add Notes" } ]
Tryit Editor v3.7
Tryit: HTML image size
[]
Find the Sum of the series 1, 2, 3, 6, 9, 18, 27, 54, ... till N terms - GeeksforGeeks
13 Jan, 2022 Given a number N, the task is to find the sum of the below series till N terms. Examples: Input: N = 8 Output: 201 1 + 2 + 3 + 6 + 9 + 18 + 27 + 54 + 81 = 201Input: N = 12 Output: 1821 1 + 2 + 3 + 6 + 9 + 18 + 27 + 54 + 81 + 162 + 243 + 486 + 729 = 1821 Approach: From the given series, find the formula for Nth term: 1st term = 1 2nd term = 2 = 2 * 1 3rd term = 3 = 3/2 * 2 4th term = 6 = 2 * 3 5th term = 9 = 3/2 * 6 6th term = 18 = 2 * 9 . . Nth term = [2 * (N-1)th term], if N is even [3/2 * (N-1)th term], if N is odd Therefore: Nth term of the series Then iterate over numbers in the range [1, N] to find all the terms using the above formula and compute their sum.Approach: By observing the pattern in the given series, the next numbers of the series are alternatively multiplied by 2 and 3/2.Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for the above series#include <iostream>using namespace std; // Function to find the sum of seriesvoid printSeriesSum(int N){ double sum = 0; int a = 1; int cnt = 0; // Flag to find the multiplicating // factor.. i.e, by 2 or 3/2 bool flag = true; // First term sum += a; while (cnt < N) { int nextElement; // If flag is true, multiply by 2 if (flag) { nextElement = a * 2; sum += nextElement; flag = !flag; } // If flag is false, multiply by 3/2 else { nextElement = a * 3 / 2; sum += nextElement; flag = !flag; } // Update the previous element // to nextElement a = nextElement; cnt++; } // Print the sum cout << sum << endl;} // Driver Codeint main(){ int N = 8; printSeriesSum(N); return 0;} // Java program for the above seriesclass GFG { // Function to find the sum of series static void printSeriesSum(int N) { double sum = 0; int a = 1; int cnt = 0; // Flag to find the multiplicating // factor.. i.e, by 2 or 3/2 boolean flag = true; // First term sum += a; while (cnt < N) { int nextElement; // If flag is true, multiply by 2 if (flag == true) { nextElement = a * 2; sum += nextElement; flag = !flag; } // If flag is false, multiply by 3/2 else { nextElement = a * 3 / 2; sum += nextElement; flag = !flag; } // Update the previous element // to nextElement a = nextElement; cnt++; } // Print the sum System.out.println(sum); } // Driver Code public static void main (String[] args) { int N = 8; printSeriesSum(N); }}// This code is contributed by AnkitRai01 # Python3 program for the above series # Function to find the sum of seriesdef printSeriesSum(N) : sum = 0; a = 1; cnt = 0; # Flag to find the multiplicating # factor.. i.e, by 2 or 3/2 flag = True; # First term sum += a; while (cnt < N) : nextElement = None; # If flag is true, multiply by 2 if (flag) : nextElement = a * 2; sum += nextElement; flag = not flag; # If flag is false, multiply by 3/2 else : nextElement = a * (3 / 2); sum += nextElement; flag = not flag; # Update the previous element # to nextElement a = nextElement; cnt += 1 # Print the sum print(sum); # Driver Codeif __name__ == "__main__" : N = 8; printSeriesSum(N); # This code is contributed by AnkitRai01 // C# program for the above seriesusing System; class GFG { // Function to find the sum of series static void printSeriesSum(int N) { double sum = 0; int a = 1; int cnt = 0; // Flag to find the multiplicating // factor.. i.e, by 2 or 3/2 bool flag = true; // First term sum += a; while (cnt < N) { int nextElement; // If flag is true, multiply by 2 if (flag == true) { nextElement = a * 2; sum += nextElement; flag = !flag; } // If flag is false, multiply by 3/2 else { nextElement = a * 3 / 2; sum += nextElement; flag = !flag; } // Update the previous element // to nextElement a = nextElement; cnt++; } // Print the sum Console.WriteLine(sum); } // Driver Code public static void Main (string[] args) { int N = 8; printSeriesSum(N); } } // This code is contributed by AnkitRai01 <script> // javascript program for the above series // Function to find the sum of seriesfunction printSeriesSum( N){ let sum = 0; let a = 1; let cnt = 0; // Flag to find the multiplicating // factor.. i.e, by 2 or 3/2 let flag = true; // First term sum += a; while (cnt < N) { let nextElement; // If flag is true, multiply by 2 if (flag) { nextElement = a * 2; sum += nextElement; flag = !flag; } // If flag is false, multiply by 3/2 else { nextElement = a * 3 / 2; sum += nextElement; flag = !flag; } // Update the previous element // to nextElement a = nextElement; cnt++; } // Print the sum document.write(sum );} // Driver Code let N = 8; printSeriesSum(N); // This code is contributed by todaysgaurav </script> 201 Time Complexity: O(N) Auxiliary Space: O(1) ankthon todaysgaurav souravmahato348 series series-sum Mathematical School Programming Mathematical series Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples Prime Numbers Program to find GCD or HCF of two numbers Print all possible combinations of r elements in a given array of size n Python Dictionary Arrays in C/C++ Inheritance in C++ Reverse a string in Java Interfaces in Java
[ { "code": null, "e": 25823, "s": 25795, "text": "\n13 Jan, 2022" }, { "code": null, "e": 25904, "s": 25823, "text": "Given a number N, the task is to find the sum of the below series till N terms. " }, { "code": null, "e": 25916, "s": 25904, "text": "Examples: " }, { "code": null, "e": 26082, "s": 25916, "text": "Input: N = 8 Output: 201 1 + 2 + 3 + 6 + 9 + 18 + 27 + 54 + 81 = 201Input: N = 12 Output: 1821 1 + 2 + 3 + 6 + 9 + 18 + 27 + 54 + 81 + 162 + 243 + 486 + 729 = 1821 " }, { "code": null, "e": 26150, "s": 26084, "text": "Approach: From the given series, find the formula for Nth term: " }, { "code": null, "e": 26366, "s": 26150, "text": "1st term = 1\n2nd term = 2 = 2 * 1\n3rd term = 3 = 3/2 * 2\n4th term = 6 = 2 * 3\n5th term = 9 = 3/2 * 6\n6th term = 18 = 2 * 9\n.\n.\nNth term = [2 * (N-1)th term], if N is even\n [3/2 * (N-1)th term], if N is odd" }, { "code": null, "e": 26379, "s": 26366, "text": "Therefore: " }, { "code": null, "e": 26403, "s": 26379, "text": "Nth term of the series " }, { "code": null, "e": 26699, "s": 26403, "text": "Then iterate over numbers in the range [1, N] to find all the terms using the above formula and compute their sum.Approach: By observing the pattern in the given series, the next numbers of the series are alternatively multiplied by 2 and 3/2.Below is the implementation of the above approach: " }, { "code": null, "e": 26703, "s": 26699, "text": "C++" }, { "code": null, "e": 26708, "s": 26703, "text": "Java" }, { "code": null, "e": 26716, "s": 26708, "text": "Python3" }, { "code": null, "e": 26719, "s": 26716, "text": "C#" }, { "code": null, "e": 26730, "s": 26719, "text": "Javascript" }, { "code": "// C++ program for the above series#include <iostream>using namespace std; // Function to find the sum of seriesvoid printSeriesSum(int N){ double sum = 0; int a = 1; int cnt = 0; // Flag to find the multiplicating // factor.. i.e, by 2 or 3/2 bool flag = true; // First term sum += a; while (cnt < N) { int nextElement; // If flag is true, multiply by 2 if (flag) { nextElement = a * 2; sum += nextElement; flag = !flag; } // If flag is false, multiply by 3/2 else { nextElement = a * 3 / 2; sum += nextElement; flag = !flag; } // Update the previous element // to nextElement a = nextElement; cnt++; } // Print the sum cout << sum << endl;} // Driver Codeint main(){ int N = 8; printSeriesSum(N); return 0;}", "e": 27652, "s": 26730, "text": null }, { "code": "// Java program for the above seriesclass GFG { // Function to find the sum of series static void printSeriesSum(int N) { double sum = 0; int a = 1; int cnt = 0; // Flag to find the multiplicating // factor.. i.e, by 2 or 3/2 boolean flag = true; // First term sum += a; while (cnt < N) { int nextElement; // If flag is true, multiply by 2 if (flag == true) { nextElement = a * 2; sum += nextElement; flag = !flag; } // If flag is false, multiply by 3/2 else { nextElement = a * 3 / 2; sum += nextElement; flag = !flag; } // Update the previous element // to nextElement a = nextElement; cnt++; } // Print the sum System.out.println(sum); } // Driver Code public static void main (String[] args) { int N = 8; printSeriesSum(N); }}// This code is contributed by AnkitRai01", "e": 28835, "s": 27652, "text": null }, { "code": "# Python3 program for the above series # Function to find the sum of seriesdef printSeriesSum(N) : sum = 0; a = 1; cnt = 0; # Flag to find the multiplicating # factor.. i.e, by 2 or 3/2 flag = True; # First term sum += a; while (cnt < N) : nextElement = None; # If flag is true, multiply by 2 if (flag) : nextElement = a * 2; sum += nextElement; flag = not flag; # If flag is false, multiply by 3/2 else : nextElement = a * (3 / 2); sum += nextElement; flag = not flag; # Update the previous element # to nextElement a = nextElement; cnt += 1 # Print the sum print(sum); # Driver Codeif __name__ == \"__main__\" : N = 8; printSeriesSum(N); # This code is contributed by AnkitRai01", "e": 29719, "s": 28835, "text": null }, { "code": "// C# program for the above seriesusing System; class GFG { // Function to find the sum of series static void printSeriesSum(int N) { double sum = 0; int a = 1; int cnt = 0; // Flag to find the multiplicating // factor.. i.e, by 2 or 3/2 bool flag = true; // First term sum += a; while (cnt < N) { int nextElement; // If flag is true, multiply by 2 if (flag == true) { nextElement = a * 2; sum += nextElement; flag = !flag; } // If flag is false, multiply by 3/2 else { nextElement = a * 3 / 2; sum += nextElement; flag = !flag; } // Update the previous element // to nextElement a = nextElement; cnt++; } // Print the sum Console.WriteLine(sum); } // Driver Code public static void Main (string[] args) { int N = 8; printSeriesSum(N); } } // This code is contributed by AnkitRai01 ", "e": 30955, "s": 29719, "text": null }, { "code": "<script> // javascript program for the above series // Function to find the sum of seriesfunction printSeriesSum( N){ let sum = 0; let a = 1; let cnt = 0; // Flag to find the multiplicating // factor.. i.e, by 2 or 3/2 let flag = true; // First term sum += a; while (cnt < N) { let nextElement; // If flag is true, multiply by 2 if (flag) { nextElement = a * 2; sum += nextElement; flag = !flag; } // If flag is false, multiply by 3/2 else { nextElement = a * 3 / 2; sum += nextElement; flag = !flag; } // Update the previous element // to nextElement a = nextElement; cnt++; } // Print the sum document.write(sum );} // Driver Code let N = 8; printSeriesSum(N); // This code is contributed by todaysgaurav </script>", "e": 31892, "s": 30955, "text": null }, { "code": null, "e": 31896, "s": 31892, "text": "201" }, { "code": null, "e": 31920, "s": 31898, "text": "Time Complexity: O(N)" }, { "code": null, "e": 31942, "s": 31920, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 31950, "s": 31942, "text": "ankthon" }, { "code": null, "e": 31963, "s": 31950, "text": "todaysgaurav" }, { "code": null, "e": 31979, "s": 31963, "text": "souravmahato348" }, { "code": null, "e": 31986, "s": 31979, "text": "series" }, { "code": null, "e": 31997, "s": 31986, "text": "series-sum" }, { "code": null, "e": 32010, "s": 31997, "text": "Mathematical" }, { "code": null, "e": 32029, "s": 32010, "text": "School Programming" }, { "code": null, "e": 32042, "s": 32029, "text": "Mathematical" }, { "code": null, "e": 32049, "s": 32042, "text": "series" }, { "code": null, "e": 32147, "s": 32049, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32171, "s": 32147, "text": "Merge two sorted arrays" }, { "code": null, "e": 32214, "s": 32171, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 32228, "s": 32214, "text": "Prime Numbers" }, { "code": null, "e": 32270, "s": 32228, "text": "Program to find GCD or HCF of two numbers" }, { "code": null, "e": 32343, "s": 32270, "text": "Print all possible combinations of r elements in a given array of size n" }, { "code": null, "e": 32361, "s": 32343, "text": "Python Dictionary" }, { "code": null, "e": 32377, "s": 32361, "text": "Arrays in C/C++" }, { "code": null, "e": 32396, "s": 32377, "text": "Inheritance in C++" }, { "code": null, "e": 32421, "s": 32396, "text": "Reverse a string in Java" } ]
Creating the ecology classic ‘Kite diagram’ in Python | by Alan Davies | Towards Data Science
Kite diagrams are classically used in both ecology and biology studies and also form part of the school syllabus on A-Level Biology courses in the UK. Despite this, there are few options for creating these diagrams in standard software visualisation packages, and most seem to still be hand drawn. This short post will explain how to automate this process with Python 3 and the matplotlib library. So what are Kite diagrams? Kite diagrams provide a graphical summary of different observations made along a transect. A transect is a line placed across a part of a habitat, or an entire habitat. This is often done manually with string, rope etc. The quantity of various species can be counted at regular intervals along the transect. The distribution of the various species can be affected by various different factors including predators and also by other environmental factors like heat, light and moisture levels. These are referred to as abiotic (not alive) factors. Data can also be collected using a quadrat, this involves using a square (e.g. 1m2) frame that is moved along the transect. The number of species in the square can then be counted at each point. Kite diagrams are a way of seeing the change in abundance of the various species along a transect. This allows researchers to see the relative abundance of certain species in different places in a habitat such as a seashore. There may be many types of grass, plants and insects for example distributed over the shore at different points. These diagrams are often produced by hand, and there seems to be little in the way of support for them in standard visualisation packages. We found one example in Excel (Luke, 2019) and one produced using R (Hood, 2014), but nothing using Python. As Python is being used increasingly to analyse data, we thought we would have a go at implementing a simple Kite diagram using Python. This was done using an interactive Jupyter notebook with Python 3. We present the process here for those in other fields that may find automating such diagrams useful. We have deliberately tried to keep the implementation basic for beginners. For the example, we will use Python’s ‘pandas’ library to represent the dataset that we will use. This dataset was entered into Excel and saved as a Comma Separated Values (CSV) file. We will also use the numpy library to extract columns from the dataset and apply operations to them. As is the convention in Python, we can refer to these libraries using a short hand reference (pd for pandas and np for numpy). import pandas as pdimport numpy as np Importing the data Next, we load the dataset into a pandas dataframe object using the pandas read_csv() function, supplying the path to the CSV file. We store this data in a variable called kite_data that can then be viewed in the notebook (or other Python environment). kite_data = pd.read_csv("./biology/kitedata.csv")kite_data The first column of the data should represent the distances. This will be used for the horizontal axis. The remaining columns represent the frequency of species or sometimes the percentage cover of certain plants that will be plotted at intervals on the y-axis. Create the Kite plot function The next stage is to create a function to generate the Kite diagram. This builds on the matplotlib library that is widely used to generate a large variety of visualisations. You can see some examples in the gallery here https://matplotlib.org/3.1.1/gallery/index.html. We will import the library and refer to it as plt. We will also need to use the Polygon function to draw the kite shapes on the diagram. import matplotlib.pyplot as pltfrom matplotlib.patches import Polygon After importing the libraries we can then create the function. The first column of the dataframe should be the distance or other measure of segmentation of the area (e.g. quadrats). Here we use the iloc feature which stands for integer location. This is a way of referencing columns by a number (0 to number of columns) rather than by the columns name. We can extract and store the first column of distances for use on the x-axis later. We also create an empty list to store the start points. This is used to position the individual Kite shapes on the y-axis. We also get the column names and store this in the y_values variable for plotting the species names on the y-axis later. Finally, we get the number of columns in the dataframe and store this in a variable called num_cols so we know how many species we need to add to the diagram. def kite_diagram(df, axis_labs): """Function to draw a kite diagram.""" plt.axes() start_points = [] v1 = np.array(df.iloc[:, [0]]) y_values = df.columns y_values = np.delete(y_values, 0) num_cols = len(df.columns) - 1 Now we need to get the maximum value from the dataset (not including the distances column) so that we can position the kite shapes on the diagram with adequate vertical spacing. We want to space the different Kite plots by the maximum distance so that they don’t overlap each other as this would make them unreadable. To do this we get all the columns apart from the first (distance) column, then we use the max() function to determine the maximum value in the columns. df_cols = df.iloc[:, 1:len(df.columns)] max_val = max(df_cols.max()) As Python uses an indexing system that starts at 0, we select 1 to the number of columns (length of columns) to exclude the first (distance) column which is stored at location zero. Next, we store the maximum value in the data in the variable called max_val. Each column apart from the first should represent a different species, so we need to loop over each of these columns and make a Kite shape for each species. As Python indexes from 0, we will start at 1 to skip the distance column. for j in range(1, num_cols + 1): p1 = [] p2 = [] The p1 and p2 lists will store the coordinate points for the polygons (Kite shapes) for each species. There are 2 lists because the plot essentially shows a mirror image of the same shape above and below the base line as seen in the figure below. This is achieved by halving each value and projecting a pair of points with one value above and the other below the horizontal base line by this halved value such that the distance between each pair represents the original total value. For example, a value of 8 will be 4 units above the baseline and 4 units below the baseline. To code this, we need to get the mid-point of each data value. This is done by dividing each of the values by 2. We can do this easily with numpy. We can take each of the columns values and turn them into numpy arrays. We can then divide each value in the array by 2. v2 = np.array(df.iloc[:, [j]]) / 2 It should be noted that operations cannot be applied to entire lists using standard Python lists. The figure below illustrates this, showing an error when we try to divide the list by 2. If however we use a numpy array instead, the operation will be applied to all the values in the list: Next we want to work out if this is the first Kite we are adding to the diagram, if so we want to position the vertical baseline at half the maximum value found in the dataset so we have enough space to draw the required pattern above and below the baseline. For all the other subsequent Kite patterns, we will add the maximum value in the dataset to the previous starting point to evenly space them vertically. if j == 1: start_point = max_val / 2else: start_point = start_point + max_val We also store these start points for the baseline of each species in a list for labelling the plot later. Additionally, we make the first points for our polygons (above and below the line) zero so we don’t have any gaps when we start to draw to the shapes. We do this either end of the whole shape to prevent unwanted gaps. start_points.append(start_point)p1.append([0, start_point])p2.append([0, start_point]) Generate the points for the Kite shapes For all the subsequent points we will loop through all the values and add or subtract the half values we computed and stored in the v2 variable for values both above and below the line. The pattern should be the same above and below so we store the above line points with the horizontal distance (v1) in a variable called p1 (polygon 1) and the same for below the line in a variable called p2 (polygon 2). Finally after going through all the values we add an additional pair of values to both polygons to bring the lines back down to the starting point. Again, this avoids any gaps in the pattern at the end of the shape. for i in range(0, len(v1)): p1.append([v1[i], start_point + v2[i]]) p2.append([v1[i], start_point - v2[i]])p1.append([v1[i], start_point])p2.append([v1[i], start_point]) What we end up with is a list of points with sets of coordinates. The first of each pair is the position on the x-axis (horizontal position) that goes from 0 to 20 in our example. The second number of the pair in p1 is the position above the baseline on the diagram (the vertical y-axis) whereas in p2 this is the position below the baseline: p1 = [[0, 0], [2, 0], [4, 0], [6, 0], [8, 1.5], [10, 2], [12, 4], [14, 4], [16, 3.5], [18, 2.5], [20, 2], [20, 0]] p2 = [[0, 0], [2, 0], [4, 0], [6, 0], [8, -1.5], [10, -2], [12, -4], [14, -4], [16, -3.5], [18, -2.5], [20, -2], [20, 0]] Add the shapes to the plot We can now use these points to create and add the polygons to the plot with the Polygon() function. c = np.random.rand(3,)l1 = plt.Polygon(p1, closed=None, fill=True, edgecolor=c, alpha=0.4, color=c)l2 = plt.Polygon(p2, closed=None, fill=True, edgecolor=c, alpha=0.4, color=c) We assign a random colour for each of the Kite shapes and store this value in a variable called c. We create 2 polygons with matplotlibs’ Polygon() function storing them in variables l1 and l2. The first argument is the data points (p1 or p2), next we set some of the other optional parameters, we want the shape to be filled so we set this to True, we add a colour for the edge. In this case we use the same colour as we use for the whole shape. The alpha value can be adjusted to add some transparency to the shape. This can help if there are any overlaps in the shapes or just to make the colours less intense. Finally, we add a fill colour. The polygons can now be added to the plot with the add_line() function. The gca() function Gets the Current Axis of a plot or creates one. plt.gca().add_line(l1)plt.gca().add_line(l2) Finishing touches Finally, after looping through all columns and adding species Kite shapes, we can add additional features to the entire plot after the main loop. plt.yticks(start_points, y_values)plt.xlabel(axis_labs[0])plt.ylabel(axis_labs[1])plt.axis('scaled')plt.show(); Recall that we added the column names (species) to a variable called y_values, we can add these names to the start_points locations we stored using the yticks() function to line up the species names with the baselines. The next 2 lines add labels for the x axis and y axis which we pass into the function in a list. The ‘axis scaled’ option changes the dimensions of the plot container rather than the data limits. The other option that can be used is ‘equal’ so that the x,y points have equal increments. Finally, the show() function will render the plot. Lastly, to draw the plot we need to call the function providing the dataset and x/y axis labels in a list. kite_diagram(kite_data, ['Distance', 'Species']); This output can be seen side-by-side next to the hand drawn version: The code for the full function can be seen below: def kite_diagram(df, axis_labs): """Function to draw a kite diagram.""" plt.axes() start_points = [] v1 = np.array(df.iloc[:, [0]]) y_values = df.columns y_values = np.delete(y_values, 0) num_cols = len(df.columns) - 1 df_cols = df.iloc[:, 1:len(df.columns)] max_val = max(df_cols.max()) for j in range(1, num_cols + 1): p1 = [] p2 = [] v2 = np.array(df.iloc[:, [j]]) / 2 if j == 1: start_point = max_val / 2 else: start_point = start_point + max_val start_points.append(start_point) p1.append([0, start_point]) p2.append([0, start_point]) for i in range(0, len(v1)): p1.append([v1[i], start_point + v2[i]]) p2.append([v1[i], start_point - v2[i]]) p1.append([v1[i], start_point]) p2.append([v1[i], start_point]) c = np.random.rand(3,) l1 = plt.Polygon(p1, closed=None, fill=True, edgecolor=c, alpha=0.4, color=c) l2 = plt.Polygon(p2, closed=None, fill=True, edgecolor=c, alpha=0.4, color=c) plt.gca().add_line(l1) plt.gca().add_line(l2) plt.yticks(start_points, y_values) plt.xlabel(axis_labs[0]) plt.ylabel(axis_labs[1]) plt.axis('scaled') plt.show(); Python has a wide variety of visualisations available through libraries such as matplotlib, seaborn, ggplot etc. these libraries can also be easily extended to add additional types of visualisation, as seen here. This provides a rich basis for scientific visualisation in multiple scientific fields. Modern languages with support for data science such as R and Python encourage the development of such visualisations, providing the tools to make such plots relatively simple to implement. References [1] Luke, K (2019) Best Excel Tutorial: Kite Chart [online]. Accessed: 07–07–2020 https://best-excel-tutorial.com/56-charts/267-kite-chart [2] Hood, D (2014) RPubs: Kite Graphs in R [online]. Accessed: 07–07–2020 https://rpubs.com/thoughtfulbloke/kitegraph With thanks to Victoria Golas who contributed to the writing of this post and provided the hand drawn version of the diagram.
[ { "code": null, "e": 569, "s": 171, "text": "Kite diagrams are classically used in both ecology and biology studies and also form part of the school syllabus on A-Level Biology courses in the UK. Despite this, there are few options for creating these diagrams in standard software visualisation packages, and most seem to still be hand drawn. This short post will explain how to automate this process with Python 3 and the matplotlib library." }, { "code": null, "e": 1336, "s": 569, "text": "So what are Kite diagrams? Kite diagrams provide a graphical summary of different observations made along a transect. A transect is a line placed across a part of a habitat, or an entire habitat. This is often done manually with string, rope etc. The quantity of various species can be counted at regular intervals along the transect. The distribution of the various species can be affected by various different factors including predators and also by other environmental factors like heat, light and moisture levels. These are referred to as abiotic (not alive) factors. Data can also be collected using a quadrat, this involves using a square (e.g. 1m2) frame that is moved along the transect. The number of species in the square can then be counted at each point." }, { "code": null, "e": 1435, "s": 1336, "text": "Kite diagrams are a way of seeing the change in abundance of the various species along a transect." }, { "code": null, "e": 1674, "s": 1435, "text": "This allows researchers to see the relative abundance of certain species in different places in a habitat such as a seashore. There may be many types of grass, plants and insects for example distributed over the shore at different points." }, { "code": null, "e": 2300, "s": 1674, "text": "These diagrams are often produced by hand, and there seems to be little in the way of support for them in standard visualisation packages. We found one example in Excel (Luke, 2019) and one produced using R (Hood, 2014), but nothing using Python. As Python is being used increasingly to analyse data, we thought we would have a go at implementing a simple Kite diagram using Python. This was done using an interactive Jupyter notebook with Python 3. We present the process here for those in other fields that may find automating such diagrams useful. We have deliberately tried to keep the implementation basic for beginners." }, { "code": null, "e": 2712, "s": 2300, "text": "For the example, we will use Python’s ‘pandas’ library to represent the dataset that we will use. This dataset was entered into Excel and saved as a Comma Separated Values (CSV) file. We will also use the numpy library to extract columns from the dataset and apply operations to them. As is the convention in Python, we can refer to these libraries using a short hand reference (pd for pandas and np for numpy)." }, { "code": null, "e": 2750, "s": 2712, "text": "import pandas as pdimport numpy as np" }, { "code": null, "e": 2769, "s": 2750, "text": "Importing the data" }, { "code": null, "e": 3021, "s": 2769, "text": "Next, we load the dataset into a pandas dataframe object using the pandas read_csv() function, supplying the path to the CSV file. We store this data in a variable called kite_data that can then be viewed in the notebook (or other Python environment)." }, { "code": null, "e": 3080, "s": 3021, "text": "kite_data = pd.read_csv(\"./biology/kitedata.csv\")kite_data" }, { "code": null, "e": 3342, "s": 3080, "text": "The first column of the data should represent the distances. This will be used for the horizontal axis. The remaining columns represent the frequency of species or sometimes the percentage cover of certain plants that will be plotted at intervals on the y-axis." }, { "code": null, "e": 3372, "s": 3342, "text": "Create the Kite plot function" }, { "code": null, "e": 3778, "s": 3372, "text": "The next stage is to create a function to generate the Kite diagram. This builds on the matplotlib library that is widely used to generate a large variety of visualisations. You can see some examples in the gallery here https://matplotlib.org/3.1.1/gallery/index.html. We will import the library and refer to it as plt. We will also need to use the Polygon function to draw the kite shapes on the diagram." }, { "code": null, "e": 3848, "s": 3778, "text": "import matplotlib.pyplot as pltfrom matplotlib.patches import Polygon" }, { "code": null, "e": 4688, "s": 3848, "text": "After importing the libraries we can then create the function. The first column of the dataframe should be the distance or other measure of segmentation of the area (e.g. quadrats). Here we use the iloc feature which stands for integer location. This is a way of referencing columns by a number (0 to number of columns) rather than by the columns name. We can extract and store the first column of distances for use on the x-axis later. We also create an empty list to store the start points. This is used to position the individual Kite shapes on the y-axis. We also get the column names and store this in the y_values variable for plotting the species names on the y-axis later. Finally, we get the number of columns in the dataframe and store this in a variable called num_cols so we know how many species we need to add to the diagram." }, { "code": null, "e": 4932, "s": 4688, "text": "def kite_diagram(df, axis_labs): \"\"\"Function to draw a kite diagram.\"\"\" plt.axes() start_points = [] v1 = np.array(df.iloc[:, [0]]) y_values = df.columns y_values = np.delete(y_values, 0) num_cols = len(df.columns) - 1" }, { "code": null, "e": 5402, "s": 4932, "text": "Now we need to get the maximum value from the dataset (not including the distances column) so that we can position the kite shapes on the diagram with adequate vertical spacing. We want to space the different Kite plots by the maximum distance so that they don’t overlap each other as this would make them unreadable. To do this we get all the columns apart from the first (distance) column, then we use the max() function to determine the maximum value in the columns." }, { "code": null, "e": 5478, "s": 5402, "text": " df_cols = df.iloc[:, 1:len(df.columns)] max_val = max(df_cols.max())" }, { "code": null, "e": 5968, "s": 5478, "text": "As Python uses an indexing system that starts at 0, we select 1 to the number of columns (length of columns) to exclude the first (distance) column which is stored at location zero. Next, we store the maximum value in the data in the variable called max_val. Each column apart from the first should represent a different species, so we need to loop over each of these columns and make a Kite shape for each species. As Python indexes from 0, we will start at 1 to skip the distance column." }, { "code": null, "e": 6035, "s": 5968, "text": " for j in range(1, num_cols + 1): p1 = [] p2 = []" }, { "code": null, "e": 6611, "s": 6035, "text": "The p1 and p2 lists will store the coordinate points for the polygons (Kite shapes) for each species. There are 2 lists because the plot essentially shows a mirror image of the same shape above and below the base line as seen in the figure below. This is achieved by halving each value and projecting a pair of points with one value above and the other below the horizontal base line by this halved value such that the distance between each pair represents the original total value. For example, a value of 8 will be 4 units above the baseline and 4 units below the baseline." }, { "code": null, "e": 6879, "s": 6611, "text": "To code this, we need to get the mid-point of each data value. This is done by dividing each of the values by 2. We can do this easily with numpy. We can take each of the columns values and turn them into numpy arrays. We can then divide each value in the array by 2." }, { "code": null, "e": 6918, "s": 6879, "text": " v2 = np.array(df.iloc[:, [j]]) / 2" }, { "code": null, "e": 7105, "s": 6918, "text": "It should be noted that operations cannot be applied to entire lists using standard Python lists. The figure below illustrates this, showing an error when we try to divide the list by 2." }, { "code": null, "e": 7207, "s": 7105, "text": "If however we use a numpy array instead, the operation will be applied to all the values in the list:" }, { "code": null, "e": 7619, "s": 7207, "text": "Next we want to work out if this is the first Kite we are adding to the diagram, if so we want to position the vertical baseline at half the maximum value found in the dataset so we have enough space to draw the required pattern above and below the baseline. For all the other subsequent Kite patterns, we will add the maximum value in the dataset to the previous starting point to evenly space them vertically." }, { "code": null, "e": 7703, "s": 7619, "text": "if j == 1: start_point = max_val / 2else: start_point = start_point + max_val" }, { "code": null, "e": 8027, "s": 7703, "text": "We also store these start points for the baseline of each species in a list for labelling the plot later. Additionally, we make the first points for our polygons (above and below the line) zero so we don’t have any gaps when we start to draw to the shapes. We do this either end of the whole shape to prevent unwanted gaps." }, { "code": null, "e": 8114, "s": 8027, "text": "start_points.append(start_point)p1.append([0, start_point])p2.append([0, start_point])" }, { "code": null, "e": 8154, "s": 8114, "text": "Generate the points for the Kite shapes" }, { "code": null, "e": 8776, "s": 8154, "text": "For all the subsequent points we will loop through all the values and add or subtract the half values we computed and stored in the v2 variable for values both above and below the line. The pattern should be the same above and below so we store the above line points with the horizontal distance (v1) in a variable called p1 (polygon 1) and the same for below the line in a variable called p2 (polygon 2). Finally after going through all the values we add an additional pair of values to both polygons to bring the lines back down to the starting point. Again, this avoids any gaps in the pattern at the end of the shape." }, { "code": null, "e": 8953, "s": 8776, "text": "for i in range(0, len(v1)): p1.append([v1[i], start_point + v2[i]]) p2.append([v1[i], start_point - v2[i]])p1.append([v1[i], start_point])p2.append([v1[i], start_point])" }, { "code": null, "e": 9296, "s": 8953, "text": "What we end up with is a list of points with sets of coordinates. The first of each pair is the position on the x-axis (horizontal position) that goes from 0 to 20 in our example. The second number of the pair in p1 is the position above the baseline on the diagram (the vertical y-axis) whereas in p2 this is the position below the baseline:" }, { "code": null, "e": 9411, "s": 9296, "text": "p1 = [[0, 0], [2, 0], [4, 0], [6, 0], [8, 1.5], [10, 2], [12, 4], [14, 4], [16, 3.5], [18, 2.5], [20, 2], [20, 0]]" }, { "code": null, "e": 9533, "s": 9411, "text": "p2 = [[0, 0], [2, 0], [4, 0], [6, 0], [8, -1.5], [10, -2], [12, -4], [14, -4], [16, -3.5], [18, -2.5], [20, -2], [20, 0]]" }, { "code": null, "e": 9560, "s": 9533, "text": "Add the shapes to the plot" }, { "code": null, "e": 9660, "s": 9560, "text": "We can now use these points to create and add the polygons to the plot with the Polygon() function." }, { "code": null, "e": 9837, "s": 9660, "text": "c = np.random.rand(3,)l1 = plt.Polygon(p1, closed=None, fill=True, edgecolor=c, alpha=0.4, color=c)l2 = plt.Polygon(p2, closed=None, fill=True, edgecolor=c, alpha=0.4, color=c)" }, { "code": null, "e": 10482, "s": 9837, "text": "We assign a random colour for each of the Kite shapes and store this value in a variable called c. We create 2 polygons with matplotlibs’ Polygon() function storing them in variables l1 and l2. The first argument is the data points (p1 or p2), next we set some of the other optional parameters, we want the shape to be filled so we set this to True, we add a colour for the edge. In this case we use the same colour as we use for the whole shape. The alpha value can be adjusted to add some transparency to the shape. This can help if there are any overlaps in the shapes or just to make the colours less intense. Finally, we add a fill colour." }, { "code": null, "e": 10621, "s": 10482, "text": "The polygons can now be added to the plot with the add_line() function. The gca() function Gets the Current Axis of a plot or creates one." }, { "code": null, "e": 10666, "s": 10621, "text": "plt.gca().add_line(l1)plt.gca().add_line(l2)" }, { "code": null, "e": 10684, "s": 10666, "text": "Finishing touches" }, { "code": null, "e": 10830, "s": 10684, "text": "Finally, after looping through all columns and adding species Kite shapes, we can add additional features to the entire plot after the main loop." }, { "code": null, "e": 10942, "s": 10830, "text": "plt.yticks(start_points, y_values)plt.xlabel(axis_labs[0])plt.ylabel(axis_labs[1])plt.axis('scaled')plt.show();" }, { "code": null, "e": 11499, "s": 10942, "text": "Recall that we added the column names (species) to a variable called y_values, we can add these names to the start_points locations we stored using the yticks() function to line up the species names with the baselines. The next 2 lines add labels for the x axis and y axis which we pass into the function in a list. The ‘axis scaled’ option changes the dimensions of the plot container rather than the data limits. The other option that can be used is ‘equal’ so that the x,y points have equal increments. Finally, the show() function will render the plot." }, { "code": null, "e": 11606, "s": 11499, "text": "Lastly, to draw the plot we need to call the function providing the dataset and x/y axis labels in a list." }, { "code": null, "e": 11656, "s": 11606, "text": "kite_diagram(kite_data, ['Distance', 'Species']);" }, { "code": null, "e": 11725, "s": 11656, "text": "This output can be seen side-by-side next to the hand drawn version:" }, { "code": null, "e": 11775, "s": 11725, "text": "The code for the full function can be seen below:" }, { "code": null, "e": 13057, "s": 11775, "text": "def kite_diagram(df, axis_labs): \"\"\"Function to draw a kite diagram.\"\"\" plt.axes() start_points = [] v1 = np.array(df.iloc[:, [0]]) y_values = df.columns y_values = np.delete(y_values, 0) num_cols = len(df.columns) - 1 df_cols = df.iloc[:, 1:len(df.columns)] max_val = max(df_cols.max()) for j in range(1, num_cols + 1): p1 = [] p2 = [] v2 = np.array(df.iloc[:, [j]]) / 2 if j == 1: start_point = max_val / 2 else: start_point = start_point + max_val start_points.append(start_point) p1.append([0, start_point]) p2.append([0, start_point]) for i in range(0, len(v1)): p1.append([v1[i], start_point + v2[i]]) p2.append([v1[i], start_point - v2[i]]) p1.append([v1[i], start_point]) p2.append([v1[i], start_point]) c = np.random.rand(3,) l1 = plt.Polygon(p1, closed=None, fill=True, edgecolor=c, alpha=0.4, color=c) l2 = plt.Polygon(p2, closed=None, fill=True, edgecolor=c, alpha=0.4, color=c) plt.gca().add_line(l1) plt.gca().add_line(l2) plt.yticks(start_points, y_values) plt.xlabel(axis_labs[0]) plt.ylabel(axis_labs[1]) plt.axis('scaled') plt.show();" }, { "code": null, "e": 13546, "s": 13057, "text": "Python has a wide variety of visualisations available through libraries such as matplotlib, seaborn, ggplot etc. these libraries can also be easily extended to add additional types of visualisation, as seen here. This provides a rich basis for scientific visualisation in multiple scientific fields. Modern languages with support for data science such as R and Python encourage the development of such visualisations, providing the tools to make such plots relatively simple to implement." }, { "code": null, "e": 13557, "s": 13546, "text": "References" }, { "code": null, "e": 13696, "s": 13557, "text": "[1] Luke, K (2019) Best Excel Tutorial: Kite Chart [online]. Accessed: 07–07–2020 https://best-excel-tutorial.com/56-charts/267-kite-chart" }, { "code": null, "e": 13814, "s": 13696, "text": "[2] Hood, D (2014) RPubs: Kite Graphs in R [online]. Accessed: 07–07–2020 https://rpubs.com/thoughtfulbloke/kitegraph" } ]
Call a method on a Super Class in Scala - GeeksforGeeks
05 Aug, 2019 This concept is used when we want to call super class method. So whenever a base and subclass have same named methods then to resolve ambiguity we use super keyword to call base class method. The keyword “super” came into this with the concept of Inheritance. Below is the example of call a method on a superclass. Example #1: // Scala program to call a method// on a superclass in Scala /* Base class ComputerScience */class ComputerScience{ def read { println("I'm reading") } def write { println("I'm writing") }} /* Subclass Scala */class Scala extends ComputerScience{ // Note that readThanWrite() is only in Scala class def readThanWrite() { // Will invoke or call parent class read() method super.read // Will invoke or call parent class write() method super.write }} // Creating object object Geeks{ // Main method def main(args: Array[String]) { var ob = new Scala(); // Calling readThanWrite() of Scala ob.readThanWrite(); } } I'm reading I'm writing In above example, we are calling multiple method of super class by using super keyword. Example #2: // Scala program to call a method// on a superclass in Scala /* Super class Person */class Person { def message() { println("This is person class"); } } /* Subclass Student */class Student extends Person { override def message() { println("This is student class") } // Note that display() is only in Student class def display() { // will invoke or call current class message() method message () // will invoke or call parent class message() method super.message } } /* Creating object */object Geeks{ // Main method def main(args: Array[String]) { var s = new Student(); // Calling display() of Student s.display(); } } This is student class This is person class In the above example, we have seen that if we only call method message() then, the current class message() is invoked but with the use of super keyword, message() of super class could also be invoked. Scala-OOPS Scala Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Hello World in Scala Inheritance in Scala Scala | Option How to install Scala on Windows? Scala Sequence Scala | Traits Scala | Decision Making (if, if-else, Nested if-else, if-else if) Scala ListBuffer Scala Map get() method with example Scala | Case Class and Case Object
[ { "code": null, "e": 24086, "s": 24058, "text": "\n05 Aug, 2019" }, { "code": null, "e": 24346, "s": 24086, "text": "This concept is used when we want to call super class method. So whenever a base and subclass have same named methods then to resolve ambiguity we use super keyword to call base class method. The keyword “super” came into this with the concept of Inheritance." }, { "code": null, "e": 24401, "s": 24346, "text": "Below is the example of call a method on a superclass." }, { "code": null, "e": 24413, "s": 24401, "text": "Example #1:" }, { "code": "// Scala program to call a method// on a superclass in Scala /* Base class ComputerScience */class ComputerScience{ def read { println(\"I'm reading\") } def write { println(\"I'm writing\") }} /* Subclass Scala */class Scala extends ComputerScience{ // Note that readThanWrite() is only in Scala class def readThanWrite() { // Will invoke or call parent class read() method super.read // Will invoke or call parent class write() method super.write }} // Creating object object Geeks{ // Main method def main(args: Array[String]) { var ob = new Scala(); // Calling readThanWrite() of Scala ob.readThanWrite(); } } ", "e": 25160, "s": 24413, "text": null }, { "code": null, "e": 25185, "s": 25160, "text": "I'm reading\nI'm writing\n" }, { "code": null, "e": 25273, "s": 25185, "text": "In above example, we are calling multiple method of super class by using super keyword." }, { "code": null, "e": 25285, "s": 25273, "text": "Example #2:" }, { "code": "// Scala program to call a method// on a superclass in Scala /* Super class Person */class Person { def message() { println(\"This is person class\"); } } /* Subclass Student */class Student extends Person { override def message() { println(\"This is student class\") } // Note that display() is only in Student class def display() { // will invoke or call current class message() method message () // will invoke or call parent class message() method super.message } } /* Creating object */object Geeks{ // Main method def main(args: Array[String]) { var s = new Student(); // Calling display() of Student s.display(); } } ", "e": 26055, "s": 25285, "text": null }, { "code": null, "e": 26099, "s": 26055, "text": "This is student class\nThis is person class\n" }, { "code": null, "e": 26300, "s": 26099, "text": "In the above example, we have seen that if we only call method message() then, the current class message() is invoked but with the use of super keyword, message() of super class could also be invoked." }, { "code": null, "e": 26311, "s": 26300, "text": "Scala-OOPS" }, { "code": null, "e": 26317, "s": 26311, "text": "Scala" }, { "code": null, "e": 26415, "s": 26317, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26424, "s": 26415, "text": "Comments" }, { "code": null, "e": 26437, "s": 26424, "text": "Old Comments" }, { "code": null, "e": 26458, "s": 26437, "text": "Hello World in Scala" }, { "code": null, "e": 26479, "s": 26458, "text": "Inheritance in Scala" }, { "code": null, "e": 26494, "s": 26479, "text": "Scala | Option" }, { "code": null, "e": 26527, "s": 26494, "text": "How to install Scala on Windows?" }, { "code": null, "e": 26542, "s": 26527, "text": "Scala Sequence" }, { "code": null, "e": 26557, "s": 26542, "text": "Scala | Traits" }, { "code": null, "e": 26623, "s": 26557, "text": "Scala | Decision Making (if, if-else, Nested if-else, if-else if)" }, { "code": null, "e": 26640, "s": 26623, "text": "Scala ListBuffer" }, { "code": null, "e": 26676, "s": 26640, "text": "Scala Map get() method with example" } ]
Lucy's Neighbours | Practice | GeeksforGeeks
Lucy lives in house number X. She has a list of N house numbers in the society. Distance between houses can be determined by studying the difference between house numbers. Help her find out K closest neighbors. Note: If two houses are equidistant and Lucy has to pick only one, the house with the smaller house number is given preference. Example 1: Input: N = 5, X = 0, K = 4 a[] = {-21, 21, 4, -12, 20}, Output: -21 -12 4 20 Explanation: The closest neighbour is house number 4. Followed by -12 and 20. -21 and 21 are both equal distance from X=0. Therefore, Lucy can only pick 1. Based on the given condition she picks -21 as it is the smaller of the two. Example 2: Input: N = 6, X = 5, K = 3 a[] = {10, 2, 14, 4, 7, 6}, Output: 4 6 7 Your Task: You don't need to read input or print anything. Complete the function Kclosest() which takes the array arr[], size of array N, X, and K as input parameters, and returns the list of numbers in sorted order. Expected Time Complexity: O(NlogN) Expected Auxiliary Space: O(N) Constraints: 1 ≤ K ≤ N ≤ 105 -104 ≤ X, arr[i] ≤ 104 0 artistdarkangel1 month ago Java Solution | All test Case passed Expected Time Complexity: O(NlogN)Expected Auxiliary Space: O(N) class Solution { public ArrayList<Integer> Kclosest(int arr[], int n, int x, int k) { ArrayList<Integer> arL = new ArrayList<Integer>(); PriorityQueue<Integer> pq = new PriorityQueue<Integer>(); HashSet<Integer> hs = new HashSet<Integer>(); Arrays.sort(arr); for(int i=0; i<n; i++) { pq.add(Math.abs(arr[i]-x)); hs.add(arr[i]); } for(int i=0; i<k; i++) { Integer temp=pq.poll(); if(hs.contains(x-temp)) { arL.add(x-temp); hs.remove(x-temp); } else { int a=temp+x; if(hs.contains(a)) { arL.add(a); } } } Collections.sort(arL); return arL;}} 0 shahabuddinbravo401 month ago class Solution{ public: vector<int> Kclosest(vector<int>arr, int n, int x, int k) { vector<pair<int,int>>vp; for(int i=0;i<n;i++){ vp.push_back({abs(arr[i]-x),arr[i]}); } sort(vp.begin(),vp.end()); vector<int>ans; for(int i=0;i<k;i++){ ans.push_back(vp[i].second); } sort(ans.begin(),ans.end()); return ans; } }; +1 himanshukug19cs2 months ago java soluuttion class pair implements Comparable<pair>{ int hn; int d; pair(int hn,int d){ this.hn=hn; this.d=d; }public int compareTo(pair o){if(this.d==o.d) return this.hn-o.hn;else return this.d-o.d;} }public ArrayList<Integer> Kclosest(int arr[], int n, int x, int k) { // Your code goes here ArrayList<Integer> al = new ArrayList<Integer>(); PriorityQueue<pair> pq = new PriorityQueue<>(); for(int i=0;i<n;i++){ pair p = new pair(arr[i],Math.abs(x-arr[i])); pq.add(p); } for(int i=0;i<k;i++){ al.add(pq.poll().hn); } Collections.sort(al); return al;}} -1 darshitagupta3 months ago vector<int> Kclosest(vector<int>arr, int n, int x, int k) { // Your code goes here priority_queue<pair<int,int>>maxh; vector<int>v; for(int i=0;i<n;i++) { maxh.push({abs(arr[i]-x),arr[i]}); if(maxh.size()>k) maxh.pop(); } while(maxh.size()>0) { int temp=maxh.top().second; v.push_back(temp); maxh.pop(); } sort(v.begin(),v.end()); return v; } +1 abhixhek053 months ago EASY TO UNDERSTAND C++ CODE, DONE USING MAX HEAP (PRIORITY QUEUE). BASICALLY WE NEED TO FIND K CLOSEST ELEMENTS. TC is O(Nlogk + klogk) vector<int> Kclosest(vector<int>arr, int n, int x, int k) { // Your code goes here priority_queue<pair<int,int>> q; for(int i=0;i<arr.size();i++){ q.push({abs(arr[i]-x),arr[i],}); if(q.size()>k) q.pop(); } vector<int> ans; while(q.size()){ ans.push_back(q.top().second); q.pop(); } sort(ans.begin(),ans.end()); return ans; } UPVOTE IF FOUND USEFULL 🍕🍕🍕 0 rishabh20183 months ago 0 raunakmishra12435 months ago class Solution{ public: vector<int> Kclosest(vector<int>arr, int n, int x, int k) { vector<int>v; priority_queue<pair<int,int>>maxh; for(int i=0;i<n;i++) { maxh.push({abs(x-arr[i]),arr[i]}); if(maxh.size()>k) maxh.pop(); } while(maxh.size()>0) { pair<int,int>p; p=maxh.top(); v.push_back(p.second); maxh.pop(); } sort(v.begin(),v.end()); return v; } }; 0 ssingh5be195 months ago vector<int> Kclosest(vector<int>arr, int n, int x, int k) { // Your code goes here priority_queue<pair<int,int>> q; for(int i=0;i<n;i++) { q.push(make_pair(abs(x-arr[i]),arr[i])); if(q.size()>k) q.pop(); } // while(!q.empty()) // { // cout<<q.top().first<<" "<<q.top().second<<endl; // q.pop(); // } vector<int> v; set<int> s; while(!q.empty()) { s.insert(q.top().second); q.pop(); } for(auto i:s) { v.push_back(i); } return v; } 0 Jay Kishan1 year ago Jay Kishan class Solution { public ArrayList<integer> Kclosest(int arr[], int n, int x, int k) { int temp[] = new int[n]; Arrays.sort(arr); for(int i=0;i<arr.length;i++){ temp[i]="Math.abs(arr[i]-x);" }="" arrays.sort(temp);="" int="" s="0;" arraylist<integer=""> list = new ArrayList<>(); while(s<k){ for(int="" i="0;i&lt;arr.length;i++){" if(temp[s]="=Math.abs(arr[i]-x)){" list.add(arr[i]);="" arr[i]="Integer.MAX_VALUE;" s++;="" i="arr.length;" }="" }="" }="" collections.sort(list);="" return="" list;="" }="" }=""> 0 Well Fried This comment was deleted. 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": 577, "s": 238, "text": "Lucy lives in house number X. She has a list of N house numbers in the society. Distance between houses can be determined by studying the difference between house numbers. Help her find out K closest neighbors.\nNote: If two houses are equidistant and Lucy has to pick only one, the house with the smaller house number is given preference." }, { "code": null, "e": 588, "s": 577, "text": "Example 1:" }, { "code": null, "e": 904, "s": 588, "text": "Input:\nN = 5, X = 0, K = 4\na[] = {-21, 21, 4, -12, 20}, \nOutput:\n-21 -12 4 20\nExplanation:\nThe closest neighbour is house\nnumber 4. Followed by -12 and 20. -21 and 21 \nare both equal distance from X=0. Therefore, \nLucy can only pick 1. Based on the given \ncondition she picks -21 as it is the smaller \nof the two. \n" }, { "code": null, "e": 915, "s": 904, "text": "Example 2:" }, { "code": null, "e": 987, "s": 915, "text": "Input:\nN = 6, X = 5, K = 3 \na[] = {10, 2, 14, 4, 7, 6},\nOutput:\n4 6 7 \n" }, { "code": null, "e": 1207, "s": 987, "text": "Your Task: \nYou don't need to read input or print anything. Complete the function Kclosest() which takes the array arr[], size of array N, X, and K as input parameters, and returns the list of numbers in sorted order." }, { "code": null, "e": 1273, "s": 1207, "text": "Expected Time Complexity: O(NlogN)\nExpected Auxiliary Space: O(N)" }, { "code": null, "e": 1326, "s": 1273, "text": "Constraints:\n1 ≤ K ≤ N ≤ 105 \n-104 ≤ X, arr[i] ≤ 104" }, { "code": null, "e": 1328, "s": 1326, "text": "0" }, { "code": null, "e": 1355, "s": 1328, "text": "artistdarkangel1 month ago" }, { "code": null, "e": 1392, "s": 1355, "text": "Java Solution | All test Case passed" }, { "code": null, "e": 1457, "s": 1392, "text": "Expected Time Complexity: O(NlogN)Expected Auxiliary Space: O(N)" }, { "code": null, "e": 2152, "s": 1461, "text": "class Solution { public ArrayList<Integer> Kclosest(int arr[], int n, int x, int k) { ArrayList<Integer> arL = new ArrayList<Integer>(); PriorityQueue<Integer> pq = new PriorityQueue<Integer>(); HashSet<Integer> hs = new HashSet<Integer>(); Arrays.sort(arr); for(int i=0; i<n; i++) { pq.add(Math.abs(arr[i]-x)); hs.add(arr[i]); } for(int i=0; i<k; i++) { Integer temp=pq.poll(); if(hs.contains(x-temp)) { arL.add(x-temp); hs.remove(x-temp); } else { int a=temp+x; if(hs.contains(a)) { arL.add(a); } } } Collections.sort(arL); return arL;}}" }, { "code": null, "e": 2154, "s": 2152, "text": "0" }, { "code": null, "e": 2184, "s": 2154, "text": "shahabuddinbravo401 month ago" }, { "code": null, "e": 2589, "s": 2184, "text": "class Solution{ public: vector<int> Kclosest(vector<int>arr, int n, int x, int k) { vector<pair<int,int>>vp; for(int i=0;i<n;i++){ vp.push_back({abs(arr[i]-x),arr[i]}); } sort(vp.begin(),vp.end()); vector<int>ans; for(int i=0;i<k;i++){ ans.push_back(vp[i].second); } sort(ans.begin(),ans.end()); return ans; } };" }, { "code": null, "e": 2592, "s": 2589, "text": "+1" }, { "code": null, "e": 2620, "s": 2592, "text": "himanshukug19cs2 months ago" }, { "code": null, "e": 2636, "s": 2620, "text": "java soluuttion" }, { "code": null, "e": 3258, "s": 2638, "text": "class pair implements Comparable<pair>{ int hn; int d; pair(int hn,int d){ this.hn=hn; this.d=d; }public int compareTo(pair o){if(this.d==o.d) return this.hn-o.hn;else return this.d-o.d;} }public ArrayList<Integer> Kclosest(int arr[], int n, int x, int k) { // Your code goes here ArrayList<Integer> al = new ArrayList<Integer>(); PriorityQueue<pair> pq = new PriorityQueue<>(); for(int i=0;i<n;i++){ pair p = new pair(arr[i],Math.abs(x-arr[i])); pq.add(p); } for(int i=0;i<k;i++){ al.add(pq.poll().hn); } Collections.sort(al); return al;}} " }, { "code": null, "e": 3261, "s": 3258, "text": "-1" }, { "code": null, "e": 3287, "s": 3261, "text": "darshitagupta3 months ago" }, { "code": null, "e": 3779, "s": 3287, "text": "vector<int> Kclosest(vector<int>arr, int n, int x, int k) { // Your code goes here priority_queue<pair<int,int>>maxh; vector<int>v; for(int i=0;i<n;i++) { maxh.push({abs(arr[i]-x),arr[i]}); if(maxh.size()>k) maxh.pop(); } while(maxh.size()>0) { int temp=maxh.top().second; v.push_back(temp); maxh.pop(); } sort(v.begin(),v.end()); return v; } " }, { "code": null, "e": 3784, "s": 3781, "text": "+1" }, { "code": null, "e": 3807, "s": 3784, "text": "abhixhek053 months ago" }, { "code": null, "e": 3874, "s": 3807, "text": "EASY TO UNDERSTAND C++ CODE, DONE USING MAX HEAP (PRIORITY QUEUE)." }, { "code": null, "e": 3920, "s": 3874, "text": "BASICALLY WE NEED TO FIND K CLOSEST ELEMENTS." }, { "code": null, "e": 3945, "s": 3922, "text": "TC is O(Nlogk + klogk)" }, { "code": null, "e": 4431, "s": 3947, "text": "vector<int> Kclosest(vector<int>arr, int n, int x, int k) \n { \n // Your code goes here \n priority_queue<pair<int,int>> q;\n for(int i=0;i<arr.size();i++){\n q.push({abs(arr[i]-x),arr[i],});\n if(q.size()>k) q.pop();\n }\n vector<int> ans;\n while(q.size()){\n \n ans.push_back(q.top().second);\n q.pop();\n \n }\n sort(ans.begin(),ans.end());\n return ans;\n } " }, { "code": null, "e": 4459, "s": 4431, "text": "UPVOTE IF FOUND USEFULL 🍕🍕🍕" }, { "code": null, "e": 4461, "s": 4459, "text": "0" }, { "code": null, "e": 4485, "s": 4461, "text": "rishabh20183 months ago" }, { "code": null, "e": 4487, "s": 4485, "text": "0" }, { "code": null, "e": 4516, "s": 4487, "text": "raunakmishra12435 months ago" }, { "code": null, "e": 5053, "s": 4516, "text": "class Solution{\n public:\n vector<int> Kclosest(vector<int>arr, int n, int x, int k) \n { \n vector<int>v;\n priority_queue<pair<int,int>>maxh;\n for(int i=0;i<n;i++)\n {\n maxh.push({abs(x-arr[i]),arr[i]});\n if(maxh.size()>k)\n maxh.pop();\n }\n while(maxh.size()>0)\n {\n pair<int,int>p;\n p=maxh.top();\n v.push_back(p.second);\n maxh.pop();\n }\n sort(v.begin(),v.end());\n return v;\n } \n};" }, { "code": null, "e": 5055, "s": 5053, "text": "0" }, { "code": null, "e": 5079, "s": 5055, "text": "ssingh5be195 months ago" }, { "code": null, "e": 5702, "s": 5079, "text": " vector<int> Kclosest(vector<int>arr, int n, int x, int k) { // Your code goes here priority_queue<pair<int,int>> q; for(int i=0;i<n;i++) { q.push(make_pair(abs(x-arr[i]),arr[i])); if(q.size()>k) q.pop(); } // while(!q.empty()) // { // cout<<q.top().first<<\" \"<<q.top().second<<endl; // q.pop(); // } vector<int> v; set<int> s; while(!q.empty()) { s.insert(q.top().second); q.pop(); } for(auto i:s) { v.push_back(i); } return v; } " }, { "code": null, "e": 5704, "s": 5702, "text": "0" }, { "code": null, "e": 5725, "s": 5704, "text": "Jay Kishan1 year ago" }, { "code": null, "e": 5736, "s": 5725, "text": "Jay Kishan" }, { "code": null, "e": 6259, "s": 5736, "text": "class Solution { public ArrayList<integer> Kclosest(int arr[], int n, int x, int k) { int temp[] = new int[n]; Arrays.sort(arr); for(int i=0;i<arr.length;i++){ temp[i]=\"Math.abs(arr[i]-x);\" }=\"\" arrays.sort(temp);=\"\" int=\"\" s=\"0;\" arraylist<integer=\"\"> list = new ArrayList<>(); while(s<k){ for(int=\"\" i=\"0;i&lt;arr.length;i++){\" if(temp[s]=\"=Math.abs(arr[i]-x)){\" list.add(arr[i]);=\"\" arr[i]=\"Integer.MAX_VALUE;\" s++;=\"\" i=\"arr.length;\" }=\"\" }=\"\" }=\"\" collections.sort(list);=\"\" return=\"\" list;=\"\" }=\"\" }=\"\">" }, { "code": null, "e": 6261, "s": 6259, "text": "0" }, { "code": null, "e": 6272, "s": 6261, "text": "Well Fried" }, { "code": null, "e": 6298, "s": 6272, "text": "This comment was deleted." }, { "code": null, "e": 6444, "s": 6298, "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": 6480, "s": 6444, "text": " Login to access your submissions. " }, { "code": null, "e": 6490, "s": 6480, "text": "\nProblem\n" }, { "code": null, "e": 6500, "s": 6490, "text": "\nContest\n" }, { "code": null, "e": 6563, "s": 6500, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 6711, "s": 6563, "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": 6919, "s": 6711, "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": 7025, "s": 6919, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
How to Create Button in React-Native App ?
27 Apr, 2020 In this article, we will see how to create buttons in react-native, their syntax, and different types of buttons available in react native. Creating a Button in react native is very simple. First, we have to import the button component from React Native. import { Button } from 'react-native' If you are not familiar with components of react native, then you can check out introductory article on React Native Syntax: import React, { Component } from 'react'import { Button } from 'react-native'const Test = () => { return( <Button // Define Button property /> )}export default Test The above syntax shows how a button is used in react native. It involves defining an XML tag with a button element, now according to our requirement different properties can be defined for a button. Types of Button in React Native There are five types of Buttons which are listed below: Basic Types: These fall into the basic category and can be of the following types:Button: It is used for defining click buttons.Submit: This type of button is used along with a form to submit details.Reset: It is used to clear field contents on click of it.Flat Button: It has a style of no background color. To create a flat button in react, set CSS class to e-flat.Outline Button: This type of button contains a border with a transparent background. To create this type of button, set the CSS class as an e-outline.Round Button: This button is in a circular shape. To create a round button set CSS class to e-round.Toggle Button: Toggle button is a button whose state can be changed. Let us consider an example of a play and pause button. On Click of this button, its state is changed and after another click, it regains its original state. This state change function is achieved by click event of the button. To create a toggle we need to set isToggle property to true. Basic Types: These fall into the basic category and can be of the following types:Button: It is used for defining click buttons.Submit: This type of button is used along with a form to submit details.Reset: It is used to clear field contents on click of it. Button: It is used for defining click buttons. Submit: This type of button is used along with a form to submit details. Reset: It is used to clear field contents on click of it. Flat Button: It has a style of no background color. To create a flat button in react, set CSS class to e-flat. Outline Button: This type of button contains a border with a transparent background. To create this type of button, set the CSS class as an e-outline. Round Button: This button is in a circular shape. To create a round button set CSS class to e-round. Toggle Button: Toggle button is a button whose state can be changed. Let us consider an example of a play and pause button. On Click of this button, its state is changed and after another click, it regains its original state. This state change function is achieved by click event of the button. To create a toggle we need to set isToggle property to true. Steps to create Buttons: Write and export the code to make the button and put it in a reusable component. Import that component into the App.js file. Put that button in your file the same as any other component. Add some styling in the button file. Complete code to create a Button in React Native: import React from 'react'; // Import the essential components from react-nativeimport { StyleSheet, Button, View, SafeAreaView, Text, Alert} from 'react-native'; // Function for creating buttonexport default function App() { return ( <View style={styles.container}> // Create a button <Button // Some properties given to Button title="Geeks" onPress={() => Alert.alert( 'Its GeeksforGeeks !')} /> </View> );} // Some styles given to buttonconst styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#71EC4C', alignItems: 'center', justifyContent: 'center', },}); Output: Before Click on Button: After Click on Button: Steps to Run Project: Go to your project folder and type the following command on the terminal. The following command create your project.react-native init MyAppName react-native init MyAppName Select App.js file and Paste the project code (complete code of project given above) then save the file. Start an emulator to run the project. The following command will launch the emulator.emulator -avd MyAVD emulator -avd MyAVD Now, use run the project using the following command.react-native run-android react-native run-android Another approach to Run Project: Open the terminal and jump into your project folder.cd ProjectName cd ProjectName To run the project on Expo type the following command in your terminal.expo start expo start Scan the Expo App Bar Code in your Expo App in your Mobile. react-js JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n27 Apr, 2020" }, { "code": null, "e": 194, "s": 54, "text": "In this article, we will see how to create buttons in react-native, their syntax, and different types of buttons available in react native." }, { "code": null, "e": 309, "s": 194, "text": "Creating a Button in react native is very simple. First, we have to import the button component from React Native." }, { "code": null, "e": 347, "s": 309, "text": "import { Button } from 'react-native'" }, { "code": null, "e": 464, "s": 347, "text": "If you are not familiar with components of react native, then you can check out introductory article on React Native" }, { "code": null, "e": 472, "s": 464, "text": "Syntax:" }, { "code": "import React, { Component } from 'react'import { Button } from 'react-native'const Test = () => { return( <Button // Define Button property /> )}export default Test", "e": 669, "s": 472, "text": null }, { "code": null, "e": 868, "s": 669, "text": "The above syntax shows how a button is used in react native. It involves defining an XML tag with a button element, now according to our requirement different properties can be defined for a button." }, { "code": null, "e": 956, "s": 868, "text": "Types of Button in React Native There are five types of Buttons which are listed below:" }, { "code": null, "e": 1929, "s": 956, "text": "Basic Types: These fall into the basic category and can be of the following types:Button: It is used for defining click buttons.Submit: This type of button is used along with a form to submit details.Reset: It is used to clear field contents on click of it.Flat Button: It has a style of no background color. To create a flat button in react, set CSS class to e-flat.Outline Button: This type of button contains a border with a transparent background. To create this type of button, set the CSS class as an e-outline.Round Button: This button is in a circular shape. To create a round button set CSS class to e-round.Toggle Button: Toggle button is a button whose state can be changed. Let us consider an example of a play and pause button. On Click of this button, its state is changed and after another click, it regains its original state. This state change function is achieved by click event of the button. To create a toggle we need to set isToggle property to true." }, { "code": null, "e": 2187, "s": 1929, "text": "Basic Types: These fall into the basic category and can be of the following types:Button: It is used for defining click buttons.Submit: This type of button is used along with a form to submit details.Reset: It is used to clear field contents on click of it." }, { "code": null, "e": 2234, "s": 2187, "text": "Button: It is used for defining click buttons." }, { "code": null, "e": 2307, "s": 2234, "text": "Submit: This type of button is used along with a form to submit details." }, { "code": null, "e": 2365, "s": 2307, "text": "Reset: It is used to clear field contents on click of it." }, { "code": null, "e": 2476, "s": 2365, "text": "Flat Button: It has a style of no background color. To create a flat button in react, set CSS class to e-flat." }, { "code": null, "e": 2627, "s": 2476, "text": "Outline Button: This type of button contains a border with a transparent background. To create this type of button, set the CSS class as an e-outline." }, { "code": null, "e": 2728, "s": 2627, "text": "Round Button: This button is in a circular shape. To create a round button set CSS class to e-round." }, { "code": null, "e": 3084, "s": 2728, "text": "Toggle Button: Toggle button is a button whose state can be changed. Let us consider an example of a play and pause button. On Click of this button, its state is changed and after another click, it regains its original state. This state change function is achieved by click event of the button. To create a toggle we need to set isToggle property to true." }, { "code": null, "e": 3109, "s": 3084, "text": "Steps to create Buttons:" }, { "code": null, "e": 3190, "s": 3109, "text": "Write and export the code to make the button and put it in a reusable component." }, { "code": null, "e": 3234, "s": 3190, "text": "Import that component into the App.js file." }, { "code": null, "e": 3296, "s": 3234, "text": "Put that button in your file the same as any other component." }, { "code": null, "e": 3333, "s": 3296, "text": "Add some styling in the button file." }, { "code": null, "e": 3383, "s": 3333, "text": "Complete code to create a Button in React Native:" }, { "code": "import React from 'react'; // Import the essential components from react-nativeimport { StyleSheet, Button, View, SafeAreaView, Text, Alert} from 'react-native'; // Function for creating buttonexport default function App() { return ( <View style={styles.container}> // Create a button <Button // Some properties given to Button title=\"Geeks\" onPress={() => Alert.alert( 'Its GeeksforGeeks !')} /> </View> );} // Some styles given to buttonconst styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#71EC4C', alignItems: 'center', justifyContent: 'center', },});", "e": 4125, "s": 3383, "text": null }, { "code": null, "e": 4133, "s": 4125, "text": "Output:" }, { "code": null, "e": 4157, "s": 4133, "text": "Before Click on Button:" }, { "code": null, "e": 4180, "s": 4157, "text": "After Click on Button:" }, { "code": null, "e": 4202, "s": 4180, "text": "Steps to Run Project:" }, { "code": null, "e": 4346, "s": 4202, "text": "Go to your project folder and type the following command on the terminal. The following command create your project.react-native init MyAppName" }, { "code": null, "e": 4374, "s": 4346, "text": "react-native init MyAppName" }, { "code": null, "e": 4479, "s": 4374, "text": "Select App.js file and Paste the project code (complete code of project given above) then save the file." }, { "code": null, "e": 4584, "s": 4479, "text": "Start an emulator to run the project. The following command will launch the emulator.emulator -avd MyAVD" }, { "code": null, "e": 4604, "s": 4584, "text": "emulator -avd MyAVD" }, { "code": null, "e": 4682, "s": 4604, "text": "Now, use run the project using the following command.react-native run-android" }, { "code": null, "e": 4707, "s": 4682, "text": "react-native run-android" }, { "code": null, "e": 4740, "s": 4707, "text": "Another approach to Run Project:" }, { "code": null, "e": 4807, "s": 4740, "text": "Open the terminal and jump into your project folder.cd ProjectName" }, { "code": null, "e": 4822, "s": 4807, "text": "cd ProjectName" }, { "code": null, "e": 4904, "s": 4822, "text": "To run the project on Expo type the following command in your terminal.expo start" }, { "code": null, "e": 4915, "s": 4904, "text": "expo start" }, { "code": null, "e": 4975, "s": 4915, "text": "Scan the Expo App Bar Code in your Expo App in your Mobile." }, { "code": null, "e": 4984, "s": 4975, "text": "react-js" }, { "code": null, "e": 4995, "s": 4984, "text": "JavaScript" }, { "code": null, "e": 5012, "s": 4995, "text": "Web Technologies" }, { "code": null, "e": 5039, "s": 5012, "text": "Web technologies Questions" } ]
gpg - Unix, Linux Command
gpg [--homedir name] [--options file] [options] command [args] gpg is the main program for the GnuPG system. This man page only lists the commands and options available. For more verbose documentation get the GNU Privacy Handbook (GPH) or one of the other documents at http://www.gnupg.org/documentation/ . Please remember that option parsing stops as soon as a non option is encountered, you can explicitly stop option parsing by using the special option "--". gpg may be run with no commands, in which case it will perform a reasonable action depending on the type of file it is given as input (an encrypted message is decrypted, a signature is verified, a file containing keys is listed). gpg recognizes these commands: See the option --simple-sk-checksum if you want to import such an exported key with an older OpenPGP implementation. Long options can be put in an options file (default "~/.gnupg/gpg.conf"). Short option names will not work - for example, "armor" is a valid option for the options file, while "a" is not. Do not write the 2 dashes, but simply the name of the option and any required arguments. Lines with a hash (’#’) as the first non-white-space character are ignored. Commands may be put in this file too, but that is not generally useful as the command will execute automatically with every execution of gpg. gpg recognizes these options: There are different ways to specify a user ID to GnuPG; here are some examples: The program returns 0 if everything was fine, 1 if at least a signature was bad, and other error codes for fatal errors. Use a *good* password for your user account and a *good* passphrase to protect your secret key. This passphrase is the weakest part of the whole system. Programs to do dictionary attacks on your secret keyring are very easy to write and so you should protect your "~/.gnupg/" directory very well. Keep in mind that, if this program is used over a network (telnet), it is *very* easy to spy out your passphrase! If you are going to verify detached signatures, make sure that the program knows about it; either give both filenames on the command line or use - to specify stdin. GnuPG tries to be a very flexible implementation of the OpenPGP standard. In particular, GnuPG implements many of the optional parts of the standard, such as the SHA-512 hash, and the ZLIB and BZIP2 compression algorithms. It is important to be aware that not all OpenPGP programs implement these optional algorithms and that by forcing their use via the --cipher-algo, --digest-algo, --cert-digest-algo, or --compress-algo options in GnuPG, it is possible to create a perfectly valid OpenPGP message, but one that cannot be read by the intended recipient. There are dozens of variations of OpenPGP programs available, and each supports a slightly different subset of these optional algorithms. For example, until recently, no (unhacked) version of PGP supported the BLOWFISH cipher algorithm. A message using BLOWFISH simply could not be read by a PGP user. By default, GnuPG uses the standard OpenPGP preferences system that will always do the right thing and create messages that are usable by all recipients, regardless of which OpenPGP program they use. Only override this safe default if you really know what you are doing. If you absolutely must override the safe default, or if the preferences on a given key are invalid for some reason, you are far better off using the --pgp6, --pgp7, or --pgp8 options. These options are safe as they do not force any particular algorithms in violation of OpenPGP, but rather reduce the available algorithms to a "PGP-safe" list. GPG (GNU Privacy Guard) is a public key cryptography implementation. It allows for the secure transmission of information and can be used to verify that the origin of a message is genuine. Below are few examples of usage. $ gpg --gen-key $ gpg --gen-revoke [email protected] $ gpg --import public_key_file $ gpg --sign-key [email protected] $ gpg --export --armor [email protected] $ gpg --import signed_key_file_name $ gpg --list-keys $ gpg --list-secret-keys $ gpg --refresh-keys $ gpg --encrypt --recipient [email protected] file.txt $ gpg --encrypt --recipient [email protected] --recepient [email protected] file.txt $ gpg --encrypt --recipient [email protected] file.txt $ gpg --decrypt encrypted_file.txt.gpg $ gpg encrypted_file.gpg
[ { "code": null, "e": 10785, "s": 10713, "text": "gpg [--homedir name] [--options file] [options] command [args] \n" }, { "code": null, "e": 10833, "s": 10785, "text": "\ngpg is the main program for the GnuPG system.\n" }, { "code": null, "e": 11036, "s": 10835, "text": "\nThis man page only lists the commands and options available. For more\nverbose documentation get the GNU Privacy Handbook (GPH) or one of the\nother documents at http://www.gnupg.org/documentation/ .\n" }, { "code": null, "e": 11193, "s": 11036, "text": "\nPlease remember that option parsing stops as soon as a non option is\nencountered, you can explicitly stop option parsing by using the\nspecial option \"--\".\n" }, { "code": null, "e": 11425, "s": 11193, "text": "\ngpg may be run with no commands, in which case it will\nperform a reasonable action depending on the type of file it is given\nas input (an encrypted message is decrypted, a signature is verified,\na file containing keys is listed).\n" }, { "code": null, "e": 11458, "s": 11425, "text": "\ngpg recognizes these commands:\n" }, { "code": null, "e": 11577, "s": 11458, "text": "\nSee the option --simple-sk-checksum if you want to import such an\nexported key with an older OpenPGP implementation.\n" }, { "code": null, "e": 12078, "s": 11577, "text": "\nLong options can be put in an options file (default\n\"~/.gnupg/gpg.conf\"). Short option names will not work - for example,\n\"armor\" is a valid option for the options file, while \"a\" is not. Do\nnot write the 2 dashes, but simply the name of the option and any\nrequired arguments. Lines with a hash (’#’) as the first\nnon-white-space character are ignored. Commands may be put in this\nfile too, but that is not generally useful as the command will execute\nautomatically with every execution of gpg.\n" }, { "code": null, "e": 12110, "s": 12078, "text": "\ngpg recognizes these options:\n" }, { "code": null, "e": 12196, "s": 12114, "text": "\nThere are different ways to specify a user ID to GnuPG; here are some\nexamples:\n" }, { "code": null, "e": 12323, "s": 12200, "text": "\nThe program returns 0 if everything was fine, 1 if at least\na signature was bad, and other error codes for fatal errors.\n" }, { "code": null, "e": 12626, "s": 12325, "text": "\nUse a *good* password for your user account and a *good* passphrase\nto protect your secret key. This passphrase is the weakest part of the\nwhole system. Programs to do dictionary attacks on your secret keyring\nare very easy to write and so you should protect your \"~/.gnupg/\"\ndirectory very well.\n" }, { "code": null, "e": 12742, "s": 12626, "text": "\nKeep in mind that, if this program is used over a network (telnet), it\nis *very* easy to spy out your passphrase!\n" }, { "code": null, "e": 12909, "s": 12742, "text": "\nIf you are going to verify detached signatures, make sure that the\nprogram knows about it; either give both filenames on the command line\nor use - to specify stdin.\n" }, { "code": null, "e": 13470, "s": 12909, "text": "\nGnuPG tries to be a very flexible implementation of the OpenPGP\nstandard. In particular, GnuPG implements many of the optional parts\nof the standard, such as the SHA-512 hash, and the ZLIB and BZIP2\ncompression algorithms. It is important to be aware that not all\nOpenPGP programs implement these optional algorithms and that by\nforcing their use via the --cipher-algo, --digest-algo,\n--cert-digest-algo, or --compress-algo options in GnuPG, it is\npossible to create a perfectly valid OpenPGP message, but one that\ncannot be read by the intended recipient.\n" }, { "code": null, "e": 14048, "s": 13470, "text": "\nThere are dozens of variations of OpenPGP programs available, and each\nsupports a slightly different subset of these optional algorithms.\nFor example, until recently, no (unhacked) version of PGP supported\nthe BLOWFISH cipher algorithm. A message using BLOWFISH simply could\nnot be read by a PGP user. By default, GnuPG uses the standard\nOpenPGP preferences system that will always do the right thing and\ncreate messages that are usable by all recipients, regardless of which\nOpenPGP program they use. Only override this safe default if you\nreally know what you are doing.\n" }, { "code": null, "e": 14397, "s": 14048, "text": "\nIf you absolutely must override the safe default, or if the\npreferences on a given key are invalid for some reason, you are far\nbetter off using the --pgp6, --pgp7, or --pgp8 options. These options\nare safe as they do not force any particular algorithms in violation\nof OpenPGP, but rather reduce the available algorithms to a \"PGP-safe\"\nlist.\n\n\n" }, { "code": null, "e": 14619, "s": 14397, "text": "GPG (GNU Privacy Guard) is a public key cryptography implementation.\nIt allows for the secure transmission of information and can be used to\nverify that the origin of a message is genuine. Below are few examples of usage." }, { "code": null, "e": 14636, "s": 14619, "text": "$ gpg --gen-key\n" }, { "code": null, "e": 14676, "s": 14636, "text": "$ gpg --gen-revoke [email protected]\n" }, { "code": null, "e": 14708, "s": 14676, "text": "$ gpg --import public_key_file\n" }, { "code": null, "e": 14750, "s": 14708, "text": "$ gpg --sign-key [email protected]\n" }, { "code": null, "e": 14798, "s": 14750, "text": "$ gpg --export --armor [email protected]\n" }, { "code": null, "e": 14835, "s": 14798, "text": "$ gpg --import signed_key_file_name\n" }, { "code": null, "e": 14854, "s": 14835, "text": "$ gpg --list-keys\n" }, { "code": null, "e": 14880, "s": 14854, "text": "$ gpg --list-secret-keys\n" }, { "code": null, "e": 14902, "s": 14880, "text": "$ gpg --refresh-keys\n" }, { "code": null, "e": 14966, "s": 14902, "text": "$ gpg --encrypt --recipient [email protected] file.txt\n" }, { "code": null, "e": 15073, "s": 14966, "text": "$ gpg --encrypt --recipient [email protected] --recepient [email protected] file.txt\n" }, { "code": null, "e": 15131, "s": 15073, "text": "$ gpg --encrypt --recipient [email protected] file.txt\n" }, { "code": null, "e": 15171, "s": 15131, "text": "$ gpg --decrypt encrypted_file.txt.gpg\n" } ]
How to Apply Different Styles to a Cell in a Spreadsheet using Java?
27 Apr, 2021 Apache POI is a powerful API that enables the user to create, manipulate, and display various file formats based on Microsoft Office using java programs. Using POI, one should be able to perform create, modify, and display/read operations on the following file formats. For Example, Java doesn’t provide built-in support for working with Excel files, so we need to look for open-source APIs for the job. It is an open-source library developed and distributed by Apache Software Foundation to design or modify Microsoft Office files using Java program. It contains classes and methods to decode the user input data or a file into MS Office documents. Here different styles can be applied like fonts, colors, cell merging, alignments, etc. to a cell in Excel using this concept in the Java program. Apache POI Architecture: It consists of various components that make an architecture to form a working system: POIFS (Poor Obfuscation Implementation File System): This component is the basic factor of all other POI elements. It is used to read different files explicitly. HSSF (Horrible Spreadsheet Format): It is used to read and write xls format of MS-Excel files. XSSF (XML Spreadsheet Format): It is used for xlsx file format of MS-Excel. HPSF (Horrible Property Set Format): It is used to extract property sets of the MS-Office files. HWPF (Horrible Word Processor Format): It is used to read and write doc extension files of MS-Word. XWPF (XML Word Processor Format): It is used to read and write Docx extension files of MS-Word. HSLF (Horrible Slide Layout Format): It is used to read, create, and edit PowerPoint presentations. HDGF (Horrible Diagram Format): It contains classes and methods for MS-Visio binary files. HPBF (Horrible Publisher Format): It is used to read and write MS-Publisher files. A Jar file is a Zip archive containing one or multiple java class files. This makes the usage of libraries handier. Directories and Jar files are added to the build path and available to the ClassLoader at runtime to find particular classes inside it. We generally use .jar files to distribute Java applications or libraries, in the form of Java class files and associated metadata and resources (text, images, etc.). One can say JAR = JavaARchive Approach: Step 1: Import the necessary .jar files like HSSF, XML and add them to your build path. Step 2: Create a workbook using “new XSSFWorkbook()” in which we have to create the spreadsheet or the Excel file using “workbook.createSheet(‘Sheet1’)” in which we are going to apply different styles. Step 3: Apply the styles, here merge the cells using the command spreadsheet.addMergedRegion. We have to provide the range addresses of rows and columns as well as its parameter. Step 4: Now the next style in determining the cell alignment. For this, we have two commands“style1.setAlignment(XSSFCellStyle.ALIGN_LEFT)” for determining the alignment and“style1.setVerticalAlignment(XSSFCellStyle.VERTICAL_TOP)” for determining vertical alignment “style1.setAlignment(XSSFCellStyle.ALIGN_LEFT)” for determining the alignment and “style1.setVerticalAlignment(XSSFCellStyle.VERTICAL_TOP)” for determining vertical alignment Step 5: For applying border to a cell, we can use “setBorderBottom/Left/Top/Right(XSSFCleeName.BorderName)”. Step 6: Change the border name in the parameter to go through different border styles. Step 7: For filling colors and adding patterns, first set the background color of the cell using “setFillBackgroundColor(HSSFColor.COLOR_NAME.index)”. Step 8: Then set the pattern whichever you like by “setFillPattern(XSSFCellStyle.PATTERN_NAME)”. Step 9: Finally, set the alignment using”setAlignment(XSSFCellStyle.ALIGN_TYPE); Implementation: Carrying out the above procedural steps over the empty Excel file at the local directory already created. Create a Spread Sheet by creating an object of XSSFSheetCreating a row in the above XSSFSheet using createRow() method.Later on, setting the height of a rowCreating an object of type XSSFCell and typecasting above row created to it.Setting cell values.Merging the cells.Aligning the cells.Justify the alignment.Bordering the cells.Filling colors in the cells.Creating a new file in the local directory by creating the object of FileOutputStream.Write to the above workbook created in the initial step.Close the connection of the file. Create a Spread Sheet by creating an object of XSSFSheet Creating a row in the above XSSFSheet using createRow() method.Later on, setting the height of a row Later on, setting the height of a row Creating an object of type XSSFCell and typecasting above row created to it. Setting cell values. Merging the cells. Aligning the cells. Justify the alignment. Bordering the cells. Filling colors in the cells. Creating a new file in the local directory by creating the object of FileOutputStream. Write to the above workbook created in the initial step. Close the connection of the file. Example: Java // Java Program to apply different styles// to a cell in a spreadsheet // Importing java input/output classesimport java.io.File;import java.io.FileOutputStream;// Importing Apache POI modulesimport org.apache.poi.hssf.util.HSSFColor;import org.apache.poi.ss.usermodel.IndexedColors;import org.apache.poi.ss.util.CellRangeAddress;import org.apache.poi.xssf.usermodel.XSSFCell;import org.apache.poi.xssf.usermodel.XSSFCellStyle;import org.apache.poi.xssf.usermodel.XSSFRow;import org.apache.poi.xssf.usermodel.XSSFSheet;import org.apache.poi.xssf.usermodel.XSSFWorkbook; // Class- for styling cellspublic class GFG { // Main driver method public static void main(String[] args) throws Exception { // Create a Work Book XSSFWorkbook workbook = new XSSFWorkbook(); // Step 1: Create a Spread Sheet by // creating an object of XSSFSheet XSSFSheet spreadsheet = workbook.createSheet("Sheet1"); // Step 2(a): Creating a row in above XSSFSheet // using createRow() method XSSFRow row = spreadsheet.createRow((short)1); // Step 2(b): Setting height of a row row.setHeight((short)800); // Step 3: Creating an object of type XSSFCell and // typecasting above row created to it XSSFCell cell = (XSSFCell)row.createCell((short)1); // Step 4: Setting cell values cell.setCellValue("Merged cells"); // Step 5: MERGING CELLS // This statement for merging cells spreadsheet.addMergedRegion(new CellRangeAddress( 1, // first row (0-based) 1, // last row (0-based) 1, // first column (0-based) 4 // last column (0-based) )); // Step 6: CELL Alignment row = spreadsheet.createRow(5); cell = (XSSFCell)row.createCell(0); row.setHeight((short)800); // 6(a) Top Left alignment XSSFCellStyle style1 = workbook.createCellStyle(); spreadsheet.setColumnWidth(0, 8000); style1.setAlignment(XSSFCellStyle.ALIGN_LEFT); style1.setVerticalAlignment( XSSFCellStyle.VERTICAL_TOP); cell.setCellValue("Hi, I'm top left indent"); cell.setCellStyle(style1); row = spreadsheet.createRow(6); cell = (XSSFCell)row.createCell(1); row.setHeight((short)800); // 6(b) Center Align Cell Contents XSSFCellStyle style2 = workbook.createCellStyle(); style2.setAlignment(XSSFCellStyle.ALIGN_CENTER); style2.setVerticalAlignment( XSSFCellStyle.VERTICAL_CENTER); cell.setCellValue("I'm Center Aligned indent"); cell.setCellStyle(style2); row = spreadsheet.createRow(7); cell = (XSSFCell)row.createCell(2); row.setHeight((short)800); // 6(c) Bottom Right alignment XSSFCellStyle style3 = workbook.createCellStyle(); style3.setAlignment(XSSFCellStyle.ALIGN_RIGHT); style3.setVerticalAlignment( XSSFCellStyle.VERTICAL_BOTTOM); cell.setCellValue("I'm Bottom Right indent"); cell.setCellStyle(style3); row = spreadsheet.createRow(8); cell = (XSSFCell)row.createCell(3); // Step 7: Justifying Alignment XSSFCellStyle style4 = workbook.createCellStyle(); style4.setAlignment(XSSFCellStyle.ALIGN_JUSTIFY); style4.setVerticalAlignment( XSSFCellStyle.VERTICAL_JUSTIFY); cell.setCellValue( "I'm Justify indent nice to meet you"); cell.setCellStyle(style4); // Step 8: CELL BORDER row = spreadsheet.createRow((short)10); row.setHeight((short)800); cell = (XSSFCell)row.createCell((short)1); cell.setCellValue("BORDER"); XSSFCellStyle style5 = workbook.createCellStyle(); style5.setBorderBottom(XSSFCellStyle.BORDER_THICK); style5.setBottomBorderColor( IndexedColors.BLUE.getIndex()); style5.setBorderLeft(XSSFCellStyle.BORDER_DOUBLE); style5.setLeftBorderColor( IndexedColors.GREEN.getIndex()); style5.setBorderRight(XSSFCellStyle.BORDER_HAIR); style5.setRightBorderColor( IndexedColors.RED.getIndex()); style5.setBorderTop(XSSFCellStyle.BIG_SPOTS); style5.setTopBorderColor( IndexedColors.Black.getIndex()); cell.setCellStyle(style5); // Step 9: Fill Colors // 9(a) Background color row = spreadsheet.createRow((short)10); cell = (XSSFCell)row.createCell((short)1); XSSFCellStyle style6 = workbook.createCellStyle(); style6.setFillBackgroundColor(HSSFColor.BLUE.index); style6.setFillPattern( XSSFCellStyle.FILL_HORIZONTAL_CROSS_HATCH); style6.setAlignment(XSSFCellStyle.ALIGN_FILL); spreadsheet.setColumnWidth(1, 8000); cell.setCellValue("FILL HORIZONTAL CROSS HATCH"); cell.setCellStyle(style6); // 9(b) Foreground color row = spreadsheet.createRow((short)12); cell = (XSSFCell)row.createCell((short)1); XSSFCellStyle style7 = workbook.createCellStyle(); style7.setFillForegroundColor( HSSFColor.GREEN.index); style7.setFillPattern( XSSFCellStyle.THIN_VERTICAL_STRIPE); style7.setAlignment(XSSFCellStyle.ALIGN_FILL); cell.setCellValue("THIN VERTICAL STRIPE"); cell.setCellStyle(style7); // Step 10: Creating a new file in the local // directory by creating object of FileOutputStream FileOutputStream out = new FileOutputStream( new File("C:/poiexcel/stlingcells.xlsx")); // Step 11: Write to above workbook created in // initial step workbook.write(out); // Step 12: Close the file connection out.close(); // Display message for console window when // program is successfully executed System.out.println("gfg.xlsx success"); }} Output sweetyty Picked Technical Scripter 2020 Java Java Programs Technical Scripter Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Introduction to Java Constructors in Java Exceptions in Java Generics in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class Factory method design pattern in Java Java Program to Remove Duplicate Elements From the Array
[ { "code": null, "e": 28, "s": 0, "text": "\n27 Apr, 2021" }, { "code": null, "e": 825, "s": 28, "text": "Apache POI is a powerful API that enables the user to create, manipulate, and display various file formats based on Microsoft Office using java programs. Using POI, one should be able to perform create, modify, and display/read operations on the following file formats. For Example, Java doesn’t provide built-in support for working with Excel files, so we need to look for open-source APIs for the job. It is an open-source library developed and distributed by Apache Software Foundation to design or modify Microsoft Office files using Java program. It contains classes and methods to decode the user input data or a file into MS Office documents. Here different styles can be applied like fonts, colors, cell merging, alignments, etc. to a cell in Excel using this concept in the Java program." }, { "code": null, "e": 936, "s": 825, "text": "Apache POI Architecture: It consists of various components that make an architecture to form a working system:" }, { "code": null, "e": 1098, "s": 936, "text": "POIFS (Poor Obfuscation Implementation File System): This component is the basic factor of all other POI elements. It is used to read different files explicitly." }, { "code": null, "e": 1193, "s": 1098, "text": "HSSF (Horrible Spreadsheet Format): It is used to read and write xls format of MS-Excel files." }, { "code": null, "e": 1269, "s": 1193, "text": "XSSF (XML Spreadsheet Format): It is used for xlsx file format of MS-Excel." }, { "code": null, "e": 1366, "s": 1269, "text": "HPSF (Horrible Property Set Format): It is used to extract property sets of the MS-Office files." }, { "code": null, "e": 1466, "s": 1366, "text": "HWPF (Horrible Word Processor Format): It is used to read and write doc extension files of MS-Word." }, { "code": null, "e": 1562, "s": 1466, "text": "XWPF (XML Word Processor Format): It is used to read and write Docx extension files of MS-Word." }, { "code": null, "e": 1662, "s": 1562, "text": "HSLF (Horrible Slide Layout Format): It is used to read, create, and edit PowerPoint presentations." }, { "code": null, "e": 1753, "s": 1662, "text": "HDGF (Horrible Diagram Format): It contains classes and methods for MS-Visio binary files." }, { "code": null, "e": 1836, "s": 1753, "text": "HPBF (Horrible Publisher Format): It is used to read and write MS-Publisher files." }, { "code": null, "e": 2254, "s": 1836, "text": "A Jar file is a Zip archive containing one or multiple java class files. This makes the usage of libraries handier. Directories and Jar files are added to the build path and available to the ClassLoader at runtime to find particular classes inside it. We generally use .jar files to distribute Java applications or libraries, in the form of Java class files and associated metadata and resources (text, images, etc.)." }, { "code": null, "e": 2285, "s": 2254, "text": " One can say JAR = JavaARchive" }, { "code": null, "e": 2295, "s": 2285, "text": "Approach:" }, { "code": null, "e": 2383, "s": 2295, "text": "Step 1: Import the necessary .jar files like HSSF, XML and add them to your build path." }, { "code": null, "e": 2585, "s": 2383, "text": "Step 2: Create a workbook using “new XSSFWorkbook()” in which we have to create the spreadsheet or the Excel file using “workbook.createSheet(‘Sheet1’)” in which we are going to apply different styles." }, { "code": null, "e": 2764, "s": 2585, "text": "Step 3: Apply the styles, here merge the cells using the command spreadsheet.addMergedRegion. We have to provide the range addresses of rows and columns as well as its parameter." }, { "code": null, "e": 3030, "s": 2764, "text": "Step 4: Now the next style in determining the cell alignment. For this, we have two commands“style1.setAlignment(XSSFCellStyle.ALIGN_LEFT)” for determining the alignment and“style1.setVerticalAlignment(XSSFCellStyle.VERTICAL_TOP)” for determining vertical alignment" }, { "code": null, "e": 3112, "s": 3030, "text": "“style1.setAlignment(XSSFCellStyle.ALIGN_LEFT)” for determining the alignment and" }, { "code": null, "e": 3205, "s": 3112, "text": "“style1.setVerticalAlignment(XSSFCellStyle.VERTICAL_TOP)” for determining vertical alignment" }, { "code": null, "e": 3314, "s": 3205, "text": "Step 5: For applying border to a cell, we can use “setBorderBottom/Left/Top/Right(XSSFCleeName.BorderName)”." }, { "code": null, "e": 3401, "s": 3314, "text": "Step 6: Change the border name in the parameter to go through different border styles." }, { "code": null, "e": 3552, "s": 3401, "text": "Step 7: For filling colors and adding patterns, first set the background color of the cell using “setFillBackgroundColor(HSSFColor.COLOR_NAME.index)”." }, { "code": null, "e": 3649, "s": 3552, "text": "Step 8: Then set the pattern whichever you like by “setFillPattern(XSSFCellStyle.PATTERN_NAME)”." }, { "code": null, "e": 3730, "s": 3649, "text": "Step 9: Finally, set the alignment using”setAlignment(XSSFCellStyle.ALIGN_TYPE);" }, { "code": null, "e": 3852, "s": 3730, "text": "Implementation: Carrying out the above procedural steps over the empty Excel file at the local directory already created." }, { "code": null, "e": 4387, "s": 3852, "text": "Create a Spread Sheet by creating an object of XSSFSheetCreating a row in the above XSSFSheet using createRow() method.Later on, setting the height of a rowCreating an object of type XSSFCell and typecasting above row created to it.Setting cell values.Merging the cells.Aligning the cells.Justify the alignment.Bordering the cells.Filling colors in the cells.Creating a new file in the local directory by creating the object of FileOutputStream.Write to the above workbook created in the initial step.Close the connection of the file." }, { "code": null, "e": 4444, "s": 4387, "text": "Create a Spread Sheet by creating an object of XSSFSheet" }, { "code": null, "e": 4545, "s": 4444, "text": "Creating a row in the above XSSFSheet using createRow() method.Later on, setting the height of a row" }, { "code": null, "e": 4583, "s": 4545, "text": "Later on, setting the height of a row" }, { "code": null, "e": 4660, "s": 4583, "text": "Creating an object of type XSSFCell and typecasting above row created to it." }, { "code": null, "e": 4681, "s": 4660, "text": "Setting cell values." }, { "code": null, "e": 4700, "s": 4681, "text": "Merging the cells." }, { "code": null, "e": 4720, "s": 4700, "text": "Aligning the cells." }, { "code": null, "e": 4743, "s": 4720, "text": "Justify the alignment." }, { "code": null, "e": 4764, "s": 4743, "text": "Bordering the cells." }, { "code": null, "e": 4793, "s": 4764, "text": "Filling colors in the cells." }, { "code": null, "e": 4880, "s": 4793, "text": "Creating a new file in the local directory by creating the object of FileOutputStream." }, { "code": null, "e": 4937, "s": 4880, "text": "Write to the above workbook created in the initial step." }, { "code": null, "e": 4971, "s": 4937, "text": "Close the connection of the file." }, { "code": null, "e": 4980, "s": 4971, "text": "Example:" }, { "code": null, "e": 4985, "s": 4980, "text": "Java" }, { "code": "// Java Program to apply different styles// to a cell in a spreadsheet // Importing java input/output classesimport java.io.File;import java.io.FileOutputStream;// Importing Apache POI modulesimport org.apache.poi.hssf.util.HSSFColor;import org.apache.poi.ss.usermodel.IndexedColors;import org.apache.poi.ss.util.CellRangeAddress;import org.apache.poi.xssf.usermodel.XSSFCell;import org.apache.poi.xssf.usermodel.XSSFCellStyle;import org.apache.poi.xssf.usermodel.XSSFRow;import org.apache.poi.xssf.usermodel.XSSFSheet;import org.apache.poi.xssf.usermodel.XSSFWorkbook; // Class- for styling cellspublic class GFG { // Main driver method public static void main(String[] args) throws Exception { // Create a Work Book XSSFWorkbook workbook = new XSSFWorkbook(); // Step 1: Create a Spread Sheet by // creating an object of XSSFSheet XSSFSheet spreadsheet = workbook.createSheet(\"Sheet1\"); // Step 2(a): Creating a row in above XSSFSheet // using createRow() method XSSFRow row = spreadsheet.createRow((short)1); // Step 2(b): Setting height of a row row.setHeight((short)800); // Step 3: Creating an object of type XSSFCell and // typecasting above row created to it XSSFCell cell = (XSSFCell)row.createCell((short)1); // Step 4: Setting cell values cell.setCellValue(\"Merged cells\"); // Step 5: MERGING CELLS // This statement for merging cells spreadsheet.addMergedRegion(new CellRangeAddress( 1, // first row (0-based) 1, // last row (0-based) 1, // first column (0-based) 4 // last column (0-based) )); // Step 6: CELL Alignment row = spreadsheet.createRow(5); cell = (XSSFCell)row.createCell(0); row.setHeight((short)800); // 6(a) Top Left alignment XSSFCellStyle style1 = workbook.createCellStyle(); spreadsheet.setColumnWidth(0, 8000); style1.setAlignment(XSSFCellStyle.ALIGN_LEFT); style1.setVerticalAlignment( XSSFCellStyle.VERTICAL_TOP); cell.setCellValue(\"Hi, I'm top left indent\"); cell.setCellStyle(style1); row = spreadsheet.createRow(6); cell = (XSSFCell)row.createCell(1); row.setHeight((short)800); // 6(b) Center Align Cell Contents XSSFCellStyle style2 = workbook.createCellStyle(); style2.setAlignment(XSSFCellStyle.ALIGN_CENTER); style2.setVerticalAlignment( XSSFCellStyle.VERTICAL_CENTER); cell.setCellValue(\"I'm Center Aligned indent\"); cell.setCellStyle(style2); row = spreadsheet.createRow(7); cell = (XSSFCell)row.createCell(2); row.setHeight((short)800); // 6(c) Bottom Right alignment XSSFCellStyle style3 = workbook.createCellStyle(); style3.setAlignment(XSSFCellStyle.ALIGN_RIGHT); style3.setVerticalAlignment( XSSFCellStyle.VERTICAL_BOTTOM); cell.setCellValue(\"I'm Bottom Right indent\"); cell.setCellStyle(style3); row = spreadsheet.createRow(8); cell = (XSSFCell)row.createCell(3); // Step 7: Justifying Alignment XSSFCellStyle style4 = workbook.createCellStyle(); style4.setAlignment(XSSFCellStyle.ALIGN_JUSTIFY); style4.setVerticalAlignment( XSSFCellStyle.VERTICAL_JUSTIFY); cell.setCellValue( \"I'm Justify indent nice to meet you\"); cell.setCellStyle(style4); // Step 8: CELL BORDER row = spreadsheet.createRow((short)10); row.setHeight((short)800); cell = (XSSFCell)row.createCell((short)1); cell.setCellValue(\"BORDER\"); XSSFCellStyle style5 = workbook.createCellStyle(); style5.setBorderBottom(XSSFCellStyle.BORDER_THICK); style5.setBottomBorderColor( IndexedColors.BLUE.getIndex()); style5.setBorderLeft(XSSFCellStyle.BORDER_DOUBLE); style5.setLeftBorderColor( IndexedColors.GREEN.getIndex()); style5.setBorderRight(XSSFCellStyle.BORDER_HAIR); style5.setRightBorderColor( IndexedColors.RED.getIndex()); style5.setBorderTop(XSSFCellStyle.BIG_SPOTS); style5.setTopBorderColor( IndexedColors.Black.getIndex()); cell.setCellStyle(style5); // Step 9: Fill Colors // 9(a) Background color row = spreadsheet.createRow((short)10); cell = (XSSFCell)row.createCell((short)1); XSSFCellStyle style6 = workbook.createCellStyle(); style6.setFillBackgroundColor(HSSFColor.BLUE.index); style6.setFillPattern( XSSFCellStyle.FILL_HORIZONTAL_CROSS_HATCH); style6.setAlignment(XSSFCellStyle.ALIGN_FILL); spreadsheet.setColumnWidth(1, 8000); cell.setCellValue(\"FILL HORIZONTAL CROSS HATCH\"); cell.setCellStyle(style6); // 9(b) Foreground color row = spreadsheet.createRow((short)12); cell = (XSSFCell)row.createCell((short)1); XSSFCellStyle style7 = workbook.createCellStyle(); style7.setFillForegroundColor( HSSFColor.GREEN.index); style7.setFillPattern( XSSFCellStyle.THIN_VERTICAL_STRIPE); style7.setAlignment(XSSFCellStyle.ALIGN_FILL); cell.setCellValue(\"THIN VERTICAL STRIPE\"); cell.setCellStyle(style7); // Step 10: Creating a new file in the local // directory by creating object of FileOutputStream FileOutputStream out = new FileOutputStream( new File(\"C:/poiexcel/stlingcells.xlsx\")); // Step 11: Write to above workbook created in // initial step workbook.write(out); // Step 12: Close the file connection out.close(); // Display message for console window when // program is successfully executed System.out.println(\"gfg.xlsx success\"); }}", "e": 10917, "s": 4985, "text": null }, { "code": null, "e": 10928, "s": 10921, "text": "Output" }, { "code": null, "e": 10941, "s": 10932, "text": "sweetyty" }, { "code": null, "e": 10948, "s": 10941, "text": "Picked" }, { "code": null, "e": 10972, "s": 10948, "text": "Technical Scripter 2020" }, { "code": null, "e": 10977, "s": 10972, "text": "Java" }, { "code": null, "e": 10991, "s": 10977, "text": "Java Programs" }, { "code": null, "e": 11010, "s": 10991, "text": "Technical Scripter" }, { "code": null, "e": 11015, "s": 11010, "text": "Java" }, { "code": null, "e": 11113, "s": 11015, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 11128, "s": 11113, "text": "Stream In Java" }, { "code": null, "e": 11149, "s": 11128, "text": "Introduction to Java" }, { "code": null, "e": 11170, "s": 11149, "text": "Constructors in Java" }, { "code": null, "e": 11189, "s": 11170, "text": "Exceptions in Java" }, { "code": null, "e": 11206, "s": 11189, "text": "Generics in Java" }, { "code": null, "e": 11232, "s": 11206, "text": "Java Programming Examples" }, { "code": null, "e": 11266, "s": 11232, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 11313, "s": 11266, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 11351, "s": 11313, "text": "Factory method design pattern in Java" } ]
MoviePy – Creating Composite Video Clips
21 May, 2021 In this article, we will see how we can composite video file in MoviePy. MoviePy is a Python module for video editing, which can be used for basic operations on videos and GIF’s. Meaning of composite is combining different elements, composite video is the combination of different video clips unlike stacking and concatenation of video files composite files are easy to implement but complex structure. Composite file combine the clips over one another and get played at the same time, position and timing of video playback can be set any time. In order to do this we will use CompositeVideoClip methodSyntax : CompositeVideoClip(clips)Argument : It takes list of video clips as argumentReturn : It returns VideoFileClip object Below is the implementation Python3 # Import everything needed to edit video clipsfrom moviepy.editor import * # loading video dsa gfg intro video and getting only first 5 secondsclip1 = VideoFileClip("dsa_geek.webm").subclip(0, 5) # rotating clip1 by 90 degree to get the clip2clip2 = clip1.margin(40).set_start(3) # rotating clip1 by 180 degree to get the clip3clip3 = clip1.rotate(180).set_start(6) # creating a composite videofinal = CompositeVideoClip([clip2, clip1, clip3]) # showing final clipfinal.ipython_display(width = 480) Output : Moviepy - Building video __temp__.mp4. Moviepy - Writing video __temp__.mp4 Moviepy - Done ! Moviepy - video ready __temp__.mp4 Another example Python3 # Import everything needed to edit video clipsfrom moviepy.editor import * # loading video gfgclip = VideoFileClip("geeks.mp4") # getting subclip from itclip1 = clip.subclip(0, 5) # mirroring image according to the y axisclip2 = clip.fx(vfx.mirror_y).set_start((4)) # creating a composite videofinal = CompositeVideoClip([clip1, clip2]) # showing final clipfinal.ipython_display(width = 480) Output : Moviepy - Building video __temp__.mp4. MoviePy - Writing audio in __temp__TEMP_MPY_wvf_snd.mp3 MoviePy - Done. Moviepy - Writing video __temp__.mp4 Moviepy - Done ! Moviepy - video ready __temp__.mp4 anikaseth98 Python-MoviePy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 28, "s": 0, "text": "\n21 May, 2021" }, { "code": null, "e": 573, "s": 28, "text": "In this article, we will see how we can composite video file in MoviePy. MoviePy is a Python module for video editing, which can be used for basic operations on videos and GIF’s. Meaning of composite is combining different elements, composite video is the combination of different video clips unlike stacking and concatenation of video files composite files are easy to implement but complex structure. Composite file combine the clips over one another and get played at the same time, position and timing of video playback can be set any time." }, { "code": null, "e": 758, "s": 573, "text": "In order to do this we will use CompositeVideoClip methodSyntax : CompositeVideoClip(clips)Argument : It takes list of video clips as argumentReturn : It returns VideoFileClip object " }, { "code": null, "e": 788, "s": 758, "text": "Below is the implementation " }, { "code": null, "e": 796, "s": 788, "text": "Python3" }, { "code": "# Import everything needed to edit video clipsfrom moviepy.editor import * # loading video dsa gfg intro video and getting only first 5 secondsclip1 = VideoFileClip(\"dsa_geek.webm\").subclip(0, 5) # rotating clip1 by 90 degree to get the clip2clip2 = clip1.margin(40).set_start(3) # rotating clip1 by 180 degree to get the clip3clip3 = clip1.rotate(180).set_start(6) # creating a composite videofinal = CompositeVideoClip([clip2, clip1, clip3]) # showing final clipfinal.ipython_display(width = 480)", "e": 1300, "s": 796, "text": null }, { "code": null, "e": 1310, "s": 1300, "text": "Output : " }, { "code": null, "e": 1561, "s": 1310, "text": "Moviepy - Building video __temp__.mp4.\nMoviepy - Writing video __temp__.mp4\n\n \nMoviepy - Done !\nMoviepy - video ready __temp__.mp4\n " }, { "code": null, "e": 1578, "s": 1561, "text": "Another example " }, { "code": null, "e": 1586, "s": 1578, "text": "Python3" }, { "code": "# Import everything needed to edit video clipsfrom moviepy.editor import * # loading video gfgclip = VideoFileClip(\"geeks.mp4\") # getting subclip from itclip1 = clip.subclip(0, 5) # mirroring image according to the y axisclip2 = clip.fx(vfx.mirror_y).set_start((4)) # creating a composite videofinal = CompositeVideoClip([clip1, clip2]) # showing final clipfinal.ipython_display(width = 480)", "e": 1981, "s": 1586, "text": null }, { "code": null, "e": 1991, "s": 1981, "text": "Output : " }, { "code": null, "e": 2555, "s": 1991, "text": "Moviepy - Building video __temp__.mp4.\n \nMoviePy - Writing audio in __temp__TEMP_MPY_wvf_snd.mp3\n\nMoviePy - Done.\n \nMoviepy - Writing video __temp__.mp4\n\nMoviepy - Done !\n \nMoviepy - video ready __temp__.mp4\n " }, { "code": null, "e": 2569, "s": 2557, "text": "anikaseth98" }, { "code": null, "e": 2584, "s": 2569, "text": "Python-MoviePy" }, { "code": null, "e": 2591, "s": 2584, "text": "Python" }, { "code": null, "e": 2689, "s": 2591, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2721, "s": 2689, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2748, "s": 2721, "text": "Python Classes and Objects" }, { "code": null, "e": 2769, "s": 2748, "text": "Python OOPs Concepts" }, { "code": null, "e": 2792, "s": 2769, "text": "Introduction To PYTHON" }, { "code": null, "e": 2848, "s": 2792, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2879, "s": 2848, "text": "Python | os.path.join() method" }, { "code": null, "e": 2921, "s": 2879, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2963, "s": 2921, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 3002, "s": 2963, "text": "Python | Get unique values from a list" } ]
Maximum possible difference of two subsets of an array
30 May, 2022 Given an array of n-integers. The array may contain repetitive elements but the highest frequency of any elements must not exceed two. You have to make two subsets such that the difference of the sum of their elements is maximum and both of them jointly contain all elements of the given array along with the most important condition, no subset should contain repetitive elements. Examples: Input : arr[] = {5, 8, -1, 4} Output : Maximum Difference = 18 Explanation : Let Subset A = {5, 8, 4} & Subset B = {-1} Sum of elements of subset A = 17, of subset B = -1 Difference of Sum of Both subsets = 17 - (-1) = 18 Input : arr[] = {5, 8, 5, 4} Output : Maximum Difference = 12 Explanation : Let Subset A = {5, 8, 4} & Subset B = {5} Sum of elements of subset A = 17, of subset B = 5 Difference of Sum of Both subsets = 17 - 5 = 12 Before solving this question we have to take care of some given conditions, and they are listed as: While building up the subsets, take care that no subset should contain repetitive elements. And for this, we can conclude that all such elements whose frequency are 2, going to be part of both subsets, and hence overall they don’t have any impact on the difference of subset-sum. So, we can easily ignore them. For making the difference of the sum of elements of both subset maximum we have to make subset in such a way that all positive elements belong to one subset and negative ones to other subsets. Algorithm with time complexity O(n2): for i=0 to n-1 isSingleOccurrence = true; for j= i+1 to n-1 // if frequency of any element is two // make both equal to zero if arr[i] equals arr[j] arr[i] = arr[j] = 0 isSingleOccurrence = false; break; if isSingleOccurrence == true if (arr[i] > 0) SubsetSum_1 += arr[i]; else SubsetSum_2 += arr[i]; return abs(SubsetSum_1 - SubsetSum2) C++ Java Python3 C# PHP Javascript // CPP find maximum difference of subset sum#include <bits/stdc++.h>using namespace std; // function for maximum subset diffint maxDiff(int arr[], int n){ int SubsetSum_1 = 0, SubsetSum_2 = 0; for (int i = 0; i <= n - 1; i++) { bool isSingleOccurrence = true; for (int j = i + 1; j <= n - 1; j++) { // if frequency of any element is two // make both equal to zero if (arr[i] == arr[j]) { isSingleOccurrence = false; arr[i] = arr[j] = 0; break; } } if (isSingleOccurrence) { if (arr[i] > 0) SubsetSum_1 += arr[i]; else SubsetSum_2 += arr[i]; } } return abs(SubsetSum_1 - SubsetSum_2);} // driver programint main(){ int arr[] = { 4, 2, -3, 3, -2, -2, 8 }; int n = sizeof(arr) / sizeof(arr[0]); cout << "Maximum Difference = " << maxDiff(arr, n); return 0;} // java find maximum difference// of subset sumimport java .io.*; public class GFG { // function for maximum subset diff static int maxDiff(int []arr, int n) { int SubsetSum_1 = 0, SubsetSum_2 = 0; for (int i = 0; i <= n - 1; i++) { boolean isSingleOccurrence = true; for (int j = i + 1; j <= n - 1; j++) { // if frequency of any element // is two make both equal to // zero if (arr[i] == arr[j]) { isSingleOccurrence = false; arr[i] = arr[j] = 0; break; } } if (isSingleOccurrence) { if (arr[i] > 0) SubsetSum_1 += arr[i]; else SubsetSum_2 += arr[i]; } } return Math.abs(SubsetSum_1 - SubsetSum_2); } // driver program static public void main (String[] args) { int []arr = { 4, 2, -3, 3, -2, -2, 8 }; int n = arr.length; System.out.println("Maximum Difference = " + maxDiff(arr, n)); }} // This code is contributed by vt_m. # Python3 find maximum difference# of subset sum import math # function for maximum subset diffdef maxDiff(arr, n) : SubsetSum_1 = 0 SubsetSum_2 = 0 for i in range(0, n) : isSingleOccurrence = True for j in range(i + 1, n) : # if frequency of any element # is two make both equal to # zero if (arr[i] == arr[j]) : isSingleOccurrence = False arr[i] = arr[j] = 0 break if (isSingleOccurrence == True) : if (arr[i] > 0) : SubsetSum_1 += arr[i] else : SubsetSum_2 += arr[i] return abs(SubsetSum_1 - SubsetSum_2) # Driver Codearr = [4, 2, -3, 3, -2, -2, 8]n = len(arr)print ("Maximum Difference = {}" . format(maxDiff(arr, n))) # This code is contributed by Manish Shaw# (manishshaw1) // C# find maximum difference of// subset sumusing System; public class GFG { // function for maximum subset diff static int maxDiff(int []arr, int n) { int SubsetSum_1 = 0, SubsetSum_2 = 0; for (int i = 0; i <= n - 1; i++) { bool isSingleOccurrence = true; for (int j = i + 1; j <= n - 1; j++) { // if frequency of any element // is two make both equal to // zero if (arr[i] == arr[j]) { isSingleOccurrence = false; arr[i] = arr[j] = 0; break; } } if (isSingleOccurrence) { if (arr[i] > 0) SubsetSum_1 += arr[i]; else SubsetSum_2 += arr[i]; } } return Math.Abs(SubsetSum_1 - SubsetSum_2); } // driver program static public void Main () { int []arr = { 4, 2, -3, 3, -2, -2, 8 }; int n = arr.Length; Console.WriteLine("Maximum Difference = " + maxDiff(arr, n)); }} // This code is contributed by vt_m. <?php// PHP find maximum difference// of subset sum // function for maximum subset difffunction maxDiff($arr, $n){ $SubsetSum_1 = 0; $SubsetSum_2 = 0; for ($i = 0; $i <= $n - 1; $i++) { $isSingleOccurrence = true; for ($j = $i + 1; $j <= $n - 1; $j++) { // if frequency of any element is two // make both equal to zero if ($arr[$i] == $arr[$j]) { $isSingleOccurrence = false; $arr[$i] = $arr[$j] = 0; break; } } if ($isSingleOccurrence) { if ($arr[$i] > 0) $SubsetSum_1 += $arr[$i]; else $SubsetSum_2 += $arr[$i]; } } return abs($SubsetSum_1 - $SubsetSum_2);} // Driver Code $arr = array(4, 2, -3, 3, -2, -2, 8); $n = sizeof($arr); echo "Maximum Difference = " , maxDiff($arr, $n); // This code is contributed by nitin mittal?> <script> // JavaScript Program to find maximum difference// of subset sum // function for maximum subset diff function maxDiff(arr, n) { let SubsetSum_1 = 0, SubsetSum_2 = 0; for (let i = 0; i <= n - 1; i++) { let isSingleOccurrence = true; for (let j = i + 1; j <= n - 1; j++) { // if frequency of any element // is two make both equal to // zero if (arr[i] == arr[j]) { isSingleOccurrence = false; arr[i] = arr[j] = 0; break; } } if (isSingleOccurrence) { if (arr[i] > 0) SubsetSum_1 += arr[i]; else SubsetSum_2 += arr[i]; } } return Math.abs(SubsetSum_1 - SubsetSum_2); } // Driver program let arr = [ 4, 2, -3, 3, -2, -2, 8 ]; let n = arr.length; document.write("Maximum Difference = " + maxDiff(arr, n)); // This code is contributed by susmitakundugoaldanga.</script> Maximum Difference = 20 Algorithm with time complexity O(n log n): -> sort the array -> for i =0 to n-2 // consecutive two elements are not equal // add absolute arr[i] to result if arr[i] != arr[i+1] result += abs(arr[i]) // else skip next element too else i++; // special check for last two elements -> if (arr[n-2] != arr[n-1]) result += arr[n-1] -> return result; C++ Java Python 3 C# PHP Javascript // CPP find maximum difference of subset sum#include <bits/stdc++.h>using namespace std; // function for maximum subset diffint maxDiff(int arr[], int n){ int result = 0; // sort the array sort(arr, arr + n); // calculate the result for (int i = 0; i < n - 1; i++) { if (arr[i] != arr[i + 1]) result += abs(arr[i]); else i++; } // check for last element if (arr[n - 2] != arr[n - 1]) result += abs(arr[n - 1]); // return result return result;} // driver programint main(){ int arr[] = { 4, 2, -3, 3, -2, -2, 8 }; int n = sizeof(arr) / sizeof(arr[0]); cout << "Maximum Difference = " << maxDiff(arr, n); return 0;} // java find maximum difference of// subset sumimport java. io.*;import java .util.*; public class GFG { // function for maximum subset diff static int maxDiff(int []arr, int n) { int result = 0; // sort the array Arrays.sort(arr); // calculate the result for (int i = 0; i < n - 1; i++) { if (arr[i] != arr[i + 1]) result += Math.abs(arr[i]); else i++; } // check for last element if (arr[n - 2] != arr[n - 1]) result += Math.abs(arr[n - 1]); // return result return result; } // driver program static public void main (String[] args) { int[] arr = { 4, 2, -3, 3, -2, -2, 8 }; int n = arr.length; System.out.println("Maximum Difference = " + maxDiff(arr, n)); }} // This code is contributed by vt_m. # Python 3 find maximum difference# of subset sum # function for maximum subset diffdef maxDiff(arr, n): result = 0 # sort the array arr.sort() # calculate the result for i in range(n - 1): if (abs(arr[i]) != abs(arr[i + 1])): result += abs(arr[i]) else: pass # check for last element if (arr[n - 2] != arr[n - 1]): result += abs(arr[n - 1]) # return result return result # Driver Codeif __name__ == "__main__": arr = [ 4, 2, -3, 3, -2, -2, 8 ] n = len(arr) print("Maximum Difference = " , maxDiff(arr, n)) # This code is contributed by ita_c // C# find maximum difference// of subset sumusing System; public class GFG { // function for maximum subset diff static int maxDiff(int []arr, int n) { int result = 0; // sort the array Array.Sort(arr); // calculate the result for (int i = 0; i < n - 1; i++) { if (arr[i] != arr[i + 1]) result += Math.Abs(arr[i]); else i++; } // check for last element if (arr[n - 2] != arr[n - 1]) result += Math.Abs(arr[n - 1]); // return result return result; } // driver program static public void Main () { int[] arr = { 4, 2, -3, 3, -2, -2, 8 }; int n = arr.Length; Console.WriteLine("Maximum Difference = " + maxDiff(arr, n)); }} // This code is contributed by vt_m. <?php// PHP find maximum difference of subset sum // function for maximum subset difffunction maxDiff( $arr, $n){ $result = 0; // sort the array sort($arr); // calculate the result for ( $i = 0; $i < $n - 1; $i++) { if ($arr[$i] != $arr[$i + 1]) $result += abs($arr[$i]); else $i++; } // check for last element if ($arr[$n - 2] != $arr[$n - 1]) $result += abs($arr[$n - 1]); // return result return $result;} // Driver Code $arr = array( 4, 2, -3, 3, -2, -2, 8 ); $n = count($arr); echo "Maximum Difference = " , maxDiff($arr, $n); // This code is contributed by anuj_67.?> <script> // Javascript find maximum difference of subset sum // function for maximum subset difffunction maxDiff(arr, n){ var result = 0; // sort the array arr.sort((a,b)=> a-b) // calculate the result for (var i = 0; i < n - 1; i++) { if (arr[i] != arr[i + 1]) result += Math.abs(arr[i]); else i++; } // check for last element if (arr[n - 2] != arr[n - 1]) result += Math.abs(arr[n - 1]); // return result return result;} // driver programvar arr = [ 4, 2, -3, 3, -2, -2, 8 ];var n = arr.length;document.write( "Maximum Difference = " + maxDiff(arr, n)); </script> Maximum Difference = 20 Algorithm with time complexity O(n): make hash table for positive elements: for all positive elements(arr[i]) if frequency == 1 SubsetSum_1 += arr[i]; make hash table for negative elements: for all negative elements if frequency == 1 SubsetSum_2 += arr[i]; return abs(SubsetSum_1 - SubsetSum2) C++ Java Python3 C# Javascript // CPP find maximum difference of subset sum#include <bits/stdc++.h>using namespace std; // function for maximum subset diffint maxDiff(int arr[], int n){ unordered_map<int, int> hashPositive; unordered_map<int, int> hashNegative; int SubsetSum_1 = 0, SubsetSum_2 = 0; // construct hash for positive elements for (int i = 0; i <= n - 1; i++) if (arr[i] > 0) hashPositive[arr[i]]++; // calculate subset sum for positive elements for (int i = 0; i <= n - 1; i++) if (arr[i] > 0 && hashPositive[arr[i]] == 1) SubsetSum_1 += arr[i]; // construct hash for negative elements for (int i = 0; i <= n - 1; i++) if (arr[i] < 0) hashNegative[abs(arr[i])]++; // calculate subset sum for negative elements for (int i = 0; i <= n - 1; i++) if (arr[i] < 0 && hashNegative[abs(arr[i])] == 1) SubsetSum_2 += arr[i]; return abs(SubsetSum_1 - SubsetSum_2);} // driver programint main(){ int arr[] = { 4, 2, -3, 3, -2, -2, 8 }; int n = sizeof(arr) / sizeof(arr[0]); cout << "Maximum Difference = " << maxDiff(arr, n); return 0;} // Java find maximum// difference of subset sumimport java.util.*;class GFG{ // Function for maximum subset diffpublic static int maxDiff(int arr[], int n){ HashMap<Integer, Integer> hashPositive = new HashMap<>(); HashMap<Integer, Integer> hashNegative = new HashMap<>(); int SubsetSum_1 = 0, SubsetSum_2 = 0; // Construct hash for // positive elements for (int i = 0; i <= n - 1; i++) { if (arr[i] > 0) { if(hashPositive.containsKey(arr[i])) { hashPositive.replace(arr[i], hashPositive.get(arr[i]) + 1); } else { hashPositive.put(arr[i], 1); } } } // Calculate subset sum // for positive elements for (int i = 0; i <= n - 1; i++) { if(arr[i] > 0 && hashPositive.containsKey(arr[i])) { if(hashPositive.get(arr[i]) == 1) { SubsetSum_1 += arr[i]; } } } // Construct hash for // negative elements for (int i = 0; i <= n - 1; i++) { if (arr[i] < 0) { if(hashNegative.containsKey(Math.abs(arr[i]))) { hashNegative.replace(Math.abs(arr[i]), hashNegative.get(Math.abs(arr[i])) + 1); } else { hashNegative.put(Math.abs(arr[i]), 1); } } } // Calculate subset sum for // negative elements for (int i = 0; i <= n - 1; i++) { if (arr[i] < 0 && hashNegative.containsKey(Math.abs(arr[i]))) { if(hashNegative.get(Math.abs(arr[i])) == 1) { SubsetSum_2 += arr[i]; } } } return Math.abs(SubsetSum_1 - SubsetSum_2);} // Driver codepublic static void main(String[] args){ int arr[] = {4, 2, -3, 3, -2, -2, 8}; int n = arr.length; System.out.print("Maximum Difference = " + maxDiff(arr, n));}} // This code is contributed by divyeshrabadiya07 # Python3 find maximum difference of subset sum # function for maximum subset diffdef maxDiff(arr, n): hashPositive = dict() hashNegative = dict() SubsetSum_1, SubsetSum_2 = 0, 0 # construct hash for positive elements for i in range(n): if (arr[i] > 0): hashPositive[arr[i]] = \ hashPositive.get(arr[i], 0) + 1 # calculate subset sum for positive elements for i in range(n): if (arr[i] > 0 and arr[i] in hashPositive.keys() and hashPositive[arr[i]] == 1): SubsetSum_1 += arr[i] # construct hash for negative elements for i in range(n): if (arr[i] < 0): hashNegative[abs(arr[i])] = \ hashNegative.get(abs(arr[i]), 0) + 1 # calculate subset sum for negative elements for i in range(n): if (arr[i] < 0 and abs(arr[i]) in hashNegative.keys() and hashNegative[abs(arr[i])] == 1): SubsetSum_2 += arr[i] return abs(SubsetSum_1 - SubsetSum_2) # Driver Codearr = [4, 2, -3, 3, -2, -2, 8]n = len(arr)print("Maximum Difference =", maxDiff(arr, n)) # This code is contributed by mohit kumar // C# find maximum// difference of subset sumusing System;using System.Collections.Generic; class GFG { // Function for maximum subset diff static int maxDiff(int[] arr, int n) { Dictionary<int, int> hashPositive = new Dictionary<int, int>(); Dictionary<int, int> hashNegative = new Dictionary<int, int>(); int SubsetSum_1 = 0, SubsetSum_2 = 0; // Construct hash for // positive elements for (int i = 0; i <= n - 1; i++) { if (arr[i] > 0) { if(hashPositive.ContainsKey(arr[i])) { hashPositive[arr[i]] += 1; } else { hashPositive.Add(arr[i], 1); } } } // Calculate subset sum // for positive elements for (int i = 0; i <= n - 1; i++) { if(arr[i] > 0 && hashPositive.ContainsKey(arr[i])) { if(hashPositive[arr[i]] == 1) { SubsetSum_1 += arr[i]; } } } // Construct hash for // negative elements for (int i = 0; i <= n - 1; i++) { if (arr[i] < 0) { if(hashNegative.ContainsKey(Math.Abs(arr[i]))) { hashNegative[Math.Abs(arr[i])] += 1; } else { hashNegative.Add(Math.Abs(arr[i]), 1); } } } // Calculate subset sum for // negative elements for (int i = 0; i <= n - 1; i++) { if (arr[i] < 0 && hashNegative.ContainsKey(Math.Abs(arr[i]))) { if(hashNegative[Math.Abs(arr[i])] == 1) { SubsetSum_2 += arr[i]; } } } return Math.Abs(SubsetSum_1 - SubsetSum_2); } // Driver code static void Main() { int[] arr = {4, 2, -3, 3, -2, -2, 8}; int n = arr.Length; Console.WriteLine("Maximum Difference = " + maxDiff(arr, n)); }} // This code is contributed by divesh072019 <script>// Javascript find maximum// difference of subset sum // Function for maximum subset difffunction maxDiff(arr,n){ let hashPositive = new Map(); let hashNegative = new Map(); let SubsetSum_1 = 0, SubsetSum_2 = 0; // Construct hash for // positive elements for (let i = 0; i <= n - 1; i++) { if (arr[i] > 0) { if(hashPositive.has(arr[i])) { hashPositive.set(arr[i], hashPositive.get(arr[i]) + 1); } else { hashPositive.set(arr[i], 1); } } } // Calculate subset sum // for positive elements for (let i = 0; i <= n - 1; i++) { if(arr[i] > 0 && hashPositive.has(arr[i])) { if(hashPositive.get(arr[i]) == 1) { SubsetSum_1 += arr[i]; } } } // Construct hash for // negative elements for (let i = 0; i <= n - 1; i++) { if (arr[i] < 0) { if(hashNegative.has(Math.abs(arr[i]))) { hashNegative.set(Math.abs(arr[i]), hashNegative.get(Math.abs(arr[i])) + 1); } else { hashNegative.set(Math.abs(arr[i]), 1); } } } // Calculate subset sum for // negative elements for (let i = 0; i <= n - 1; i++) { if (arr[i] < 0 && hashNegative.has(Math.abs(arr[i]))) { if(hashNegative.get(Math.abs(arr[i])) == 1) { SubsetSum_2 += arr[i]; } } } return Math.abs(SubsetSum_1 - SubsetSum_2); } // Driver code let arr = [4, 2, -3, 3, -2, -2, 8];let n = arr.length;document.write("Maximum Difference = " + maxDiff(arr, n)); // This code is contributed by rag2127</script> Maximum Difference = 20 vt_m nitin mittal manishshaw1 ukasp mohit kumar 29 divyeshrabadiya07 divyesh072019 susmitakundugoaldanga rutvik_56 rag2127 surinderdawra388 Arrays Hash Sorting Technical Scripter Arrays Hash Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n30 May, 2022" }, { "code": null, "e": 446, "s": 54, "text": "Given an array of n-integers. The array may contain repetitive elements but the highest frequency of any elements must not exceed two. You have to make two subsets such that the difference of the sum of their elements is maximum and both of them jointly contain all elements of the given array along with the most important condition, no subset should contain repetitive elements. Examples: " }, { "code": null, "e": 887, "s": 446, "text": "Input : arr[] = {5, 8, -1, 4}\nOutput : Maximum Difference = 18\nExplanation : \nLet Subset A = {5, 8, 4} & Subset B = {-1}\nSum of elements of subset A = 17, of subset B = -1\nDifference of Sum of Both subsets = 17 - (-1) = 18\n\nInput : arr[] = {5, 8, 5, 4}\nOutput : Maximum Difference = 12\nExplanation : \nLet Subset A = {5, 8, 4} & Subset B = {5}\nSum of elements of subset A = 17, of subset B = 5\nDifference of Sum of Both subsets = 17 - 5 = 12" }, { "code": null, "e": 988, "s": 887, "text": "Before solving this question we have to take care of some given conditions, and they are listed as: " }, { "code": null, "e": 1299, "s": 988, "text": "While building up the subsets, take care that no subset should contain repetitive elements. And for this, we can conclude that all such elements whose frequency are 2, going to be part of both subsets, and hence overall they don’t have any impact on the difference of subset-sum. So, we can easily ignore them." }, { "code": null, "e": 1492, "s": 1299, "text": "For making the difference of the sum of elements of both subset maximum we have to make subset in such a way that all positive elements belong to one subset and negative ones to other subsets." }, { "code": null, "e": 1531, "s": 1492, "text": "Algorithm with time complexity O(n2): " }, { "code": null, "e": 1997, "s": 1531, "text": "for i=0 to n-1\n isSingleOccurrence = true;\n for j= i+1 to n-1\n\n // if frequency of any element is two\n // make both equal to zero\n if arr[i] equals arr[j]\n arr[i] = arr[j] = 0\n isSingleOccurrence = false;\n break;\n \n if isSingleOccurrence == true\n if (arr[i] > 0)\n SubsetSum_1 += arr[i];\n else \n SubsetSum_2 += arr[i];\nreturn abs(SubsetSum_1 - SubsetSum2)" }, { "code": null, "e": 2001, "s": 1997, "text": "C++" }, { "code": null, "e": 2006, "s": 2001, "text": "Java" }, { "code": null, "e": 2014, "s": 2006, "text": "Python3" }, { "code": null, "e": 2017, "s": 2014, "text": "C#" }, { "code": null, "e": 2021, "s": 2017, "text": "PHP" }, { "code": null, "e": 2032, "s": 2021, "text": "Javascript" }, { "code": "// CPP find maximum difference of subset sum#include <bits/stdc++.h>using namespace std; // function for maximum subset diffint maxDiff(int arr[], int n){ int SubsetSum_1 = 0, SubsetSum_2 = 0; for (int i = 0; i <= n - 1; i++) { bool isSingleOccurrence = true; for (int j = i + 1; j <= n - 1; j++) { // if frequency of any element is two // make both equal to zero if (arr[i] == arr[j]) { isSingleOccurrence = false; arr[i] = arr[j] = 0; break; } } if (isSingleOccurrence) { if (arr[i] > 0) SubsetSum_1 += arr[i]; else SubsetSum_2 += arr[i]; } } return abs(SubsetSum_1 - SubsetSum_2);} // driver programint main(){ int arr[] = { 4, 2, -3, 3, -2, -2, 8 }; int n = sizeof(arr) / sizeof(arr[0]); cout << \"Maximum Difference = \" << maxDiff(arr, n); return 0;}", "e": 2989, "s": 2032, "text": null }, { "code": "// java find maximum difference// of subset sumimport java .io.*; public class GFG { // function for maximum subset diff static int maxDiff(int []arr, int n) { int SubsetSum_1 = 0, SubsetSum_2 = 0; for (int i = 0; i <= n - 1; i++) { boolean isSingleOccurrence = true; for (int j = i + 1; j <= n - 1; j++) { // if frequency of any element // is two make both equal to // zero if (arr[i] == arr[j]) { isSingleOccurrence = false; arr[i] = arr[j] = 0; break; } } if (isSingleOccurrence) { if (arr[i] > 0) SubsetSum_1 += arr[i]; else SubsetSum_2 += arr[i]; } } return Math.abs(SubsetSum_1 - SubsetSum_2); } // driver program static public void main (String[] args) { int []arr = { 4, 2, -3, 3, -2, -2, 8 }; int n = arr.length; System.out.println(\"Maximum Difference = \" + maxDiff(arr, n)); }} // This code is contributed by vt_m.", "e": 4249, "s": 2989, "text": null }, { "code": "# Python3 find maximum difference# of subset sum import math # function for maximum subset diffdef maxDiff(arr, n) : SubsetSum_1 = 0 SubsetSum_2 = 0 for i in range(0, n) : isSingleOccurrence = True for j in range(i + 1, n) : # if frequency of any element # is two make both equal to # zero if (arr[i] == arr[j]) : isSingleOccurrence = False arr[i] = arr[j] = 0 break if (isSingleOccurrence == True) : if (arr[i] > 0) : SubsetSum_1 += arr[i] else : SubsetSum_2 += arr[i] return abs(SubsetSum_1 - SubsetSum_2) # Driver Codearr = [4, 2, -3, 3, -2, -2, 8]n = len(arr)print (\"Maximum Difference = {}\" . format(maxDiff(arr, n))) # This code is contributed by Manish Shaw# (manishshaw1)", "e": 5121, "s": 4249, "text": null }, { "code": "// C# find maximum difference of// subset sumusing System; public class GFG { // function for maximum subset diff static int maxDiff(int []arr, int n) { int SubsetSum_1 = 0, SubsetSum_2 = 0; for (int i = 0; i <= n - 1; i++) { bool isSingleOccurrence = true; for (int j = i + 1; j <= n - 1; j++) { // if frequency of any element // is two make both equal to // zero if (arr[i] == arr[j]) { isSingleOccurrence = false; arr[i] = arr[j] = 0; break; } } if (isSingleOccurrence) { if (arr[i] > 0) SubsetSum_1 += arr[i]; else SubsetSum_2 += arr[i]; } } return Math.Abs(SubsetSum_1 - SubsetSum_2); } // driver program static public void Main () { int []arr = { 4, 2, -3, 3, -2, -2, 8 }; int n = arr.Length; Console.WriteLine(\"Maximum Difference = \" + maxDiff(arr, n)); }} // This code is contributed by vt_m.", "e": 6361, "s": 5121, "text": null }, { "code": "<?php// PHP find maximum difference// of subset sum // function for maximum subset difffunction maxDiff($arr, $n){ $SubsetSum_1 = 0; $SubsetSum_2 = 0; for ($i = 0; $i <= $n - 1; $i++) { $isSingleOccurrence = true; for ($j = $i + 1; $j <= $n - 1; $j++) { // if frequency of any element is two // make both equal to zero if ($arr[$i] == $arr[$j]) { $isSingleOccurrence = false; $arr[$i] = $arr[$j] = 0; break; } } if ($isSingleOccurrence) { if ($arr[$i] > 0) $SubsetSum_1 += $arr[$i]; else $SubsetSum_2 += $arr[$i]; } } return abs($SubsetSum_1 - $SubsetSum_2);} // Driver Code $arr = array(4, 2, -3, 3, -2, -2, 8); $n = sizeof($arr); echo \"Maximum Difference = \" , maxDiff($arr, $n); // This code is contributed by nitin mittal?>", "e": 7323, "s": 6361, "text": null }, { "code": "<script> // JavaScript Program to find maximum difference// of subset sum // function for maximum subset diff function maxDiff(arr, n) { let SubsetSum_1 = 0, SubsetSum_2 = 0; for (let i = 0; i <= n - 1; i++) { let isSingleOccurrence = true; for (let j = i + 1; j <= n - 1; j++) { // if frequency of any element // is two make both equal to // zero if (arr[i] == arr[j]) { isSingleOccurrence = false; arr[i] = arr[j] = 0; break; } } if (isSingleOccurrence) { if (arr[i] > 0) SubsetSum_1 += arr[i]; else SubsetSum_2 += arr[i]; } } return Math.abs(SubsetSum_1 - SubsetSum_2); } // Driver program let arr = [ 4, 2, -3, 3, -2, -2, 8 ]; let n = arr.length; document.write(\"Maximum Difference = \" + maxDiff(arr, n)); // This code is contributed by susmitakundugoaldanga.</script>", "e": 8536, "s": 7323, "text": null }, { "code": null, "e": 8560, "s": 8536, "text": "Maximum Difference = 20" }, { "code": null, "e": 8607, "s": 8562, "text": "Algorithm with time complexity O(n log n): " }, { "code": null, "e": 8974, "s": 8607, "text": "-> sort the array\n-> for i =0 to n-2\n // consecutive two elements are not equal\n // add absolute arr[i] to result\n if arr[i] != arr[i+1]\n result += abs(arr[i])\n // else skip next element too\n else\n i++;\n \n// special check for last two elements\n-> if (arr[n-2] != arr[n-1])\n result += arr[n-1]\n\n-> return result;" }, { "code": null, "e": 8978, "s": 8974, "text": "C++" }, { "code": null, "e": 8983, "s": 8978, "text": "Java" }, { "code": null, "e": 8992, "s": 8983, "text": "Python 3" }, { "code": null, "e": 8995, "s": 8992, "text": "C#" }, { "code": null, "e": 8999, "s": 8995, "text": "PHP" }, { "code": null, "e": 9010, "s": 8999, "text": "Javascript" }, { "code": "// CPP find maximum difference of subset sum#include <bits/stdc++.h>using namespace std; // function for maximum subset diffint maxDiff(int arr[], int n){ int result = 0; // sort the array sort(arr, arr + n); // calculate the result for (int i = 0; i < n - 1; i++) { if (arr[i] != arr[i + 1]) result += abs(arr[i]); else i++; } // check for last element if (arr[n - 2] != arr[n - 1]) result += abs(arr[n - 1]); // return result return result;} // driver programint main(){ int arr[] = { 4, 2, -3, 3, -2, -2, 8 }; int n = sizeof(arr) / sizeof(arr[0]); cout << \"Maximum Difference = \" << maxDiff(arr, n); return 0;}", "e": 9713, "s": 9010, "text": null }, { "code": "// java find maximum difference of// subset sumimport java. io.*;import java .util.*; public class GFG { // function for maximum subset diff static int maxDiff(int []arr, int n) { int result = 0; // sort the array Arrays.sort(arr); // calculate the result for (int i = 0; i < n - 1; i++) { if (arr[i] != arr[i + 1]) result += Math.abs(arr[i]); else i++; } // check for last element if (arr[n - 2] != arr[n - 1]) result += Math.abs(arr[n - 1]); // return result return result; } // driver program static public void main (String[] args) { int[] arr = { 4, 2, -3, 3, -2, -2, 8 }; int n = arr.length; System.out.println(\"Maximum Difference = \" + maxDiff(arr, n)); }} // This code is contributed by vt_m.", "e": 10665, "s": 9713, "text": null }, { "code": "# Python 3 find maximum difference# of subset sum # function for maximum subset diffdef maxDiff(arr, n): result = 0 # sort the array arr.sort() # calculate the result for i in range(n - 1): if (abs(arr[i]) != abs(arr[i + 1])): result += abs(arr[i]) else: pass # check for last element if (arr[n - 2] != arr[n - 1]): result += abs(arr[n - 1]) # return result return result # Driver Codeif __name__ == \"__main__\": arr = [ 4, 2, -3, 3, -2, -2, 8 ] n = len(arr) print(\"Maximum Difference = \" , maxDiff(arr, n)) # This code is contributed by ita_c", "e": 11316, "s": 10665, "text": null }, { "code": "// C# find maximum difference// of subset sumusing System; public class GFG { // function for maximum subset diff static int maxDiff(int []arr, int n) { int result = 0; // sort the array Array.Sort(arr); // calculate the result for (int i = 0; i < n - 1; i++) { if (arr[i] != arr[i + 1]) result += Math.Abs(arr[i]); else i++; } // check for last element if (arr[n - 2] != arr[n - 1]) result += Math.Abs(arr[n - 1]); // return result return result; } // driver program static public void Main () { int[] arr = { 4, 2, -3, 3, -2, -2, 8 }; int n = arr.Length; Console.WriteLine(\"Maximum Difference = \" + maxDiff(arr, n)); }} // This code is contributed by vt_m.", "e": 12224, "s": 11316, "text": null }, { "code": "<?php// PHP find maximum difference of subset sum // function for maximum subset difffunction maxDiff( $arr, $n){ $result = 0; // sort the array sort($arr); // calculate the result for ( $i = 0; $i < $n - 1; $i++) { if ($arr[$i] != $arr[$i + 1]) $result += abs($arr[$i]); else $i++; } // check for last element if ($arr[$n - 2] != $arr[$n - 1]) $result += abs($arr[$n - 1]); // return result return $result;} // Driver Code $arr = array( 4, 2, -3, 3, -2, -2, 8 ); $n = count($arr); echo \"Maximum Difference = \" , maxDiff($arr, $n); // This code is contributed by anuj_67.?>", "e": 12906, "s": 12224, "text": null }, { "code": "<script> // Javascript find maximum difference of subset sum // function for maximum subset difffunction maxDiff(arr, n){ var result = 0; // sort the array arr.sort((a,b)=> a-b) // calculate the result for (var i = 0; i < n - 1; i++) { if (arr[i] != arr[i + 1]) result += Math.abs(arr[i]); else i++; } // check for last element if (arr[n - 2] != arr[n - 1]) result += Math.abs(arr[n - 1]); // return result return result;} // driver programvar arr = [ 4, 2, -3, 3, -2, -2, 8 ];var n = arr.length;document.write( \"Maximum Difference = \" + maxDiff(arr, n)); </script>", "e": 13549, "s": 12906, "text": null }, { "code": null, "e": 13573, "s": 13549, "text": "Maximum Difference = 20" }, { "code": null, "e": 13614, "s": 13575, "text": "Algorithm with time complexity O(n): " }, { "code": null, "e": 13919, "s": 13614, "text": "make hash table for positive elements:\n for all positive elements(arr[i])\n if frequency == 1\n SubsetSum_1 += arr[i];\nmake hash table for negative elements:\n for all negative elements\n if frequency == 1\n SubsetSum_2 += arr[i];\nreturn abs(SubsetSum_1 - SubsetSum2)" }, { "code": null, "e": 13923, "s": 13919, "text": "C++" }, { "code": null, "e": 13928, "s": 13923, "text": "Java" }, { "code": null, "e": 13936, "s": 13928, "text": "Python3" }, { "code": null, "e": 13939, "s": 13936, "text": "C#" }, { "code": null, "e": 13950, "s": 13939, "text": "Javascript" }, { "code": "// CPP find maximum difference of subset sum#include <bits/stdc++.h>using namespace std; // function for maximum subset diffint maxDiff(int arr[], int n){ unordered_map<int, int> hashPositive; unordered_map<int, int> hashNegative; int SubsetSum_1 = 0, SubsetSum_2 = 0; // construct hash for positive elements for (int i = 0; i <= n - 1; i++) if (arr[i] > 0) hashPositive[arr[i]]++; // calculate subset sum for positive elements for (int i = 0; i <= n - 1; i++) if (arr[i] > 0 && hashPositive[arr[i]] == 1) SubsetSum_1 += arr[i]; // construct hash for negative elements for (int i = 0; i <= n - 1; i++) if (arr[i] < 0) hashNegative[abs(arr[i])]++; // calculate subset sum for negative elements for (int i = 0; i <= n - 1; i++) if (arr[i] < 0 && hashNegative[abs(arr[i])] == 1) SubsetSum_2 += arr[i]; return abs(SubsetSum_1 - SubsetSum_2);} // driver programint main(){ int arr[] = { 4, 2, -3, 3, -2, -2, 8 }; int n = sizeof(arr) / sizeof(arr[0]); cout << \"Maximum Difference = \" << maxDiff(arr, n); return 0;}", "e": 15096, "s": 13950, "text": null }, { "code": "// Java find maximum// difference of subset sumimport java.util.*;class GFG{ // Function for maximum subset diffpublic static int maxDiff(int arr[], int n){ HashMap<Integer, Integer> hashPositive = new HashMap<>(); HashMap<Integer, Integer> hashNegative = new HashMap<>(); int SubsetSum_1 = 0, SubsetSum_2 = 0; // Construct hash for // positive elements for (int i = 0; i <= n - 1; i++) { if (arr[i] > 0) { if(hashPositive.containsKey(arr[i])) { hashPositive.replace(arr[i], hashPositive.get(arr[i]) + 1); } else { hashPositive.put(arr[i], 1); } } } // Calculate subset sum // for positive elements for (int i = 0; i <= n - 1; i++) { if(arr[i] > 0 && hashPositive.containsKey(arr[i])) { if(hashPositive.get(arr[i]) == 1) { SubsetSum_1 += arr[i]; } } } // Construct hash for // negative elements for (int i = 0; i <= n - 1; i++) { if (arr[i] < 0) { if(hashNegative.containsKey(Math.abs(arr[i]))) { hashNegative.replace(Math.abs(arr[i]), hashNegative.get(Math.abs(arr[i])) + 1); } else { hashNegative.put(Math.abs(arr[i]), 1); } } } // Calculate subset sum for // negative elements for (int i = 0; i <= n - 1; i++) { if (arr[i] < 0 && hashNegative.containsKey(Math.abs(arr[i]))) { if(hashNegative.get(Math.abs(arr[i])) == 1) { SubsetSum_2 += arr[i]; } } } return Math.abs(SubsetSum_1 - SubsetSum_2);} // Driver codepublic static void main(String[] args){ int arr[] = {4, 2, -3, 3, -2, -2, 8}; int n = arr.length; System.out.print(\"Maximum Difference = \" + maxDiff(arr, n));}} // This code is contributed by divyeshrabadiya07", "e": 16930, "s": 15096, "text": null }, { "code": "# Python3 find maximum difference of subset sum # function for maximum subset diffdef maxDiff(arr, n): hashPositive = dict() hashNegative = dict() SubsetSum_1, SubsetSum_2 = 0, 0 # construct hash for positive elements for i in range(n): if (arr[i] > 0): hashPositive[arr[i]] = \\ hashPositive.get(arr[i], 0) + 1 # calculate subset sum for positive elements for i in range(n): if (arr[i] > 0 and arr[i] in hashPositive.keys() and hashPositive[arr[i]] == 1): SubsetSum_1 += arr[i] # construct hash for negative elements for i in range(n): if (arr[i] < 0): hashNegative[abs(arr[i])] = \\ hashNegative.get(abs(arr[i]), 0) + 1 # calculate subset sum for negative elements for i in range(n): if (arr[i] < 0 and abs(arr[i]) in hashNegative.keys() and hashNegative[abs(arr[i])] == 1): SubsetSum_2 += arr[i] return abs(SubsetSum_1 - SubsetSum_2) # Driver Codearr = [4, 2, -3, 3, -2, -2, 8]n = len(arr)print(\"Maximum Difference =\", maxDiff(arr, n)) # This code is contributed by mohit kumar", "e": 18098, "s": 16930, "text": null }, { "code": "// C# find maximum// difference of subset sumusing System;using System.Collections.Generic; class GFG { // Function for maximum subset diff static int maxDiff(int[] arr, int n) { Dictionary<int, int> hashPositive = new Dictionary<int, int>(); Dictionary<int, int> hashNegative = new Dictionary<int, int>(); int SubsetSum_1 = 0, SubsetSum_2 = 0; // Construct hash for // positive elements for (int i = 0; i <= n - 1; i++) { if (arr[i] > 0) { if(hashPositive.ContainsKey(arr[i])) { hashPositive[arr[i]] += 1; } else { hashPositive.Add(arr[i], 1); } } } // Calculate subset sum // for positive elements for (int i = 0; i <= n - 1; i++) { if(arr[i] > 0 && hashPositive.ContainsKey(arr[i])) { if(hashPositive[arr[i]] == 1) { SubsetSum_1 += arr[i]; } } } // Construct hash for // negative elements for (int i = 0; i <= n - 1; i++) { if (arr[i] < 0) { if(hashNegative.ContainsKey(Math.Abs(arr[i]))) { hashNegative[Math.Abs(arr[i])] += 1; } else { hashNegative.Add(Math.Abs(arr[i]), 1); } } } // Calculate subset sum for // negative elements for (int i = 0; i <= n - 1; i++) { if (arr[i] < 0 && hashNegative.ContainsKey(Math.Abs(arr[i]))) { if(hashNegative[Math.Abs(arr[i])] == 1) { SubsetSum_2 += arr[i]; } } } return Math.Abs(SubsetSum_1 - SubsetSum_2); } // Driver code static void Main() { int[] arr = {4, 2, -3, 3, -2, -2, 8}; int n = arr.Length; Console.WriteLine(\"Maximum Difference = \" + maxDiff(arr, n)); }} // This code is contributed by divesh072019", "e": 20102, "s": 18098, "text": null }, { "code": "<script>// Javascript find maximum// difference of subset sum // Function for maximum subset difffunction maxDiff(arr,n){ let hashPositive = new Map(); let hashNegative = new Map(); let SubsetSum_1 = 0, SubsetSum_2 = 0; // Construct hash for // positive elements for (let i = 0; i <= n - 1; i++) { if (arr[i] > 0) { if(hashPositive.has(arr[i])) { hashPositive.set(arr[i], hashPositive.get(arr[i]) + 1); } else { hashPositive.set(arr[i], 1); } } } // Calculate subset sum // for positive elements for (let i = 0; i <= n - 1; i++) { if(arr[i] > 0 && hashPositive.has(arr[i])) { if(hashPositive.get(arr[i]) == 1) { SubsetSum_1 += arr[i]; } } } // Construct hash for // negative elements for (let i = 0; i <= n - 1; i++) { if (arr[i] < 0) { if(hashNegative.has(Math.abs(arr[i]))) { hashNegative.set(Math.abs(arr[i]), hashNegative.get(Math.abs(arr[i])) + 1); } else { hashNegative.set(Math.abs(arr[i]), 1); } } } // Calculate subset sum for // negative elements for (let i = 0; i <= n - 1; i++) { if (arr[i] < 0 && hashNegative.has(Math.abs(arr[i]))) { if(hashNegative.get(Math.abs(arr[i])) == 1) { SubsetSum_2 += arr[i]; } } } return Math.abs(SubsetSum_1 - SubsetSum_2); } // Driver code let arr = [4, 2, -3, 3, -2, -2, 8];let n = arr.length;document.write(\"Maximum Difference = \" + maxDiff(arr, n)); // This code is contributed by rag2127</script>", "e": 21746, "s": 20102, "text": null }, { "code": null, "e": 21770, "s": 21746, "text": "Maximum Difference = 20" }, { "code": null, "e": 21777, "s": 21772, "text": "vt_m" }, { "code": null, "e": 21790, "s": 21777, "text": "nitin mittal" }, { "code": null, "e": 21802, "s": 21790, "text": "manishshaw1" }, { "code": null, "e": 21808, "s": 21802, "text": "ukasp" }, { "code": null, "e": 21823, "s": 21808, "text": "mohit kumar 29" }, { "code": null, "e": 21841, "s": 21823, "text": "divyeshrabadiya07" }, { "code": null, "e": 21855, "s": 21841, "text": "divyesh072019" }, { "code": null, "e": 21877, "s": 21855, "text": "susmitakundugoaldanga" }, { "code": null, "e": 21887, "s": 21877, "text": "rutvik_56" }, { "code": null, "e": 21895, "s": 21887, "text": "rag2127" }, { "code": null, "e": 21912, "s": 21895, "text": "surinderdawra388" }, { "code": null, "e": 21919, "s": 21912, "text": "Arrays" }, { "code": null, "e": 21924, "s": 21919, "text": "Hash" }, { "code": null, "e": 21932, "s": 21924, "text": "Sorting" }, { "code": null, "e": 21951, "s": 21932, "text": "Technical Scripter" }, { "code": null, "e": 21958, "s": 21951, "text": "Arrays" }, { "code": null, "e": 21963, "s": 21958, "text": "Hash" }, { "code": null, "e": 21971, "s": 21963, "text": "Sorting" } ]
Print Doubly Linked list in Reverse Order
08 Jul, 2022 Given a doubly-linked list of positive integers. The task is to print the given doubly linked list data in reverse order. Examples: Input: List = 1 <=> 2 <=> 3 <=> 4 <=> 5 Output: 5 4 3 2 1 Input: 10 <=> 20 <=> 30 <=> 40 Output: 40 30 20 10 Approach: Take a pointer to point to head of the doubly linked list. Now, start traversing through the linked list till the end. After reaching last node, start traversing in backward direction and simultaneously print the node->data. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ Program to print doubly// linked list in reverse order#include <bits/stdc++.h>using namespace std; // Doubly linked list nodestruct Node { int data; struct Node* next; struct Node* prev;}; // Function to print nodes of Doubly// Linked List in reverse ordervoid reversePrint(struct Node** head_ref){ struct Node* tail = *head_ref; // Traversing till tail of the linked list while (tail->next != NULL) { tail = tail->next; } // Traversing linked list from tail // and printing the node->data while (tail != *head_ref) { cout << tail->data << " "; tail = tail->prev; } cout << tail->data << endl;} /* UTILITY FUNCTIONS */// Function to insert a node at the// beginning of the Doubly Linked Listvoid push(struct Node** head_ref, int new_data){ // allocate node struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); // put in the data new_node->data = new_data; // since we are adding at the beginning, // prev is always NULL new_node->prev = NULL; // link the old list off the new node new_node->next = (*head_ref); // change prev of head node to new node if ((*head_ref) != NULL) (*head_ref)->prev = new_node; // move the head to point to the new node (*head_ref) = new_node;} // Driver Codeint main(){ // Start with the empty list struct Node* head = NULL; // Let us create a sorted linked list // to test the functions // Created linked list will be 10->8->4->2 push(&head, 2); push(&head, 4); push(&head, 8); push(&head, 10); cout << "Linked List elements in reverse order : " << endl; reversePrint(&head); return 0;} // Java Program to print doubly// linked list in reverse orderclass Sol{ // Doubly linked list nodestatic class Node{ int data; Node next; Node prev;}; // Function to print nodes of Doubly// Linked List in reverse orderstatic void reversePrint( Node head_ref){ Node tail = head_ref; // Traversing till tail of the linked list while (tail.next != null) { tail = tail.next; } // Traversing linked list from tail // and printing the node.data while (tail != head_ref) { System.out.print( tail.data + " "); tail = tail.prev; } System.out.println( tail.data );} // UTILITY FUNCTIONS /// Function to insert a node at the// beginning of the Doubly Linked Liststatic Node push( Node head_ref, int new_data){ // allocate node Node new_node = new Node(); // put in the data new_node.data = new_data; // since we are adding at the beginning, // prev is always null new_node.prev = null; // link the old list off the new node new_node.next = (head_ref); // change prev of head node to new node if ((head_ref) != null) (head_ref).prev = new_node; // move the head to point to the new node (head_ref) = new_node; return head_ref;} // Driver Codepublic static void main(String args[]){ // Start with the empty list Node head = null; // Let us create a sorted linked list // to test the functions // Created linked list will be 10.8.4.2 head = push(head, 2); head = push(head, 4); head = push(head, 8); head = push(head, 10); System.out.print( "Linked List elements in reverse order : " ); reversePrint(head);}} // This code is contributed by Arnab Kundu # Python3 Program to print doubly# linked list in reverse orderimport math # Doubly linked list nodeclass Node: def __init__(self, data): self.data = data self.next = None # Function to print nodes of Doubly# Linked List in reverse orderdef reversePrint(head_ref): tail = head_ref # Traversing till tail of the linked list while (tail.next != None): tail = tail.next # Traversing linked list from tail # and print the node.data while (tail != head_ref): print(tail.data, end = " ") tail = tail.prev print(tail.data) # UTILITY FUNCTIONS# Function to insert a node at the# beginning of the Doubly Linked Listdef push(head_ref, new_data): # allocate node new_node = Node(new_data) # put in the data new_node.data = new_data # since we are adding at the beginning, # prev is always None new_node.prev = None # link the old list off the new node new_node.next = head_ref # change prev of head node to new node if (head_ref != None): head_ref.prev = new_node # move the head to po to the new node head_ref = new_node return head_ref # Driver Codeif __name__=='__main__': # Start with the empty list head = None # Let us create a sorted linked list # to test the functions # Created linked list will be 10.8.4.2 head = push(head, 2) head = push(head, 4) head = push(head, 8) head = push(head, 10) print("Linked List elements in reverse order : ") reversePrint(head) # This code is contributed by Srathore // C# Program to print doubly// linked list in reverse orderusing System; class Sol{ // Doubly linked list nodepublic class Node{ public int data; public Node next; public Node prev;}; // Function to print nodes of Doubly// Linked List in reverse orderstatic void reversePrint( Node head_ref){ Node tail = head_ref; // Traversing till tail of the linked list while (tail.next != null) { tail = tail.next; } // Traversing linked list from tail // and printing the node.data while (tail != head_ref) { Console.Write( tail.data + " "); tail = tail.prev; } Console.WriteLine( tail.data );} // UTILITY FUNCTIONS /// Function to insert a node at the// beginning of the Doubly Linked Liststatic Node push( Node head_ref, int new_data){ // allocate node Node new_node = new Node(); // put in the data new_node.data = new_data; // since we are adding at the beginning, // prev is always null new_node.prev = null; // link the old list off the new node new_node.next = (head_ref); // change prev of head node to new node if ((head_ref) != null) (head_ref).prev = new_node; // move the head to point to the new node (head_ref) = new_node; return head_ref;} // Driver Codepublic static void Main(String []args){ // Start with the empty list Node head = null; // Let us create a sorted linked list // to test the functions // Created linked list will be 10.8.4.2 head = push(head, 2); head = push(head, 4); head = push(head, 8); head = push(head, 10); Console.Write( "Linked List elements in reverse order : " ); reversePrint(head);}} // This code contributed by Rajput-Ji <script> // JavaScript Program to print doubly // linked list in reverse order // Doubly linked list node class Node { constructor() { this.data = 0; this.next = null; this.prev = null; } } // Function to print nodes of Doubly // Linked List in reverse order function reversePrint(head_ref) { var tail = head_ref; // Traversing till tail of the linked list while (tail.next != null) { tail = tail.next; } // Traversing linked list from tail // and printing the node.data while (tail != head_ref) { document.write(tail.data + " "); tail = tail.prev; } document.write(tail.data + "<br>"); } // UTILITY FUNCTIONS / // Function to insert a node at the // beginning of the Doubly Linked List function push(head_ref, new_data) { // allocate node var new_node = new Node(); // put in the data new_node.data = new_data; // since we are adding at the beginning, // prev is always null new_node.prev = null; // link the old list off the new node new_node.next = head_ref; // change prev of head node to new node if (head_ref != null) head_ref.prev = new_node; // move the head to point to the new node head_ref = new_node; return head_ref; } // Driver Code // Start with the empty list var head = null; // Let us create a sorted linked list // to test the functions // Created linked list will be 10.8.4.2 head = push(head, 2); head = push(head, 4); head = push(head, 8); head = push(head, 10); document.write("Linked List elements in reverse order : <br>"); reversePrint(head); </script> Linked List elements in reverse order : 2 4 8 10 Time complexity: O(N) where N is no of nodes in Doubly Linked List Auxiliary Space: O(N) andrew1234 Rajput-Ji Akanksha_Rai sapnasingh4991 rdtank simranarora5sos varshagumber28 kumargaurav97520 doubly linked list Reverse Linked List Linked List Reverse Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Data Structures What is Data Structure: Types, Classifications and Applications Types of Linked List Circular Singly Linked List | Insertion Find first node of loop in a linked list Add two numbers represented by linked lists | Set 2 Flattening a Linked List Real-time application of Data Structures Insert a node at a specific position in a linked list Clone a linked list with next and random pointer | Set 1
[ { "code": null, "e": 28, "s": 0, "text": "\n08 Jul, 2022" }, { "code": null, "e": 151, "s": 28, "text": "Given a doubly-linked list of positive integers. The task is to print the given doubly linked list data in reverse order. " }, { "code": null, "e": 162, "s": 151, "text": "Examples: " }, { "code": null, "e": 282, "s": 162, "text": "Input: List = 1 <=> 2 <=> 3 <=> 4 <=> 5\nOutput: 5 4 3 2 1\n\nInput: 10 <=> 20 <=> 30 <=> 40\nOutput: 40 30 20 10" }, { "code": null, "e": 293, "s": 282, "text": "Approach: " }, { "code": null, "e": 352, "s": 293, "text": "Take a pointer to point to head of the doubly linked list." }, { "code": null, "e": 412, "s": 352, "text": "Now, start traversing through the linked list till the end." }, { "code": null, "e": 518, "s": 412, "text": "After reaching last node, start traversing in backward direction and simultaneously print the node->data." }, { "code": null, "e": 570, "s": 518, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 574, "s": 570, "text": "C++" }, { "code": null, "e": 579, "s": 574, "text": "Java" }, { "code": null, "e": 587, "s": 579, "text": "Python3" }, { "code": null, "e": 590, "s": 587, "text": "C#" }, { "code": null, "e": 601, "s": 590, "text": "Javascript" }, { "code": "// C++ Program to print doubly// linked list in reverse order#include <bits/stdc++.h>using namespace std; // Doubly linked list nodestruct Node { int data; struct Node* next; struct Node* prev;}; // Function to print nodes of Doubly// Linked List in reverse ordervoid reversePrint(struct Node** head_ref){ struct Node* tail = *head_ref; // Traversing till tail of the linked list while (tail->next != NULL) { tail = tail->next; } // Traversing linked list from tail // and printing the node->data while (tail != *head_ref) { cout << tail->data << \" \"; tail = tail->prev; } cout << tail->data << endl;} /* UTILITY FUNCTIONS */// Function to insert a node at the// beginning of the Doubly Linked Listvoid push(struct Node** head_ref, int new_data){ // allocate node struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); // put in the data new_node->data = new_data; // since we are adding at the beginning, // prev is always NULL new_node->prev = NULL; // link the old list off the new node new_node->next = (*head_ref); // change prev of head node to new node if ((*head_ref) != NULL) (*head_ref)->prev = new_node; // move the head to point to the new node (*head_ref) = new_node;} // Driver Codeint main(){ // Start with the empty list struct Node* head = NULL; // Let us create a sorted linked list // to test the functions // Created linked list will be 10->8->4->2 push(&head, 2); push(&head, 4); push(&head, 8); push(&head, 10); cout << \"Linked List elements in reverse order : \" << endl; reversePrint(&head); return 0;}", "e": 2289, "s": 601, "text": null }, { "code": "// Java Program to print doubly// linked list in reverse orderclass Sol{ // Doubly linked list nodestatic class Node{ int data; Node next; Node prev;}; // Function to print nodes of Doubly// Linked List in reverse orderstatic void reversePrint( Node head_ref){ Node tail = head_ref; // Traversing till tail of the linked list while (tail.next != null) { tail = tail.next; } // Traversing linked list from tail // and printing the node.data while (tail != head_ref) { System.out.print( tail.data + \" \"); tail = tail.prev; } System.out.println( tail.data );} // UTILITY FUNCTIONS /// Function to insert a node at the// beginning of the Doubly Linked Liststatic Node push( Node head_ref, int new_data){ // allocate node Node new_node = new Node(); // put in the data new_node.data = new_data; // since we are adding at the beginning, // prev is always null new_node.prev = null; // link the old list off the new node new_node.next = (head_ref); // change prev of head node to new node if ((head_ref) != null) (head_ref).prev = new_node; // move the head to point to the new node (head_ref) = new_node; return head_ref;} // Driver Codepublic static void main(String args[]){ // Start with the empty list Node head = null; // Let us create a sorted linked list // to test the functions // Created linked list will be 10.8.4.2 head = push(head, 2); head = push(head, 4); head = push(head, 8); head = push(head, 10); System.out.print( \"Linked List elements in reverse order : \" ); reversePrint(head);}} // This code is contributed by Arnab Kundu", "e": 3983, "s": 2289, "text": null }, { "code": "# Python3 Program to print doubly# linked list in reverse orderimport math # Doubly linked list nodeclass Node: def __init__(self, data): self.data = data self.next = None # Function to print nodes of Doubly# Linked List in reverse orderdef reversePrint(head_ref): tail = head_ref # Traversing till tail of the linked list while (tail.next != None): tail = tail.next # Traversing linked list from tail # and print the node.data while (tail != head_ref): print(tail.data, end = \" \") tail = tail.prev print(tail.data) # UTILITY FUNCTIONS# Function to insert a node at the# beginning of the Doubly Linked Listdef push(head_ref, new_data): # allocate node new_node = Node(new_data) # put in the data new_node.data = new_data # since we are adding at the beginning, # prev is always None new_node.prev = None # link the old list off the new node new_node.next = head_ref # change prev of head node to new node if (head_ref != None): head_ref.prev = new_node # move the head to po to the new node head_ref = new_node return head_ref # Driver Codeif __name__=='__main__': # Start with the empty list head = None # Let us create a sorted linked list # to test the functions # Created linked list will be 10.8.4.2 head = push(head, 2) head = push(head, 4) head = push(head, 8) head = push(head, 10) print(\"Linked List elements in reverse order : \") reversePrint(head) # This code is contributed by Srathore", "e": 5547, "s": 3983, "text": null }, { "code": "// C# Program to print doubly// linked list in reverse orderusing System; class Sol{ // Doubly linked list nodepublic class Node{ public int data; public Node next; public Node prev;}; // Function to print nodes of Doubly// Linked List in reverse orderstatic void reversePrint( Node head_ref){ Node tail = head_ref; // Traversing till tail of the linked list while (tail.next != null) { tail = tail.next; } // Traversing linked list from tail // and printing the node.data while (tail != head_ref) { Console.Write( tail.data + \" \"); tail = tail.prev; } Console.WriteLine( tail.data );} // UTILITY FUNCTIONS /// Function to insert a node at the// beginning of the Doubly Linked Liststatic Node push( Node head_ref, int new_data){ // allocate node Node new_node = new Node(); // put in the data new_node.data = new_data; // since we are adding at the beginning, // prev is always null new_node.prev = null; // link the old list off the new node new_node.next = (head_ref); // change prev of head node to new node if ((head_ref) != null) (head_ref).prev = new_node; // move the head to point to the new node (head_ref) = new_node; return head_ref;} // Driver Codepublic static void Main(String []args){ // Start with the empty list Node head = null; // Let us create a sorted linked list // to test the functions // Created linked list will be 10.8.4.2 head = push(head, 2); head = push(head, 4); head = push(head, 8); head = push(head, 10); Console.Write( \"Linked List elements in reverse order : \" ); reversePrint(head);}} // This code contributed by Rajput-Ji", "e": 7270, "s": 5547, "text": null }, { "code": "<script> // JavaScript Program to print doubly // linked list in reverse order // Doubly linked list node class Node { constructor() { this.data = 0; this.next = null; this.prev = null; } } // Function to print nodes of Doubly // Linked List in reverse order function reversePrint(head_ref) { var tail = head_ref; // Traversing till tail of the linked list while (tail.next != null) { tail = tail.next; } // Traversing linked list from tail // and printing the node.data while (tail != head_ref) { document.write(tail.data + \" \"); tail = tail.prev; } document.write(tail.data + \"<br>\"); } // UTILITY FUNCTIONS / // Function to insert a node at the // beginning of the Doubly Linked List function push(head_ref, new_data) { // allocate node var new_node = new Node(); // put in the data new_node.data = new_data; // since we are adding at the beginning, // prev is always null new_node.prev = null; // link the old list off the new node new_node.next = head_ref; // change prev of head node to new node if (head_ref != null) head_ref.prev = new_node; // move the head to point to the new node head_ref = new_node; return head_ref; } // Driver Code // Start with the empty list var head = null; // Let us create a sorted linked list // to test the functions // Created linked list will be 10.8.4.2 head = push(head, 2); head = push(head, 4); head = push(head, 8); head = push(head, 10); document.write(\"Linked List elements in reverse order : <br>\"); reversePrint(head); </script>", "e": 9132, "s": 7270, "text": null }, { "code": null, "e": 9182, "s": 9132, "text": "Linked List elements in reverse order : \n2 4 8 10" }, { "code": null, "e": 9251, "s": 9184, "text": "Time complexity: O(N) where N is no of nodes in Doubly Linked List" }, { "code": null, "e": 9273, "s": 9251, "text": "Auxiliary Space: O(N)" }, { "code": null, "e": 9284, "s": 9273, "text": "andrew1234" }, { "code": null, "e": 9294, "s": 9284, "text": "Rajput-Ji" }, { "code": null, "e": 9307, "s": 9294, "text": "Akanksha_Rai" }, { "code": null, "e": 9322, "s": 9307, "text": "sapnasingh4991" }, { "code": null, "e": 9329, "s": 9322, "text": "rdtank" }, { "code": null, "e": 9345, "s": 9329, "text": "simranarora5sos" }, { "code": null, "e": 9360, "s": 9345, "text": "varshagumber28" }, { "code": null, "e": 9377, "s": 9360, "text": "kumargaurav97520" }, { "code": null, "e": 9396, "s": 9377, "text": "doubly linked list" }, { "code": null, "e": 9404, "s": 9396, "text": "Reverse" }, { "code": null, "e": 9416, "s": 9404, "text": "Linked List" }, { "code": null, "e": 9428, "s": 9416, "text": "Linked List" }, { "code": null, "e": 9436, "s": 9428, "text": "Reverse" }, { "code": null, "e": 9534, "s": 9436, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 9566, "s": 9534, "text": "Introduction to Data Structures" }, { "code": null, "e": 9630, "s": 9566, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 9651, "s": 9630, "text": "Types of Linked List" }, { "code": null, "e": 9691, "s": 9651, "text": "Circular Singly Linked List | Insertion" }, { "code": null, "e": 9732, "s": 9691, "text": "Find first node of loop in a linked list" }, { "code": null, "e": 9784, "s": 9732, "text": "Add two numbers represented by linked lists | Set 2" }, { "code": null, "e": 9809, "s": 9784, "text": "Flattening a Linked List" }, { "code": null, "e": 9850, "s": 9809, "text": "Real-time application of Data Structures" }, { "code": null, "e": 9904, "s": 9850, "text": "Insert a node at a specific position in a linked list" } ]
Change Axis Labels, Set Title and Figure Size to Plots with Seaborn
26 Nov, 2020 Seaborn is Python’s visualization library built as an extension to Matplotlib. Seaborn has Axes-level functions (scatterplot, regplot, boxplot, kdeplot, etc.) as well as Figure-level functions (lmplot, factorplot, jointplot, relplot etc.). Axes-level functions return Matplotlib axes objects with the plot drawn on them while figure-level functions include axes that are always organized in a meaningful way. The basic customization that a graph needs to make it understandable is setting the title, setting the axis labels, and adjusting the figure size. Any customization made is on the axes object for axes-level functions and the figure object for figure-level functions. Note: Axes in the above explanation refers to a part of the figure or the top layer of a figure and is not the mathematical term for more than one axis. Consider a plot on a figure. This plot axes. Now, consider multiple subplots on a figure. Each of these subplots is one axes. Let us see some examples to better understand customization with Seaborn. Python # Import required librariesimport matplotlib.pyplot as pltimport seaborn as sns # Load data settips = sns.load_dataset( "tips" )tips.head() Output: Example 1: Customizing plot with axes object For axes-level functions, pass the figsize argument to the plt.subplots() function to set the figure size. The function plt.subplots() returns Figure and Axes objects. These objects are created ahead of time and later the plots are drawn on it. We make use of the set_title(), set_xlabel(), and set_ylabel() functions to change axis labels and set the title for a plot. We can set the size of the text with size attribute. Make sure to assign the axes-level object while creating the plot. This object is then used for setting the title and labels as shown below. Python # Set figure size (width, height) in inchesfig, ax = plt.subplots(figsize = ( 5 , 3 )) # Plot the scatterplotsns.scatterplot( ax = ax , x = "total_bill" , y = "tip" , data = tips ) # Set label for x-axisax.set_xlabel( "Total Bill (USD)" , size = 12 ) # Set label for y-axisax.set_ylabel( "Tips (USD)" , size = 12 ) # Set title for plotax.set_title( "Bill vs Tips" , size = 24 ) # Display figureplt.show() Output: Example 2: Customizing scatter plot with pyplot object We can also change the axis labels and set the plot title with the matplotlib.pyplot object using xlabel(), ylabel() and title() functions. Similar to the above example, we can set the size of the text with the size attribute. The function plt.figure() creates a Figure instance and the figsize argument allows to set the figure size. Python # Set figure size (width, height) in inchesplt.figure(figsize = ( 5 , 3 )) # Plot scatterplotsns.scatterplot( x = "total_bill" , y = "tip" , data = tips ) # Set label for x-axisplt.xlabel( "Total Bill (USD)" , size = 12 ) # Set label for y-axisplt.ylabel( "Tips (USD)" , size = 12 ) # Set title for figureplt.title( "Bill vs Tips" , size = 24 ) # Display figureplt.show() Output: Example 3: Customizing multiple plots in the same figure Seaborn’s relplot function returns a FacetGrid object which is a figure-level object. This object allows the convenient management of subplots. To give a title to the complete figure containing multiple subplots, we use the suptitle() method. The subplots_adjust() method is used to avoid overlapping of subplot titles and the figure title by specifying the top, bottom, left, and right edge positions of the subplots. To set the figure size, pass a dictionary with the key ‘figure.figsize’ in the set() method. The set() method allows to set multiple theme parameters in a single step. Python # Set figure sizesns.set( rc = {'figure.figsize' : ( 20, 20 ), 'axes.labelsize' : 12 }) # Plot scatter plotg = sns.relplot(data = tips , x = "total_bill" , y = "tip" , col = "time" , hue = "day" , style = "day" , kind = "scatter" ) # Title for the complete figureg.fig.suptitle("Tips by time of day" , fontsize = 'x-large' , fontweight = 'bold' ) # Adjust subplots so that titles don't overlapg.fig.subplots_adjust( top = 0.85 ) # Set x-axis and y-axis labelsg.set_axis_labels( "Tip" , "Total Bill (USD)" ) # Display the figureplt.show() Output: Python-Seaborn Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Nov, 2020" }, { "code": null, "e": 705, "s": 28, "text": "Seaborn is Python’s visualization library built as an extension to Matplotlib. Seaborn has Axes-level functions (scatterplot, regplot, boxplot, kdeplot, etc.) as well as Figure-level functions (lmplot, factorplot, jointplot, relplot etc.). Axes-level functions return Matplotlib axes objects with the plot drawn on them while figure-level functions include axes that are always organized in a meaningful way. The basic customization that a graph needs to make it understandable is setting the title, setting the axis labels, and adjusting the figure size. Any customization made is on the axes object for axes-level functions and the figure object for figure-level functions. " }, { "code": null, "e": 984, "s": 705, "text": "Note: Axes in the above explanation refers to a part of the figure or the top layer of a figure and is not the mathematical term for more than one axis. Consider a plot on a figure. This plot axes. Now, consider multiple subplots on a figure. Each of these subplots is one axes." }, { "code": null, "e": 1058, "s": 984, "text": "Let us see some examples to better understand customization with Seaborn." }, { "code": null, "e": 1065, "s": 1058, "text": "Python" }, { "code": "# Import required librariesimport matplotlib.pyplot as pltimport seaborn as sns # Load data settips = sns.load_dataset( \"tips\" )tips.head()", "e": 1206, "s": 1065, "text": null }, { "code": null, "e": 1214, "s": 1206, "text": "Output:" }, { "code": null, "e": 1259, "s": 1214, "text": "Example 1: Customizing plot with axes object" }, { "code": null, "e": 1823, "s": 1259, "text": "For axes-level functions, pass the figsize argument to the plt.subplots() function to set the figure size. The function plt.subplots() returns Figure and Axes objects. These objects are created ahead of time and later the plots are drawn on it. We make use of the set_title(), set_xlabel(), and set_ylabel() functions to change axis labels and set the title for a plot. We can set the size of the text with size attribute. Make sure to assign the axes-level object while creating the plot. This object is then used for setting the title and labels as shown below." }, { "code": null, "e": 1830, "s": 1823, "text": "Python" }, { "code": "# Set figure size (width, height) in inchesfig, ax = plt.subplots(figsize = ( 5 , 3 )) # Plot the scatterplotsns.scatterplot( ax = ax , x = \"total_bill\" , y = \"tip\" , data = tips ) # Set label for x-axisax.set_xlabel( \"Total Bill (USD)\" , size = 12 ) # Set label for y-axisax.set_ylabel( \"Tips (USD)\" , size = 12 ) # Set title for plotax.set_title( \"Bill vs Tips\" , size = 24 ) # Display figureplt.show()", "e": 2240, "s": 1830, "text": null }, { "code": null, "e": 2248, "s": 2240, "text": "Output:" }, { "code": null, "e": 2303, "s": 2248, "text": "Example 2: Customizing scatter plot with pyplot object" }, { "code": null, "e": 2638, "s": 2303, "text": "We can also change the axis labels and set the plot title with the matplotlib.pyplot object using xlabel(), ylabel() and title() functions. Similar to the above example, we can set the size of the text with the size attribute. The function plt.figure() creates a Figure instance and the figsize argument allows to set the figure size." }, { "code": null, "e": 2645, "s": 2638, "text": "Python" }, { "code": "# Set figure size (width, height) in inchesplt.figure(figsize = ( 5 , 3 )) # Plot scatterplotsns.scatterplot( x = \"total_bill\" , y = \"tip\" , data = tips ) # Set label for x-axisplt.xlabel( \"Total Bill (USD)\" , size = 12 ) # Set label for y-axisplt.ylabel( \"Tips (USD)\" , size = 12 ) # Set title for figureplt.title( \"Bill vs Tips\" , size = 24 ) # Display figureplt.show()", "e": 3022, "s": 2645, "text": null }, { "code": null, "e": 3030, "s": 3022, "text": "Output:" }, { "code": null, "e": 3087, "s": 3030, "text": "Example 3: Customizing multiple plots in the same figure" }, { "code": null, "e": 3674, "s": 3087, "text": "Seaborn’s relplot function returns a FacetGrid object which is a figure-level object. This object allows the convenient management of subplots. To give a title to the complete figure containing multiple subplots, we use the suptitle() method. The subplots_adjust() method is used to avoid overlapping of subplot titles and the figure title by specifying the top, bottom, left, and right edge positions of the subplots. To set the figure size, pass a dictionary with the key ‘figure.figsize’ in the set() method. The set() method allows to set multiple theme parameters in a single step." }, { "code": null, "e": 3681, "s": 3674, "text": "Python" }, { "code": "# Set figure sizesns.set( rc = {'figure.figsize' : ( 20, 20 ), 'axes.labelsize' : 12 }) # Plot scatter plotg = sns.relplot(data = tips , x = \"total_bill\" , y = \"tip\" , col = \"time\" , hue = \"day\" , style = \"day\" , kind = \"scatter\" ) # Title for the complete figureg.fig.suptitle(\"Tips by time of day\" , fontsize = 'x-large' , fontweight = 'bold' ) # Adjust subplots so that titles don't overlapg.fig.subplots_adjust( top = 0.85 ) # Set x-axis and y-axis labelsg.set_axis_labels( \"Tip\" , \"Total Bill (USD)\" ) # Display the figureplt.show()", "e": 4316, "s": 3681, "text": null }, { "code": null, "e": 4324, "s": 4316, "text": "Output:" }, { "code": null, "e": 4339, "s": 4324, "text": "Python-Seaborn" }, { "code": null, "e": 4346, "s": 4339, "text": "Python" } ]
Sort array of objects by object fields in PHP
04 Jan, 2019 Given an array of objects and the task is to sort the array by object by given fields. Approach:The usort() function is an inbuilt function in PHP which is used to sort the array of elements conditionally with a given comparator function. The usort() function can also be used to sort an array of objects by object field. Call usort() function with first argument as the array of objects and second argument as the comparator function on the basis of which comparison between two array objects has to be made. Example: <?php // PHP program to show sorting of // array of objects by object fields // School Data array$gfg_array = array( array( 'score' => '100', 'name' => 'Sam', 'subject' => 'Data Structures' ), array( 'score' => '50', 'name' => 'Tanya', 'subject' => 'Advanced Algorithms' ), array( 'score' => '75', 'name' => 'Jack', 'subject' => 'Distributed Computing' )); // Class for encapsulating school dataclass geekSchool { var $score, $name, $subject; // Constructor for class initialization public function geekSchool($data) { $this->name = $data['name']; $this->score = $data['score']; $this->subject = $data['subject']; }} // Function to convert array data to class objectfunction data2Object($data) { $class_object = new geekSchool($data); return $class_object;} // Comparator function used for comparator// scores of two object/studentsfunction comparator($object1, $object2) { return $object1->score > $object2->score;} // Generating array of objects$school_data = array_map('data2Object', $gfg_array); // Printing original object array dataprint("Original object array:\n"); print_r($school_data); // Sorting the class objects according // to their scoresusort($school_data, 'comparator'); // Printing sorted object array dataprint("\nSorted object array:\n"); print_r($school_data); ?> Original object array: Array ( [0] => geekSchool Object ( [score] => 100 [name] => Sam [subject] => Data Structures ) [1] => geekSchool Object ( [score] => 50 [name] => Tanya [subject] => Advanced Algorithms ) [2] => geekSchool Object ( [score] => 75 [name] => Jack [subject] => Distributed Computing ) ) Sorted object array: Array ( [0] => geekSchool Object ( [score] => 50 [name] => Tanya [subject] => Advanced Algorithms ) [1] => geekSchool Object ( [score] => 75 [name] => Jack [subject] => Distributed Computing ) [2] => geekSchool Object ( [score] => 100 [name] => Sam [subject] => Data Structures ) ) PHP-array Picked PHP PHP Programs Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to execute PHP code using command line ? PHP in_array() Function How to delete an array element based on key in PHP? How to Insert Form Data into Database using PHP ? How to convert array to string in PHP ? How to execute PHP code using command line ? How to delete an array element based on key in PHP? How to Insert Form Data into Database using PHP ? How to convert array to string in PHP ? How to pop an alert message box using PHP ?
[ { "code": null, "e": 52, "s": 24, "text": "\n04 Jan, 2019" }, { "code": null, "e": 139, "s": 52, "text": "Given an array of objects and the task is to sort the array by object by given fields." }, { "code": null, "e": 562, "s": 139, "text": "Approach:The usort() function is an inbuilt function in PHP which is used to sort the array of elements conditionally with a given comparator function. The usort() function can also be used to sort an array of objects by object field. Call usort() function with first argument as the array of objects and second argument as the comparator function on the basis of which comparison between two array objects has to be made." }, { "code": null, "e": 571, "s": 562, "text": "Example:" }, { "code": "<?php // PHP program to show sorting of // array of objects by object fields // School Data array$gfg_array = array( array( 'score' => '100', 'name' => 'Sam', 'subject' => 'Data Structures' ), array( 'score' => '50', 'name' => 'Tanya', 'subject' => 'Advanced Algorithms' ), array( 'score' => '75', 'name' => 'Jack', 'subject' => 'Distributed Computing' )); // Class for encapsulating school dataclass geekSchool { var $score, $name, $subject; // Constructor for class initialization public function geekSchool($data) { $this->name = $data['name']; $this->score = $data['score']; $this->subject = $data['subject']; }} // Function to convert array data to class objectfunction data2Object($data) { $class_object = new geekSchool($data); return $class_object;} // Comparator function used for comparator// scores of two object/studentsfunction comparator($object1, $object2) { return $object1->score > $object2->score;} // Generating array of objects$school_data = array_map('data2Object', $gfg_array); // Printing original object array dataprint(\"Original object array:\\n\"); print_r($school_data); // Sorting the class objects according // to their scoresusort($school_data, 'comparator'); // Printing sorted object array dataprint(\"\\nSorted object array:\\n\"); print_r($school_data); ?>", "e": 1999, "s": 571, "text": null }, { "code": null, "e": 2951, "s": 1999, "text": "Original object array:\nArray\n(\n [0] => geekSchool Object\n (\n [score] => 100\n [name] => Sam\n [subject] => Data Structures\n )\n\n [1] => geekSchool Object\n (\n [score] => 50\n [name] => Tanya\n [subject] => Advanced Algorithms\n )\n\n [2] => geekSchool Object\n (\n [score] => 75\n [name] => Jack\n [subject] => Distributed Computing\n )\n\n)\n\nSorted object array:\nArray\n(\n [0] => geekSchool Object\n (\n [score] => 50\n [name] => Tanya\n [subject] => Advanced Algorithms\n )\n\n [1] => geekSchool Object\n (\n [score] => 75\n [name] => Jack\n [subject] => Distributed Computing\n )\n\n [2] => geekSchool Object\n (\n [score] => 100\n [name] => Sam\n [subject] => Data Structures\n )\n\n)\n" }, { "code": null, "e": 2961, "s": 2951, "text": "PHP-array" }, { "code": null, "e": 2968, "s": 2961, "text": "Picked" }, { "code": null, "e": 2972, "s": 2968, "text": "PHP" }, { "code": null, "e": 2985, "s": 2972, "text": "PHP Programs" }, { "code": null, "e": 3002, "s": 2985, "text": "Web Technologies" }, { "code": null, "e": 3006, "s": 3002, "text": "PHP" }, { "code": null, "e": 3104, "s": 3006, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3149, "s": 3104, "text": "How to execute PHP code using command line ?" }, { "code": null, "e": 3173, "s": 3149, "text": "PHP in_array() Function" }, { "code": null, "e": 3225, "s": 3173, "text": "How to delete an array element based on key in PHP?" }, { "code": null, "e": 3275, "s": 3225, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 3315, "s": 3275, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 3360, "s": 3315, "text": "How to execute PHP code using command line ?" }, { "code": null, "e": 3412, "s": 3360, "text": "How to delete an array element based on key in PHP?" }, { "code": null, "e": 3462, "s": 3412, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 3502, "s": 3462, "text": "How to convert array to string in PHP ?" } ]
Containerizing Java applications | Creating a Spring Boot App using Dockerfile
22 Oct, 2021 The goal of this article is to containerize a Java application easily, by creating a Spring Boot App using Dockerfile. The steps will be as follows:- Setting up a spring-boot appCreating a dockerfileBuilding project jarBuilding docker image by using dockerfileRunning image Setting up a spring-boot app Creating a dockerfile Building project jar Building docker image by using dockerfile Running image Let’s examine the above steps in detail: Setting up spring-boot app: So first of all, use spring initializer to have a very basic spring-boot greetings project with the help of a web dependency.The project includes a simple rest controller with a simple greeting message.To run this app use command:mvn spring-boot:runCreating A Dockerfile: A dockerfile is a text document which contains commands read by docker and is executed in order to build a container image.FROM: The keyword FROM tells Docker to use a given base image as a build base. In this case Java8 is used as base image with jdk-alpine as tag. A tag can be thought as a version.COPY: copying .jar file to the build image inside /usr/app.WORKDIR: The WORKDIR instruction sets the working directory for any RUN, CMD, ENTRYPOINT, COPY and ADD instructions that follow in the Dockerfile. Here the workdir is switched to /usr/appRUN: The RUN instruction runs any command mentioned.ENTRYPOINT: Tells Docker how to run application. Making array to run spring-boot app as java -jar .jar.Building Project Jar: Now run mvn install to build a .jar file in target directory.Building Docker Image: Execute command docker build -t spring-boot-docker-demo .Run the image build: Execute command docker run spring-boot-docker-demo Setting up spring-boot app: So first of all, use spring initializer to have a very basic spring-boot greetings project with the help of a web dependency.The project includes a simple rest controller with a simple greeting message.To run this app use command:mvn spring-boot:run The project includes a simple rest controller with a simple greeting message. To run this app use command: mvn spring-boot:run Creating A Dockerfile: A dockerfile is a text document which contains commands read by docker and is executed in order to build a container image.FROM: The keyword FROM tells Docker to use a given base image as a build base. In this case Java8 is used as base image with jdk-alpine as tag. A tag can be thought as a version.COPY: copying .jar file to the build image inside /usr/app.WORKDIR: The WORKDIR instruction sets the working directory for any RUN, CMD, ENTRYPOINT, COPY and ADD instructions that follow in the Dockerfile. Here the workdir is switched to /usr/appRUN: The RUN instruction runs any command mentioned.ENTRYPOINT: Tells Docker how to run application. Making array to run spring-boot app as java -jar .jar. FROM: The keyword FROM tells Docker to use a given base image as a build base. In this case Java8 is used as base image with jdk-alpine as tag. A tag can be thought as a version. COPY: copying .jar file to the build image inside /usr/app. WORKDIR: The WORKDIR instruction sets the working directory for any RUN, CMD, ENTRYPOINT, COPY and ADD instructions that follow in the Dockerfile. Here the workdir is switched to /usr/app RUN: The RUN instruction runs any command mentioned. ENTRYPOINT: Tells Docker how to run application. Making array to run spring-boot app as java -jar .jar. Building Project Jar: Now run mvn install to build a .jar file in target directory. Building Docker Image: Execute command docker build -t spring-boot-docker-demo . Run the image build: Execute command docker run spring-boot-docker-demo Github repository: Spring Boot Docker Demo ruhelaa48 saurabh1990aror java-advanced Java-Spring Java Technical Scripter Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Introduction to Java Constructors in Java Exceptions in Java Generics in Java Functional Interfaces in Java Java Programming Examples Strings in Java Differences between JDK, JRE and JVM Abstraction in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Oct, 2021" }, { "code": null, "e": 147, "s": 28, "text": "The goal of this article is to containerize a Java application easily, by creating a Spring Boot App using Dockerfile." }, { "code": null, "e": 178, "s": 147, "text": "The steps will be as follows:-" }, { "code": null, "e": 302, "s": 178, "text": "Setting up a spring-boot appCreating a dockerfileBuilding project jarBuilding docker image by using dockerfileRunning image" }, { "code": null, "e": 331, "s": 302, "text": "Setting up a spring-boot app" }, { "code": null, "e": 353, "s": 331, "text": "Creating a dockerfile" }, { "code": null, "e": 374, "s": 353, "text": "Building project jar" }, { "code": null, "e": 416, "s": 374, "text": "Building docker image by using dockerfile" }, { "code": null, "e": 430, "s": 416, "text": "Running image" }, { "code": null, "e": 471, "s": 430, "text": "Let’s examine the above steps in detail:" }, { "code": null, "e": 1708, "s": 471, "text": "Setting up spring-boot app: So first of all, use spring initializer to have a very basic spring-boot greetings project with the help of a web dependency.The project includes a simple rest controller with a simple greeting message.To run this app use command:mvn spring-boot:runCreating A Dockerfile: A dockerfile is a text document which contains commands read by docker and is executed in order to build a container image.FROM: The keyword FROM tells Docker to use a given base image as a build base. In this case Java8 is used as base image with jdk-alpine as tag. A tag can be thought as a version.COPY: copying .jar file to the build image inside /usr/app.WORKDIR: The WORKDIR instruction sets the working directory for any RUN, CMD, ENTRYPOINT, COPY and ADD instructions that follow in the Dockerfile. Here the workdir is switched to /usr/appRUN: The RUN instruction runs any command mentioned.ENTRYPOINT: Tells Docker how to run application. Making array to run spring-boot app as java -jar .jar.Building Project Jar: Now run mvn install to build a .jar file in target directory.Building Docker Image: Execute command docker build -t spring-boot-docker-demo .Run the image build: Execute command docker run spring-boot-docker-demo" }, { "code": null, "e": 1986, "s": 1708, "text": "Setting up spring-boot app: So first of all, use spring initializer to have a very basic spring-boot greetings project with the help of a web dependency.The project includes a simple rest controller with a simple greeting message.To run this app use command:mvn spring-boot:run" }, { "code": null, "e": 2064, "s": 1986, "text": "The project includes a simple rest controller with a simple greeting message." }, { "code": null, "e": 2093, "s": 2064, "text": "To run this app use command:" }, { "code": null, "e": 2113, "s": 2093, "text": "mvn spring-boot:run" }, { "code": null, "e": 2839, "s": 2113, "text": "Creating A Dockerfile: A dockerfile is a text document which contains commands read by docker and is executed in order to build a container image.FROM: The keyword FROM tells Docker to use a given base image as a build base. In this case Java8 is used as base image with jdk-alpine as tag. A tag can be thought as a version.COPY: copying .jar file to the build image inside /usr/app.WORKDIR: The WORKDIR instruction sets the working directory for any RUN, CMD, ENTRYPOINT, COPY and ADD instructions that follow in the Dockerfile. Here the workdir is switched to /usr/appRUN: The RUN instruction runs any command mentioned.ENTRYPOINT: Tells Docker how to run application. Making array to run spring-boot app as java -jar .jar." }, { "code": null, "e": 3018, "s": 2839, "text": "FROM: The keyword FROM tells Docker to use a given base image as a build base. In this case Java8 is used as base image with jdk-alpine as tag. A tag can be thought as a version." }, { "code": null, "e": 3078, "s": 3018, "text": "COPY: copying .jar file to the build image inside /usr/app." }, { "code": null, "e": 3266, "s": 3078, "text": "WORKDIR: The WORKDIR instruction sets the working directory for any RUN, CMD, ENTRYPOINT, COPY and ADD instructions that follow in the Dockerfile. Here the workdir is switched to /usr/app" }, { "code": null, "e": 3319, "s": 3266, "text": "RUN: The RUN instruction runs any command mentioned." }, { "code": null, "e": 3423, "s": 3319, "text": "ENTRYPOINT: Tells Docker how to run application. Making array to run spring-boot app as java -jar .jar." }, { "code": null, "e": 3507, "s": 3423, "text": "Building Project Jar: Now run mvn install to build a .jar file in target directory." }, { "code": null, "e": 3588, "s": 3507, "text": "Building Docker Image: Execute command docker build -t spring-boot-docker-demo ." }, { "code": null, "e": 3660, "s": 3588, "text": "Run the image build: Execute command docker run spring-boot-docker-demo" }, { "code": null, "e": 3703, "s": 3660, "text": "Github repository: Spring Boot Docker Demo" }, { "code": null, "e": 3713, "s": 3703, "text": "ruhelaa48" }, { "code": null, "e": 3729, "s": 3713, "text": "saurabh1990aror" }, { "code": null, "e": 3743, "s": 3729, "text": "java-advanced" }, { "code": null, "e": 3755, "s": 3743, "text": "Java-Spring" }, { "code": null, "e": 3760, "s": 3755, "text": "Java" }, { "code": null, "e": 3779, "s": 3760, "text": "Technical Scripter" }, { "code": null, "e": 3784, "s": 3779, "text": "Java" }, { "code": null, "e": 3882, "s": 3784, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3897, "s": 3882, "text": "Stream In Java" }, { "code": null, "e": 3918, "s": 3897, "text": "Introduction to Java" }, { "code": null, "e": 3939, "s": 3918, "text": "Constructors in Java" }, { "code": null, "e": 3958, "s": 3939, "text": "Exceptions in Java" }, { "code": null, "e": 3975, "s": 3958, "text": "Generics in Java" }, { "code": null, "e": 4005, "s": 3975, "text": "Functional Interfaces in Java" }, { "code": null, "e": 4031, "s": 4005, "text": "Java Programming Examples" }, { "code": null, "e": 4047, "s": 4031, "text": "Strings in Java" }, { "code": null, "e": 4084, "s": 4047, "text": "Differences between JDK, JRE and JVM" } ]
PySpark – GroupBy and sort DataFrame in descending order
23 May, 2021 In this article, we will discuss how to groupby PySpark DataFrame and then sort it in descending order. groupBy(): The groupBy() function in pyspark is used for identical grouping data on DataFrame while performing an aggregate function on the grouped data. Syntax: DataFrame.groupBy(*cols) Parameters: cols→ Columns by which we need to group data sort(): The sort() function is used to sort one or more columns. By default, it sorts by ascending order. Syntax: sort(*cols, ascending=True) Parameters: cols→ Columns by which sorting is needed to be performed. PySpark DataFrame also provides orderBy() function that sorts one or more columns. By default, it orders by ascending. Syntax: orderBy(*cols, ascending=True) Parameters: cols→ Columns by which sorting is needed to be performed. ascending→ Boolean value to say that sorting is to be done in ascending order Example 1: In this example, we are going to group the dataframe by name and aggregate marks. We will sort the table using the sort() function in which we will access the column using the col() function and desc() function to sort it in descending order. Python3 # import the required modulesfrom pyspark.sql import SparkSessionfrom pyspark.sql.functions import avg, col, desc # Start spark sessionspark = SparkSession.builder.appName("GeeksForGeeks").getOrCreate() # Define sample datasimpleData = [("Pulkit","trial_1",32), ("Ritika","trial_1",42), ("Pulkit","trial_2",45), ("Ritika","trial_2",50), ("Ritika","trial_3",62), ("Pulkit","trial_3",55), ("Ritika","trial_4",75), ("Pulkit","trial_4",70) ] # define the schemaschema = ["Name","Number_of_Trials","Marks"] # create a dataframedf = spark.createDataFrame(data=simpleData, schema = schema) # group by name and aggrigate using# average marks sort the column using# col and desc() functiondf.groupBy("Name") \ .agg(avg("Marks").alias("Avg_Marks")) \ .sort(col("Avg_Marks").desc()) \ .show() # stop spark sessionspark.stop() Output: Example 2: In this example, we are going to group the dataframe by name and aggregate marks. We will sort the table using the sort() function in which we will access the column within the desc() function to sort it in descending order. Python3 # import the required modulesfrom pyspark.sql import SparkSessionfrom pyspark.sql.functions import avg, col, desc # Start spark sessionspark = SparkSession.builder.appName("Student_Info").getOrCreate() # sample datasetsimpleData = [("Pulkit","trial_1",32), ("Ritika","trial_1",42), ("Pulkit","trial_2",45), ("Ritika","trial_2",50), ("Ritika","trial_3",62), ("Pulkit","trial_3",55), ("Ritika","trial_4",75), ("Pulkit","trial_4",70) ] # define the schema to be usedschema = ["Name","Number_of_Trials","Marks"] # create the dataframedf = spark.createDataFrame(data=simpleData, schema = schema) # perform groupby operation on name table# aggrigate marks and give it a new name# sort in descending order by avg_marksdf.groupBy("Name") \ .agg(avg("Marks").alias("Avg_Marks")) \ .sort(desc("Avg_Marks")) \ .show() # stop sparks sessionspark.stop() Output: Example 3: In this example, we are going to group the dataframe by name and aggregate marks. We will sort the table using the orderBy() function in which we will pass ascending parameter as False to sort the data in descending order. Python3 # import required modulesfrom pyspark.sql import SparkSessionfrom pyspark.sql.functions import avg, col, desc # Start spark sessionspark = SparkSession.builder.appName("Student_Info").getOrCreate() # sample datasetsimpleData = [("Pulkit","trial_1",32), ("Ritika","trial_1",42), ("Pulkit","trial_2",45), ("Ritika","trial_2",50), ("Ritika","trial_3",62), ("Pulkit","trial_3",55), ("Ritika","trial_4",75), ("Pulkit","trial_4",70) ] # define the schemaschema = ["Name","Number_of_Trials","Marks"] # create a dataframedf = spark.createDataFrame(data=simpleData, schema = schema) df.groupBy("Name")\ .agg(avg("Marks").alias("Avg_Marks"))\ .orderBy("Avg_Marks", ascending=False)\ .show() # stop sparks sessionspark.stop() Output: Picked Python-Pyspark Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Python | os.path.join() method How to drop one or multiple columns in Pandas Dataframe Introduction To PYTHON How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | datetime.timedelta() function Python | Get unique values from a list
[ { "code": null, "e": 28, "s": 0, "text": "\n23 May, 2021" }, { "code": null, "e": 132, "s": 28, "text": "In this article, we will discuss how to groupby PySpark DataFrame and then sort it in descending order." }, { "code": null, "e": 286, "s": 132, "text": "groupBy(): The groupBy() function in pyspark is used for identical grouping data on DataFrame while performing an aggregate function on the grouped data." }, { "code": null, "e": 319, "s": 286, "text": "Syntax: DataFrame.groupBy(*cols)" }, { "code": null, "e": 331, "s": 319, "text": "Parameters:" }, { "code": null, "e": 376, "s": 331, "text": "cols→ Columns by which we need to group data" }, { "code": null, "e": 482, "s": 376, "text": "sort(): The sort() function is used to sort one or more columns. By default, it sorts by ascending order." }, { "code": null, "e": 518, "s": 482, "text": "Syntax: sort(*cols, ascending=True)" }, { "code": null, "e": 530, "s": 518, "text": "Parameters:" }, { "code": null, "e": 588, "s": 530, "text": "cols→ Columns by which sorting is needed to be performed." }, { "code": null, "e": 707, "s": 588, "text": "PySpark DataFrame also provides orderBy() function that sorts one or more columns. By default, it orders by ascending." }, { "code": null, "e": 746, "s": 707, "text": "Syntax: orderBy(*cols, ascending=True)" }, { "code": null, "e": 758, "s": 746, "text": "Parameters:" }, { "code": null, "e": 816, "s": 758, "text": "cols→ Columns by which sorting is needed to be performed." }, { "code": null, "e": 894, "s": 816, "text": "ascending→ Boolean value to say that sorting is to be done in ascending order" }, { "code": null, "e": 1148, "s": 894, "text": "Example 1: In this example, we are going to group the dataframe by name and aggregate marks. We will sort the table using the sort() function in which we will access the column using the col() function and desc() function to sort it in descending order." }, { "code": null, "e": 1156, "s": 1148, "text": "Python3" }, { "code": "# import the required modulesfrom pyspark.sql import SparkSessionfrom pyspark.sql.functions import avg, col, desc # Start spark sessionspark = SparkSession.builder.appName(\"GeeksForGeeks\").getOrCreate() # Define sample datasimpleData = [(\"Pulkit\",\"trial_1\",32), (\"Ritika\",\"trial_1\",42), (\"Pulkit\",\"trial_2\",45), (\"Ritika\",\"trial_2\",50), (\"Ritika\",\"trial_3\",62), (\"Pulkit\",\"trial_3\",55), (\"Ritika\",\"trial_4\",75), (\"Pulkit\",\"trial_4\",70) ] # define the schemaschema = [\"Name\",\"Number_of_Trials\",\"Marks\"] # create a dataframedf = spark.createDataFrame(data=simpleData, schema = schema) # group by name and aggrigate using# average marks sort the column using# col and desc() functiondf.groupBy(\"Name\") \\ .agg(avg(\"Marks\").alias(\"Avg_Marks\")) \\ .sort(col(\"Avg_Marks\").desc()) \\ .show() # stop spark sessionspark.stop()", "e": 2002, "s": 1156, "text": null }, { "code": null, "e": 2010, "s": 2002, "text": "Output:" }, { "code": null, "e": 2246, "s": 2010, "text": "Example 2: In this example, we are going to group the dataframe by name and aggregate marks. We will sort the table using the sort() function in which we will access the column within the desc() function to sort it in descending order." }, { "code": null, "e": 2254, "s": 2246, "text": "Python3" }, { "code": "# import the required modulesfrom pyspark.sql import SparkSessionfrom pyspark.sql.functions import avg, col, desc # Start spark sessionspark = SparkSession.builder.appName(\"Student_Info\").getOrCreate() # sample datasetsimpleData = [(\"Pulkit\",\"trial_1\",32), (\"Ritika\",\"trial_1\",42), (\"Pulkit\",\"trial_2\",45), (\"Ritika\",\"trial_2\",50), (\"Ritika\",\"trial_3\",62), (\"Pulkit\",\"trial_3\",55), (\"Ritika\",\"trial_4\",75), (\"Pulkit\",\"trial_4\",70) ] # define the schema to be usedschema = [\"Name\",\"Number_of_Trials\",\"Marks\"] # create the dataframedf = spark.createDataFrame(data=simpleData, schema = schema) # perform groupby operation on name table# aggrigate marks and give it a new name# sort in descending order by avg_marksdf.groupBy(\"Name\") \\ .agg(avg(\"Marks\").alias(\"Avg_Marks\")) \\ .sort(desc(\"Avg_Marks\")) \\ .show() # stop sparks sessionspark.stop()", "e": 3126, "s": 2254, "text": null }, { "code": null, "e": 3134, "s": 3126, "text": "Output:" }, { "code": null, "e": 3368, "s": 3134, "text": "Example 3: In this example, we are going to group the dataframe by name and aggregate marks. We will sort the table using the orderBy() function in which we will pass ascending parameter as False to sort the data in descending order." }, { "code": null, "e": 3376, "s": 3368, "text": "Python3" }, { "code": "# import required modulesfrom pyspark.sql import SparkSessionfrom pyspark.sql.functions import avg, col, desc # Start spark sessionspark = SparkSession.builder.appName(\"Student_Info\").getOrCreate() # sample datasetsimpleData = [(\"Pulkit\",\"trial_1\",32), (\"Ritika\",\"trial_1\",42), (\"Pulkit\",\"trial_2\",45), (\"Ritika\",\"trial_2\",50), (\"Ritika\",\"trial_3\",62), (\"Pulkit\",\"trial_3\",55), (\"Ritika\",\"trial_4\",75), (\"Pulkit\",\"trial_4\",70) ] # define the schemaschema = [\"Name\",\"Number_of_Trials\",\"Marks\"] # create a dataframedf = spark.createDataFrame(data=simpleData, schema = schema) df.groupBy(\"Name\")\\ .agg(avg(\"Marks\").alias(\"Avg_Marks\"))\\ .orderBy(\"Avg_Marks\", ascending=False)\\ .show() # stop sparks sessionspark.stop()", "e": 4128, "s": 3376, "text": null }, { "code": null, "e": 4136, "s": 4128, "text": "Output:" }, { "code": null, "e": 4143, "s": 4136, "text": "Picked" }, { "code": null, "e": 4158, "s": 4143, "text": "Python-Pyspark" }, { "code": null, "e": 4165, "s": 4158, "text": "Python" }, { "code": null, "e": 4263, "s": 4165, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4295, "s": 4263, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 4322, "s": 4295, "text": "Python Classes and Objects" }, { "code": null, "e": 4343, "s": 4322, "text": "Python OOPs Concepts" }, { "code": null, "e": 4374, "s": 4343, "text": "Python | os.path.join() method" }, { "code": null, "e": 4430, "s": 4374, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 4453, "s": 4430, "text": "Introduction To PYTHON" }, { "code": null, "e": 4495, "s": 4453, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 4537, "s": 4495, "text": "Check if element exists in list in Python" }, { "code": null, "e": 4576, "s": 4537, "text": "Python | datetime.timedelta() function" } ]
Angular 2 - Custom Pipes
Angular 2 also has the facility to create custom pipes. The general way to define a custom pipe is as follows. import { Pipe, PipeTransform } from '@angular/core'; @Pipe({name: 'Pipename'}) export class Pipeclass implements PipeTransform { transform(parameters): returntype { } } Where, 'Pipename' − This is the name of the pipe. 'Pipename' − This is the name of the pipe. Pipeclass − This is name of the class assigned to the custom pipe. Pipeclass − This is name of the class assigned to the custom pipe. Transform − This is the function to work with the pipe. Transform − This is the function to work with the pipe. Parameters − This are the parameters which are passed to the pipe. Parameters − This are the parameters which are passed to the pipe. Returntype − This is the return type of the pipe. Returntype − This is the return type of the pipe. Let’s create a custom pipe that multiplies 2 numbers. We will then use that pipe in our component class. Step 1 − First, create a file called multiplier.pipe.ts. Step 2 − Place the following code in the above created file. import { Pipe, PipeTransform } from '@angular/core'; @Pipe ({ name: 'Multiplier' }) export class MultiplierPipe implements PipeTransform { transform(value: number, multiply: string): number { let mul = parseFloat(multiply); return mul * value } } Following points need to be noted about the above code. We are first importing the Pipe and PipeTransform modules. We are first importing the Pipe and PipeTransform modules. Then, we are creating a Pipe with the name 'Multiplier'. Then, we are creating a Pipe with the name 'Multiplier'. Creating a class called MultiplierPipe that implements the PipeTransform module. Creating a class called MultiplierPipe that implements the PipeTransform module. The transform function will then take in the value and multiple parameter and output the multiplication of both numbers. The transform function will then take in the value and multiple parameter and output the multiplication of both numbers. Step 3 − In the app.component.ts file, place the following code. import { Component } from '@angular/core'; @Component ({ selector: 'my-app', template: '<p>Multiplier: {{2 | Multiplier: 10}}</p>' }) export class AppComponent { } Note − In our template, we use our new custom pipe. Step 4 − Ensure the following code is placed in the app.module.ts file. import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppComponent } from './app.component'; import { MultiplierPipe } from './multiplier.pipe' @NgModule ({ imports: [BrowserModule], declarations: [AppComponent, MultiplierPipe], bootstrap: [AppComponent] }) export class AppModule {} Following things need to be noted about the above code. We need to ensure to include our MultiplierPipe module. We need to ensure to include our MultiplierPipe module. We also need to ensure it is included in the declarations section. We also need to ensure it is included in the declarations section. Once you save all the code changes and refresh the browser, you will get the following output.
[ { "code": null, "e": 2542, "s": 2431, "text": "Angular 2 also has the facility to create custom pipes. The general way to define a custom pipe is as follows." }, { "code": null, "e": 2721, "s": 2542, "text": "import { Pipe, PipeTransform } from '@angular/core'; \n@Pipe({name: 'Pipename'}) \n\nexport class Pipeclass implements PipeTransform { \n transform(parameters): returntype { } \n} " }, { "code": null, "e": 2728, "s": 2721, "text": "Where," }, { "code": null, "e": 2771, "s": 2728, "text": "'Pipename' − This is the name of the pipe." }, { "code": null, "e": 2814, "s": 2771, "text": "'Pipename' − This is the name of the pipe." }, { "code": null, "e": 2881, "s": 2814, "text": "Pipeclass − This is name of the class assigned to the custom pipe." }, { "code": null, "e": 2948, "s": 2881, "text": "Pipeclass − This is name of the class assigned to the custom pipe." }, { "code": null, "e": 3004, "s": 2948, "text": "Transform − This is the function to work with the pipe." }, { "code": null, "e": 3060, "s": 3004, "text": "Transform − This is the function to work with the pipe." }, { "code": null, "e": 3127, "s": 3060, "text": "Parameters − This are the parameters which are passed to the pipe." }, { "code": null, "e": 3194, "s": 3127, "text": "Parameters − This are the parameters which are passed to the pipe." }, { "code": null, "e": 3244, "s": 3194, "text": "Returntype − This is the return type of the pipe." }, { "code": null, "e": 3294, "s": 3244, "text": "Returntype − This is the return type of the pipe." }, { "code": null, "e": 3399, "s": 3294, "text": "Let’s create a custom pipe that multiplies 2 numbers. We will then use that pipe in our component class." }, { "code": null, "e": 3456, "s": 3399, "text": "Step 1 − First, create a file called multiplier.pipe.ts." }, { "code": null, "e": 3517, "s": 3456, "text": "Step 2 − Place the following code in the above created file." }, { "code": null, "e": 3807, "s": 3517, "text": "import { \n Pipe, \n PipeTransform \n} from '@angular/core'; \n\n@Pipe ({ \n name: 'Multiplier' \n}) \n\nexport class MultiplierPipe implements PipeTransform { \n transform(value: number, multiply: string): number { \n let mul = parseFloat(multiply); \n return mul * value \n } \n} " }, { "code": null, "e": 3863, "s": 3807, "text": "Following points need to be noted about the above code." }, { "code": null, "e": 3922, "s": 3863, "text": "We are first importing the Pipe and PipeTransform modules." }, { "code": null, "e": 3981, "s": 3922, "text": "We are first importing the Pipe and PipeTransform modules." }, { "code": null, "e": 4038, "s": 3981, "text": "Then, we are creating a Pipe with the name 'Multiplier'." }, { "code": null, "e": 4095, "s": 4038, "text": "Then, we are creating a Pipe with the name 'Multiplier'." }, { "code": null, "e": 4177, "s": 4095, "text": "Creating a class called MultiplierPipe that implements the PipeTransform module. " }, { "code": null, "e": 4259, "s": 4177, "text": "Creating a class called MultiplierPipe that implements the PipeTransform module. " }, { "code": null, "e": 4380, "s": 4259, "text": "The transform function will then take in the value and multiple parameter and output the multiplication of both numbers." }, { "code": null, "e": 4501, "s": 4380, "text": "The transform function will then take in the value and multiple parameter and output the multiplication of both numbers." }, { "code": null, "e": 4566, "s": 4501, "text": "Step 3 − In the app.component.ts file, place the following code." }, { "code": null, "e": 4750, "s": 4566, "text": "import { \n Component \n} from '@angular/core'; \n\n@Component ({ \n selector: 'my-app', \n template: '<p>Multiplier: {{2 | Multiplier: 10}}</p>' \n}) \nexport class AppComponent { } " }, { "code": null, "e": 4802, "s": 4750, "text": "Note − In our template, we use our new custom pipe." }, { "code": null, "e": 4874, "s": 4802, "text": "Step 4 − Ensure the following code is placed in the app.module.ts file." }, { "code": null, "e": 5240, "s": 4874, "text": "import {\n NgModule\n} from '@angular/core';\n\nimport {\n BrowserModule\n} from '@angular/platform-browser';\n\nimport {\n AppComponent\n} from './app.component';\n\nimport {\n MultiplierPipe\n} from './multiplier.pipe'\n\n@NgModule ({\n imports: [BrowserModule],\n declarations: [AppComponent, MultiplierPipe],\n bootstrap: [AppComponent]\n})\n\nexport class AppModule {}" }, { "code": null, "e": 5296, "s": 5240, "text": "Following things need to be noted about the above code." }, { "code": null, "e": 5352, "s": 5296, "text": "We need to ensure to include our MultiplierPipe module." }, { "code": null, "e": 5408, "s": 5352, "text": "We need to ensure to include our MultiplierPipe module." }, { "code": null, "e": 5475, "s": 5408, "text": "We also need to ensure it is included in the declarations section." }, { "code": null, "e": 5542, "s": 5475, "text": "We also need to ensure it is included in the declarations section." } ]
How to Upload Image into Database and Display it using PHP ?
03 Jun, 2022 Uploading the image/videos into the database and displaying it using PHP is the way of uploading the image into the database and fetching it from the database. Using the PHP code, the user uploads the image or videos they are safely getting entry into the database and the images should be saved into a particular location by fetching these images from the database.If any of the websites contain the functionality to upload images/videos with some detail, then by using this code we will upload the image into your database and whether you would like to ascertain what the person has got to be uploaded. And by this code the image which is uploaded that where save in your system where you are given the location. Approach: Make sure you have XAMPP or WAMP server installed on your machine. In this tutorial, we will be using the WAMP server. 1. Create Database: First, we will create a database named ‘geeksforgeeks‘. You can use your existing database or create a new one. create database “geeksforgeeks” 2. Create Table: Create a table named ‘image‘. The table contains two fields: id – int(11) filename – varchar(100) The id should be in Auto incremented(AI). Your table structure should look like this: table structure of “image” Or you can create a table by copying and pasting the following code into the SQL panel of your PHPMyAdmin. CREATE TABLE IF NOT EXISTS `image` ( `id` int(11) NOT NULL AUTO_INCREMENT, `filename` varchar(100) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1; To do this from SQL panel refer to the following screenshot. create a table ‘image” from the SQL panel We will be using Bootstrap here to use Bootstrap’s form control. Below is the code to include the Bootstrap CDN link in the head section of the HTML code. <link rel=”stylesheet” href=”https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css”> Creating folder and files: We will now create a folder named “image“. The files uploaded by the client on the server will be stored in this folder. Create index.php and style.css. Keep your main project folder (for example here.. GeeksForGeeks) in the “C://wamp64/www/“, if you are using WAMP or “C://xampp/htdocs/” folder if you are using the XAMPP server respectively. The folder structure should look like this: folder structure Program: Now, we will create an HTML form for uploading image files (you can upload any type of file like .pdf or .mp4) and will display the uploaded image. HTML code: HTML <!DOCTYPE html><html> <head> <title>Image Upload</title> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"> <link rel="stylesheet" type="text/css" href="style.css" /></head> <body> <div id="content"> <form method="POST" action="" enctype="multipart/form-data"> <div class="form-group"> <input class="form-control" type="file" name="uploadfile" value="" /> </div> <div class="form-group"> <button class="btn btn-primary" type="submit" name="upload">UPLOAD</button> </div> </form> </div> <div id="display-image"> <?php $query = " select * from image "; $result = mysqli_query($db, $query); while ($data = mysqli_fetch_assoc($result)) { ?> <img src="./image/<?php echo $data['filename']; ?>"> <?php } ?> </div></body> </html> Explanation of PHP code: We are first selecting the records from the table in the $query variable. Then the $result will execute the query. While loop is used to fetch all the records in the $data to fetch the image from the database. And finally, the fetched images are displayed with the help of the <img> tag. In the <img> tag we are passing the location of the file uploaded on the server and the name of the image file in our database. CSS code: The style.css is the file that styles the form into a new design and the code is given below. CSS *{ margin: 0; padding: 0; box-sizing: border-box;} #content{ width: 50%; justify-content: center; align-items: center; margin: 20px auto; border: 1px solid #cbcbcb;}form{ width: 50%; margin: 20px auto;} #display-image{ width: 100%; justify-content: center; padding: 5px; margin: 15px;}img{ margin: 5px; width: 350px; height: 250px;} You can copy the above code and mention it into the main code directly or create a link as same in the HTML code and attach it with the main code which is given below. As mentioned that if you link the stylesheet file you should create another file in .css format and save it in the place where the main file is to be saved. The form created with the help of the POST method and the enctype=”multipart/form-data” is the action which encodes the files and allows you to send them through POST.Now we are working on the PHP code for the transfer of the image from any folder of the system in a particular folder which you are mentioning and storing it into the database as a directory. PHP code: The PHP code is for the uploading images, the file name is saved with the index.php, you can also save it with another name as you prefer. PHP <?phperror_reporting(0); $msg = ""; // If upload button is clicked ...if (isset($_POST['upload'])) { $filename = $_FILES["uploadfile"]["name"]; $tempname = $_FILES["uploadfile"]["tmp_name"]; $folder = "./image/" . $filename; $db = mysqli_connect("localhost", "root", "", "geeksforgeeks"); // Get all the submitted data from the form $sql = "INSERT INTO image (filename) VALUES ('$filename')"; // Execute query mysqli_query($db, $sql); // Now let's move the uploaded image into the folder: image if (move_uploaded_file($tempname, $folder)) { echo "<h3> Image uploaded successfully!</h3>"; } else { echo "<h3> Failed to upload image!</h3>"; }}?> Explanation: The following are the explanation to create the PHP code which is the following: The error_reporting(0) is for getting 0 error while PHP code is running. $_files work behind the scene. It is being used to upload files via the HTTP POST method and hold the attributes of files. $filename is a name used to uniquely identify a computer file stored in a file system. $tempname is used to copy the original name of the file which is uploaded to the database as the temp name where the image is stored after upload. $folder defines the path of the uploaded image into the database to the folder where you want to be stored. The “./image/” is the folder name where the image is to be saved after the upload. And the $filename is used for fetching or uploading the file. $db, the basic line for any of the PHP code for connecting to the database. $sql is used for inserting the image into the database of the table name image to the variable filename. mysqli_query is the function to execute a query of $db and $sql. Now, let’s move the uploaded image into the folder named the image. The image named folder is saved into the WAMP or XAMPP server folder which is in C drive into the www folder. Combination of the above codes: The final code of upload the image into MySQL using PHP is as followed. Program: File name: index.php This file combines the HTML and PHP code. PHP <?phperror_reporting(0); $msg = ""; // If upload button is clicked ...if (isset($_POST['upload'])) { $filename = $_FILES["uploadfile"]["name"]; $tempname = $_FILES["uploadfile"]["tmp_name"]; $folder = "./image/" . $filename; $db = mysqli_connect("localhost", "root", "", "geeksforgeeks"); // Get all the submitted data from the form $sql = "INSERT INTO image (filename) VALUES ('$filename')"; // Execute query mysqli_query($db, $sql); // Now let's move the uploaded image into the folder: image if (move_uploaded_file($tempname, $folder)) { echo "<h3> Image uploaded successfully!</h3>"; } else { echo "<h3> Failed to upload image!</h3>"; }}?> <!DOCTYPE html><html> <head> <title>Image Upload</title> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"> <link rel="stylesheet" type="text/css" href="style.css" /></head> <body> <div id="content"> <form method="POST" action="" enctype="multipart/form-data"> <div class="form-group"> <input class="form-control" type="file" name="uploadfile" value="" /> </div> <div class="form-group"> <button class="btn btn-primary" type="submit" name="upload">UPLOAD</button> </div> </form> </div> <div id="display-image"> <?php $query = " select * from image "; $result = mysqli_query($db, $query); while ($data = mysqli_fetch_assoc($result)) { ?> <img src="./image/<?php echo $data['filename']; ?>"> <?php } ?> </div></body> </html> Output: Finally, you should be able to upload the images to the database and display it by fetching them from the database. output Conclusion: The uploaded image into the database with the PHP code is simple and used for various purposes. The code helps to upload the image and then uploaded the image into the database and can be shown in another folder.One thing you should note is that when you are running this program there should be a possibility that the image is not uploaded more than 2 MB because the PHP program has set the default value of uploading an image of 2 MB and posting the image of 8 MB. For exceeding the size of uploading the image you should follow the following steps: First, open the C drive, then open the folder WAMP or XAMPP server. Then open the bin folder. Open the PHP version folder (PHP 5.6.31 folder) (KINDLY NOTE THAT IF YOU HAVE ANOTHER VERSION OF PHP YOU SHOULD OPEN THAT ALSO) Then search php.ini. Open it and then search the two variables and change with them. The variables are: upload_max_size = 100M post_max_filesize = 100M Save with this change and then open C:\wamp64\bin\apache\apache2.4.27\bin and search for the php.ini file. Change the same thing which is above mention. Restart the WAMP or XAMPP server and then run the code. PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples. Akanksha_Rai srivastavaharshit848 hardikkoriintern sanjyotpanure CSS-Misc HTML-Misc PHP-Misc CSS HTML PHP PHP Programs Web Technologies Web technologies Questions HTML PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Types of CSS (Cascading Style Sheet) How to set space between the flexbox ? How to position a div at the bottom of its container using CSS? Design a Tribute Page using HTML & CSS How to get values from html input array using JavaScript ? Types of CSS (Cascading Style Sheet) REST API (Introduction) How to set input type date in dd-mm-yyyy format using HTML ? How to set the default value for an HTML <select> element ? Design a Tribute Page using HTML & CSS
[ { "code": null, "e": 52, "s": 24, "text": "\n03 Jun, 2022" }, { "code": null, "e": 767, "s": 52, "text": "Uploading the image/videos into the database and displaying it using PHP is the way of uploading the image into the database and fetching it from the database. Using the PHP code, the user uploads the image or videos they are safely getting entry into the database and the images should be saved into a particular location by fetching these images from the database.If any of the websites contain the functionality to upload images/videos with some detail, then by using this code we will upload the image into your database and whether you would like to ascertain what the person has got to be uploaded. And by this code the image which is uploaded that where save in your system where you are given the location." }, { "code": null, "e": 896, "s": 767, "text": "Approach: Make sure you have XAMPP or WAMP server installed on your machine. In this tutorial, we will be using the WAMP server." }, { "code": null, "e": 1028, "s": 896, "text": "1. Create Database: First, we will create a database named ‘geeksforgeeks‘. You can use your existing database or create a new one." }, { "code": null, "e": 1060, "s": 1028, "text": "create database “geeksforgeeks”" }, { "code": null, "e": 1139, "s": 1060, "text": "2. Create Table: Create a table named ‘image‘. The table contains two fields: " }, { "code": null, "e": 1152, "s": 1139, "text": "id – int(11)" }, { "code": null, "e": 1176, "s": 1152, "text": "filename – varchar(100)" }, { "code": null, "e": 1262, "s": 1176, "text": "The id should be in Auto incremented(AI). Your table structure should look like this:" }, { "code": null, "e": 1289, "s": 1262, "text": "table structure of “image”" }, { "code": null, "e": 1396, "s": 1289, "text": "Or you can create a table by copying and pasting the following code into the SQL panel of your PHPMyAdmin." }, { "code": null, "e": 1570, "s": 1396, "text": "CREATE TABLE IF NOT EXISTS `image` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `filename` varchar(100) NOT NULL,\n PRIMARY KEY (`id`)\n) ENGINE=MyISAM DEFAULT CHARSET=latin1;" }, { "code": null, "e": 1631, "s": 1570, "text": "To do this from SQL panel refer to the following screenshot." }, { "code": null, "e": 1673, "s": 1631, "text": "create a table ‘image” from the SQL panel" }, { "code": null, "e": 1828, "s": 1673, "text": "We will be using Bootstrap here to use Bootstrap’s form control. Below is the code to include the Bootstrap CDN link in the head section of the HTML code." }, { "code": null, "e": 1931, "s": 1828, "text": "<link rel=”stylesheet” href=”https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css”>" }, { "code": null, "e": 1958, "s": 1931, "text": "Creating folder and files:" }, { "code": null, "e": 2346, "s": 1958, "text": "We will now create a folder named “image“. The files uploaded by the client on the server will be stored in this folder. Create index.php and style.css. Keep your main project folder (for example here.. GeeksForGeeks) in the “C://wamp64/www/“, if you are using WAMP or “C://xampp/htdocs/” folder if you are using the XAMPP server respectively. The folder structure should look like this:" }, { "code": null, "e": 2363, "s": 2346, "text": "folder structure" }, { "code": null, "e": 2520, "s": 2363, "text": "Program: Now, we will create an HTML form for uploading image files (you can upload any type of file like .pdf or .mp4) and will display the uploaded image." }, { "code": null, "e": 2532, "s": 2520, "text": "HTML code: " }, { "code": null, "e": 2537, "s": 2532, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>Image Upload</title> <link rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css\"> <link rel=\"stylesheet\" type=\"text/css\" href=\"style.css\" /></head> <body> <div id=\"content\"> <form method=\"POST\" action=\"\" enctype=\"multipart/form-data\"> <div class=\"form-group\"> <input class=\"form-control\" type=\"file\" name=\"uploadfile\" value=\"\" /> </div> <div class=\"form-group\"> <button class=\"btn btn-primary\" type=\"submit\" name=\"upload\">UPLOAD</button> </div> </form> </div> <div id=\"display-image\"> <?php $query = \" select * from image \"; $result = mysqli_query($db, $query); while ($data = mysqli_fetch_assoc($result)) { ?> <img src=\"./image/<?php echo $data['filename']; ?>\"> <?php } ?> </div></body> </html>", "e": 3474, "s": 2537, "text": null }, { "code": null, "e": 3500, "s": 3474, "text": "Explanation of PHP code: " }, { "code": null, "e": 3574, "s": 3500, "text": "We are first selecting the records from the table in the $query variable." }, { "code": null, "e": 3615, "s": 3574, "text": "Then the $result will execute the query." }, { "code": null, "e": 3710, "s": 3615, "text": "While loop is used to fetch all the records in the $data to fetch the image from the database." }, { "code": null, "e": 3916, "s": 3710, "text": "And finally, the fetched images are displayed with the help of the <img> tag. In the <img> tag we are passing the location of the file uploaded on the server and the name of the image file in our database." }, { "code": null, "e": 4022, "s": 3916, "text": "CSS code: The style.css is the file that styles the form into a new design and the code is given below. " }, { "code": null, "e": 4026, "s": 4022, "text": "CSS" }, { "code": "*{ margin: 0; padding: 0; box-sizing: border-box;} #content{ width: 50%; justify-content: center; align-items: center; margin: 20px auto; border: 1px solid #cbcbcb;}form{ width: 50%; margin: 20px auto;} #display-image{ width: 100%; justify-content: center; padding: 5px; margin: 15px;}img{ margin: 5px; width: 350px; height: 250px;}", "e": 4414, "s": 4026, "text": null }, { "code": null, "e": 5099, "s": 4414, "text": "You can copy the above code and mention it into the main code directly or create a link as same in the HTML code and attach it with the main code which is given below. As mentioned that if you link the stylesheet file you should create another file in .css format and save it in the place where the main file is to be saved. The form created with the help of the POST method and the enctype=”multipart/form-data” is the action which encodes the files and allows you to send them through POST.Now we are working on the PHP code for the transfer of the image from any folder of the system in a particular folder which you are mentioning and storing it into the database as a directory. " }, { "code": null, "e": 5250, "s": 5099, "text": "PHP code: The PHP code is for the uploading images, the file name is saved with the index.php, you can also save it with another name as you prefer. " }, { "code": null, "e": 5254, "s": 5250, "text": "PHP" }, { "code": "<?phperror_reporting(0); $msg = \"\"; // If upload button is clicked ...if (isset($_POST['upload'])) { $filename = $_FILES[\"uploadfile\"][\"name\"]; $tempname = $_FILES[\"uploadfile\"][\"tmp_name\"]; $folder = \"./image/\" . $filename; $db = mysqli_connect(\"localhost\", \"root\", \"\", \"geeksforgeeks\"); // Get all the submitted data from the form $sql = \"INSERT INTO image (filename) VALUES ('$filename')\"; // Execute query mysqli_query($db, $sql); // Now let's move the uploaded image into the folder: image if (move_uploaded_file($tempname, $folder)) { echo \"<h3> Image uploaded successfully!</h3>\"; } else { echo \"<h3> Failed to upload image!</h3>\"; }}?>", "e": 5955, "s": 5254, "text": null }, { "code": null, "e": 6050, "s": 5955, "text": "Explanation: The following are the explanation to create the PHP code which is the following: " }, { "code": null, "e": 6123, "s": 6050, "text": "The error_reporting(0) is for getting 0 error while PHP code is running." }, { "code": null, "e": 6246, "s": 6123, "text": "$_files work behind the scene. It is being used to upload files via the HTTP POST method and hold the attributes of files." }, { "code": null, "e": 6333, "s": 6246, "text": "$filename is a name used to uniquely identify a computer file stored in a file system." }, { "code": null, "e": 6480, "s": 6333, "text": "$tempname is used to copy the original name of the file which is uploaded to the database as the temp name where the image is stored after upload." }, { "code": null, "e": 6733, "s": 6480, "text": "$folder defines the path of the uploaded image into the database to the folder where you want to be stored. The “./image/” is the folder name where the image is to be saved after the upload. And the $filename is used for fetching or uploading the file." }, { "code": null, "e": 6809, "s": 6733, "text": "$db, the basic line for any of the PHP code for connecting to the database." }, { "code": null, "e": 6914, "s": 6809, "text": "$sql is used for inserting the image into the database of the table name image to the variable filename." }, { "code": null, "e": 6979, "s": 6914, "text": "mysqli_query is the function to execute a query of $db and $sql." }, { "code": null, "e": 7157, "s": 6979, "text": "Now, let’s move the uploaded image into the folder named the image. The image named folder is saved into the WAMP or XAMPP server folder which is in C drive into the www folder." }, { "code": null, "e": 7263, "s": 7157, "text": "Combination of the above codes: The final code of upload the image into MySQL using PHP is as followed. " }, { "code": null, "e": 7337, "s": 7263, "text": "Program: File name: index.php This file combines the HTML and PHP code. " }, { "code": null, "e": 7341, "s": 7337, "text": "PHP" }, { "code": "<?phperror_reporting(0); $msg = \"\"; // If upload button is clicked ...if (isset($_POST['upload'])) { $filename = $_FILES[\"uploadfile\"][\"name\"]; $tempname = $_FILES[\"uploadfile\"][\"tmp_name\"]; $folder = \"./image/\" . $filename; $db = mysqli_connect(\"localhost\", \"root\", \"\", \"geeksforgeeks\"); // Get all the submitted data from the form $sql = \"INSERT INTO image (filename) VALUES ('$filename')\"; // Execute query mysqli_query($db, $sql); // Now let's move the uploaded image into the folder: image if (move_uploaded_file($tempname, $folder)) { echo \"<h3> Image uploaded successfully!</h3>\"; } else { echo \"<h3> Failed to upload image!</h3>\"; }}?> <!DOCTYPE html><html> <head> <title>Image Upload</title> <link rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css\"> <link rel=\"stylesheet\" type=\"text/css\" href=\"style.css\" /></head> <body> <div id=\"content\"> <form method=\"POST\" action=\"\" enctype=\"multipart/form-data\"> <div class=\"form-group\"> <input class=\"form-control\" type=\"file\" name=\"uploadfile\" value=\"\" /> </div> <div class=\"form-group\"> <button class=\"btn btn-primary\" type=\"submit\" name=\"upload\">UPLOAD</button> </div> </form> </div> <div id=\"display-image\"> <?php $query = \" select * from image \"; $result = mysqli_query($db, $query); while ($data = mysqli_fetch_assoc($result)) { ?> <img src=\"./image/<?php echo $data['filename']; ?>\"> <?php } ?> </div></body> </html>", "e": 8995, "s": 7341, "text": null }, { "code": null, "e": 9120, "s": 8995, "text": "Output: Finally, you should be able to upload the images to the database and display it by fetching them from the database. " }, { "code": null, "e": 9127, "s": 9120, "text": "output" }, { "code": null, "e": 9692, "s": 9127, "text": "Conclusion: The uploaded image into the database with the PHP code is simple and used for various purposes. The code helps to upload the image and then uploaded the image into the database and can be shown in another folder.One thing you should note is that when you are running this program there should be a possibility that the image is not uploaded more than 2 MB because the PHP program has set the default value of uploading an image of 2 MB and posting the image of 8 MB. For exceeding the size of uploading the image you should follow the following steps: " }, { "code": null, "e": 9760, "s": 9692, "text": "First, open the C drive, then open the folder WAMP or XAMPP server." }, { "code": null, "e": 9786, "s": 9760, "text": "Then open the bin folder." }, { "code": null, "e": 9914, "s": 9786, "text": "Open the PHP version folder (PHP 5.6.31 folder) (KINDLY NOTE THAT IF YOU HAVE ANOTHER VERSION OF PHP YOU SHOULD OPEN THAT ALSO)" }, { "code": null, "e": 10020, "s": 9914, "text": "Then search php.ini. Open it and then search the two variables and change with them. The variables are: " }, { "code": null, "e": 10068, "s": 10020, "text": "upload_max_size = 100M\npost_max_filesize = 100M" }, { "code": null, "e": 10105, "s": 10068, "text": "Save with this change and then open " }, { "code": null, "e": 10143, "s": 10105, "text": "C:\\wamp64\\bin\\apache\\apache2.4.27\\bin" }, { "code": null, "e": 10222, "s": 10143, "text": "and search for the php.ini file. Change the same thing which is above mention." }, { "code": null, "e": 10278, "s": 10222, "text": "Restart the WAMP or XAMPP server and then run the code." }, { "code": null, "e": 10447, "s": 10278, "text": "PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples." }, { "code": null, "e": 10460, "s": 10447, "text": "Akanksha_Rai" }, { "code": null, "e": 10481, "s": 10460, "text": "srivastavaharshit848" }, { "code": null, "e": 10498, "s": 10481, "text": "hardikkoriintern" }, { "code": null, "e": 10512, "s": 10498, "text": "sanjyotpanure" }, { "code": null, "e": 10521, "s": 10512, "text": "CSS-Misc" }, { "code": null, "e": 10531, "s": 10521, "text": "HTML-Misc" }, { "code": null, "e": 10540, "s": 10531, "text": "PHP-Misc" }, { "code": null, "e": 10544, "s": 10540, "text": "CSS" }, { "code": null, "e": 10549, "s": 10544, "text": "HTML" }, { "code": null, "e": 10553, "s": 10549, "text": "PHP" }, { "code": null, "e": 10566, "s": 10553, "text": "PHP Programs" }, { "code": null, "e": 10583, "s": 10566, "text": "Web Technologies" }, { "code": null, "e": 10610, "s": 10583, "text": "Web technologies Questions" }, { "code": null, "e": 10615, "s": 10610, "text": "HTML" }, { "code": null, "e": 10619, "s": 10615, "text": "PHP" }, { "code": null, "e": 10717, "s": 10619, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 10754, "s": 10717, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 10793, "s": 10754, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 10857, "s": 10793, "text": "How to position a div at the bottom of its container using CSS?" }, { "code": null, "e": 10896, "s": 10857, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 10955, "s": 10896, "text": "How to get values from html input array using JavaScript ?" }, { "code": null, "e": 10992, "s": 10955, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 11016, "s": 10992, "text": "REST API (Introduction)" }, { "code": null, "e": 11077, "s": 11016, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 11137, "s": 11077, "text": "How to set the default value for an HTML <select> element ?" } ]
NumPy - Sort, Search & Counting Functions
A variety of sorting related functions are available in NumPy. These sorting functions implement different sorting algorithms, each of them characterized by the speed of execution, worst case performance, the workspace required and the stability of algorithms. Following table shows the comparison of three sorting algorithms. The sort() function returns a sorted copy of the input array. It has the following parameters − numpy.sort(a, axis, kind, order) Where, a Array to be sorted axis The axis along which the array is to be sorted. If none, the array is flattened, sorting on the last axis kind Default is quicksort order If the array contains fields, the order of fields to be sorted import numpy as np a = np.array([[3,7],[9,1]]) print 'Our array is:' print a print '\n' print 'Applying sort() function:' print np.sort(a) print '\n' print 'Sort along axis 0:' print np.sort(a, axis = 0) print '\n' # Order parameter in sort function dt = np.dtype([('name', 'S10'),('age', int)]) a = np.array([("raju",21),("anil",25),("ravi", 17), ("amar",27)], dtype = dt) print 'Our array is:' print a print '\n' print 'Order by name:' print np.sort(a, order = 'name') It will produce the following output − Our array is: [[3 7] [9 1]] Applying sort() function: [[3 7] [1 9]] Sort along axis 0: [[3 1] [9 7]] Our array is: [('raju', 21) ('anil', 25) ('ravi', 17) ('amar', 27)] Order by name: [('amar', 27) ('anil', 25) ('raju', 21) ('ravi', 17)] The numpy.argsort() function performs an indirect sort on input array, along the given axis and using a specified kind of sort to return the array of indices of data. This indices array is used to construct the sorted array. import numpy as np x = np.array([3, 1, 2]) print 'Our array is:' print x print '\n' print 'Applying argsort() to x:' y = np.argsort(x) print y print '\n' print 'Reconstruct original array in sorted order:' print x[y] print '\n' print 'Reconstruct the original array using loop:' for i in y: print x[i], It will produce the following output − Our array is: [3 1 2] Applying argsort() to x: [1 2 0] Reconstruct original array in sorted order: [1 2 3] Reconstruct the original array using loop: 1 2 3 function performs an indirect sort using a sequence of keys. The keys can be seen as a column in a spreadsheet. The function returns an array of indices, using which the sorted data can be obtained. Note, that the last key happens to be the primary key of sort. import numpy as np nm = ('raju','anil','ravi','amar') dv = ('f.y.', 's.y.', 's.y.', 'f.y.') ind = np.lexsort((dv,nm)) print 'Applying lexsort() function:' print ind print '\n' print 'Use this index to get sorted data:' print [nm[i] + ", " + dv[i] for i in ind] It will produce the following output − Applying lexsort() function: [3 1 0 2] Use this index to get sorted data: ['amar, f.y.', 'anil, s.y.', 'raju, f.y.', 'ravi, s.y.'] NumPy module has a number of functions for searching inside an array. Functions for finding the maximum, the minimum as well as the elements satisfying a given condition are available. These two functions return the indices of maximum and minimum elements respectively along the given axis. import numpy as np a = np.array([[30,40,70],[80,20,10],[50,90,60]]) print 'Our array is:' print a print '\n' print 'Applying argmax() function:' print np.argmax(a) print '\n' print 'Index of maximum number in flattened array' print a.flatten() print '\n' print 'Array containing indices of maximum along axis 0:' maxindex = np.argmax(a, axis = 0) print maxindex print '\n' print 'Array containing indices of maximum along axis 1:' maxindex = np.argmax(a, axis = 1) print maxindex print '\n' print 'Applying argmin() function:' minindex = np.argmin(a) print minindex print '\n' print 'Flattened array:' print a.flatten()[minindex] print '\n' print 'Flattened array along axis 0:' minindex = np.argmin(a, axis = 0) print minindex print '\n' print 'Flattened array along axis 1:' minindex = np.argmin(a, axis = 1) print minindex It will produce the following output − Our array is: [[30 40 70] [80 20 10] [50 90 60]] Applying argmax() function: 7 Index of maximum number in flattened array [30 40 70 80 20 10 50 90 60] Array containing indices of maximum along axis 0: [1 2 0] Array containing indices of maximum along axis 1: [2 0 1] Applying argmin() function: 5 Flattened array: 10 Flattened array along axis 0: [0 1 1] Flattened array along axis 1: [0 2 0] The numpy.nonzero() function returns the indices of non-zero elements in the input array. import numpy as np a = np.array([[30,40,0],[0,20,10],[50,0,60]]) print 'Our array is:' print a print '\n' print 'Applying nonzero() function:' print np.nonzero (a) It will produce the following output − Our array is: [[30 40 0] [ 0 20 10] [50 0 60]] Applying nonzero() function: (array([0, 0, 1, 1, 2, 2]), array([0, 1, 1, 2, 0, 2])) The where() function returns the indices of elements in an input array where the given condition is satisfied. import numpy as np x = np.arange(9.).reshape(3, 3) print 'Our array is:' print x print 'Indices of elements > 3' y = np.where(x > 3) print y print 'Use these indices to get elements satisfying the condition' print x[y] It will produce the following output − Our array is: [[ 0. 1. 2.] [ 3. 4. 5.] [ 6. 7. 8.]] Indices of elements > 3 (array([1, 1, 2, 2, 2]), array([1, 2, 0, 1, 2])) Use these indices to get elements satisfying the condition [ 4. 5. 6. 7. 8.] The extract() function returns the elements satisfying any condition. import numpy as np x = np.arange(9.).reshape(3, 3) print 'Our array is:' print x # define a condition condition = np.mod(x,2) == 0 print 'Element-wise value of condition' print condition print 'Extract elements using condition' print np.extract(condition, x) It will produce the following output − Our array is: [[ 0. 1. 2.] [ 3. 4. 5.] [ 6. 7. 8.]] Element-wise value of condition [[ True False True] [False True False] [ True False True]] Extract elements using condition [ 0. 2. 4. 6. 8.]
[ { "code": null, "e": 2704, "s": 2377, "text": "A variety of sorting related functions are available in NumPy. These sorting functions implement different sorting algorithms, each of them characterized by the speed of execution, worst case performance, the workspace required and the stability of algorithms. Following table shows the comparison of three sorting algorithms." }, { "code": null, "e": 2800, "s": 2704, "text": "The sort() function returns a sorted copy of the input array. It has the following parameters −" }, { "code": null, "e": 2834, "s": 2800, "text": "numpy.sort(a, axis, kind, order)\n" }, { "code": null, "e": 2841, "s": 2834, "text": "Where," }, { "code": null, "e": 2843, "s": 2841, "text": "a" }, { "code": null, "e": 2862, "s": 2843, "text": "Array to be sorted" }, { "code": null, "e": 2867, "s": 2862, "text": "axis" }, { "code": null, "e": 2973, "s": 2867, "text": "The axis along which the array is to be sorted. If none, the array is flattened, sorting on the last axis" }, { "code": null, "e": 2978, "s": 2973, "text": "kind" }, { "code": null, "e": 2999, "s": 2978, "text": "Default is quicksort" }, { "code": null, "e": 3005, "s": 2999, "text": "order" }, { "code": null, "e": 3068, "s": 3005, "text": "If the array contains fields, the order of fields to be sorted" }, { "code": null, "e": 3567, "s": 3068, "text": "import numpy as np \na = np.array([[3,7],[9,1]]) \n\nprint 'Our array is:' \nprint a \nprint '\\n'\n\nprint 'Applying sort() function:' \nprint np.sort(a) \nprint '\\n' \n \nprint 'Sort along axis 0:' \nprint np.sort(a, axis = 0) \nprint '\\n' \n\n# Order parameter in sort function \ndt = np.dtype([('name', 'S10'),('age', int)]) \na = np.array([(\"raju\",21),(\"anil\",25),(\"ravi\", 17), (\"amar\",27)], dtype = dt) \n\nprint 'Our array is:' \nprint a \nprint '\\n' \n\nprint 'Order by name:' \nprint np.sort(a, order = 'name')" }, { "code": null, "e": 3606, "s": 3567, "text": "It will produce the following output −" }, { "code": null, "e": 3852, "s": 3606, "text": "Our array is:\n[[3 7]\n [9 1]]\n\nApplying sort() function:\n[[3 7]\n [1 9]]\n\nSort along axis 0:\n[[3 1]\n [9 7]]\n\nOur array is:\n[('raju', 21) ('anil', 25) ('ravi', 17) ('amar', 27)]\n\nOrder by name:\n[('amar', 27) ('anil', 25) ('raju', 21) ('ravi', 17)]\n" }, { "code": null, "e": 4077, "s": 3852, "text": "The numpy.argsort() function performs an indirect sort on input array, along the given axis and using a specified kind of sort to return the array of indices of data. This indices array is used to construct the sorted array." }, { "code": null, "e": 4404, "s": 4077, "text": "import numpy as np \nx = np.array([3, 1, 2]) \n\nprint 'Our array is:' \nprint x \nprint '\\n' \n\nprint 'Applying argsort() to x:' \ny = np.argsort(x) \nprint y \nprint '\\n' \n\nprint 'Reconstruct original array in sorted order:' \nprint x[y] \nprint '\\n' \n\nprint 'Reconstruct the original array using loop:' \nfor i in y: \n print x[i]," }, { "code": null, "e": 4443, "s": 4404, "text": "It will produce the following output −" }, { "code": null, "e": 4603, "s": 4443, "text": "Our array is:\n[3 1 2]\n\nApplying argsort() to x:\n[1 2 0]\n\nReconstruct original array in sorted order:\n[1 2 3]\n\nReconstruct the original array using loop:\n1 2 3\n" }, { "code": null, "e": 4865, "s": 4603, "text": "function performs an indirect sort using a sequence of keys. The keys can be seen as a column in a spreadsheet. The function returns an array of indices, using which the sorted data can be obtained. Note, that the last key happens to be the primary key of sort." }, { "code": null, "e": 5139, "s": 4865, "text": "import numpy as np \n\nnm = ('raju','anil','ravi','amar') \ndv = ('f.y.', 's.y.', 's.y.', 'f.y.') \nind = np.lexsort((dv,nm)) \n\nprint 'Applying lexsort() function:' \nprint ind \nprint '\\n' \n\nprint 'Use this index to get sorted data:' \nprint [nm[i] + \", \" + dv[i] for i in ind] " }, { "code": null, "e": 5178, "s": 5139, "text": "It will produce the following output −" }, { "code": null, "e": 5311, "s": 5178, "text": "Applying lexsort() function:\n[3 1 0 2]\n\nUse this index to get sorted data:\n['amar, f.y.', 'anil, s.y.', 'raju, f.y.', 'ravi, s.y.']\n" }, { "code": null, "e": 5496, "s": 5311, "text": "NumPy module has a number of functions for searching inside an array. Functions for finding the maximum, the minimum as well as the elements satisfying a given condition are available." }, { "code": null, "e": 5602, "s": 5496, "text": "These two functions return the indices of maximum and minimum elements respectively along the given axis." }, { "code": null, "e": 6476, "s": 5602, "text": "import numpy as np \na = np.array([[30,40,70],[80,20,10],[50,90,60]]) \n\nprint 'Our array is:' \nprint a \nprint '\\n' \n\nprint 'Applying argmax() function:' \nprint np.argmax(a) \nprint '\\n' \n\nprint 'Index of maximum number in flattened array' \nprint a.flatten() \nprint '\\n' \n\nprint 'Array containing indices of maximum along axis 0:' \nmaxindex = np.argmax(a, axis = 0) \nprint maxindex \nprint '\\n' \n\nprint 'Array containing indices of maximum along axis 1:' \nmaxindex = np.argmax(a, axis = 1) \nprint maxindex \nprint '\\n' \n\nprint 'Applying argmin() function:' \nminindex = np.argmin(a) \nprint minindex \nprint '\\n' \n \nprint 'Flattened array:' \nprint a.flatten()[minindex] \nprint '\\n' \n\nprint 'Flattened array along axis 0:' \nminindex = np.argmin(a, axis = 0) \nprint minindex\nprint '\\n'\n\nprint 'Flattened array along axis 1:' \nminindex = np.argmin(a, axis = 1) \nprint minindex" }, { "code": null, "e": 6515, "s": 6476, "text": "It will produce the following output −" }, { "code": null, "e": 6919, "s": 6515, "text": "Our array is:\n[[30 40 70]\n [80 20 10]\n [50 90 60]]\n\nApplying argmax() function:\n7\n\nIndex of maximum number in flattened array\n[30 40 70 80 20 10 50 90 60]\n\nArray containing indices of maximum along axis 0:\n[1 2 0]\n\nArray containing indices of maximum along axis 1:\n[2 0 1]\n\nApplying argmin() function:\n5\n\nFlattened array:\n10\n\nFlattened array along axis 0:\n[0 1 1]\n\nFlattened array along axis 1:\n[0 2 0]\n" }, { "code": null, "e": 7009, "s": 6919, "text": "The numpy.nonzero() function returns the indices of non-zero elements in the input array." }, { "code": null, "e": 7182, "s": 7009, "text": "import numpy as np \na = np.array([[30,40,0],[0,20,10],[50,0,60]]) \n\nprint 'Our array is:' \nprint a \nprint '\\n' \n\nprint 'Applying nonzero() function:' \nprint np.nonzero (a)" }, { "code": null, "e": 7221, "s": 7182, "text": "It will produce the following output −" }, { "code": null, "e": 7356, "s": 7221, "text": "Our array is:\n[[30 40 0]\n [ 0 20 10]\n [50 0 60]]\n\nApplying nonzero() function:\n(array([0, 0, 1, 1, 2, 2]), array([0, 1, 1, 2, 0, 2]))\n" }, { "code": null, "e": 7467, "s": 7356, "text": "The where() function returns the indices of elements in an input array where the given condition is satisfied." }, { "code": null, "e": 7699, "s": 7467, "text": "import numpy as np \nx = np.arange(9.).reshape(3, 3) \n\nprint 'Our array is:' \nprint x \n\nprint 'Indices of elements > 3' \ny = np.where(x > 3) \nprint y \n\nprint 'Use these indices to get elements satisfying the condition' \nprint x[y]" }, { "code": null, "e": 7738, "s": 7699, "text": "It will produce the following output −" }, { "code": null, "e": 7945, "s": 7738, "text": "Our array is:\n[[ 0. 1. 2.]\n [ 3. 4. 5.]\n [ 6. 7. 8.]]\n\nIndices of elements > 3\n(array([1, 1, 2, 2, 2]), array([1, 2, 0, 1, 2]))\n\nUse these indices to get elements satisfying the condition\n[ 4. 5. 6. 7. 8.]\n" }, { "code": null, "e": 8015, "s": 7945, "text": "The extract() function returns the elements satisfying any condition." }, { "code": null, "e": 8289, "s": 8015, "text": "import numpy as np \nx = np.arange(9.).reshape(3, 3) \n\nprint 'Our array is:' \nprint x \n\n# define a condition \ncondition = np.mod(x,2) == 0 \n\nprint 'Element-wise value of condition' \nprint condition \n\nprint 'Extract elements using condition' \nprint np.extract(condition, x)" }, { "code": null, "e": 8328, "s": 8289, "text": "It will produce the following output −" } ]
Lodash | _.differenceWith() Method - GeeksforGeeks
08 May, 2020 The _.differenceWith() method is similar to _.difference() method that returns the array containing the values that are in the first array not in the second array but in _.differenceWith() all the elements of the first array are compared with the second array by applying comparison provided in third. It may be a little complex to understand by reading this but it will become simple when you see the example. Syntax: _.differenceWith(array, [values], [comparator]) Parameters: This method accept three parameters as mentioned above and described below: array: This parameter holds the array that values are checked or inspect. values: This parameter holds the value that need to be removed. comparator: This parameter holds the comparison invoked per element. Return Value: This method returns an array according to the condition explained above. Example 1: const _ = require('lodash') let x = [1, 2, 3] let y = [2, 4, 5] let result = _.differenceWith(x, y, _.isEqual); console.log(result); Here, const _ = require('lodash') is used to import the lodash library into the file. Output: [1, 3] So, here each element of the first array is compared with each element of the second array according to the third comparator, in our case its _.isEqual. So, if the value becomes equal it removes it. Example 2: const _ = require('lodash'); let x = [{a: 1}, {b: 2}, 6] let y = [{a: 1}, 7, 6] let result = _.differenceWith(x, y, _.isEqual); console.log(result); Output: [{b: 2}] Example 3: const _ = require('lodash'); let x1 = [1, 2, 3] let y1 = [2, 4, 5] let result1 = _.differenceWith(x1, y1, _.isEqual); console.log(result1); let x2 = [{a: 1}, {b: 2}, 6] let y2 = [{a: 1}, 7, 6] let result2 = _.differenceWith(x2, y2, _.isEqual); console.log('\n\n', result2); Output: Note: This will not work in normal JavaScript because it requires the library lodash to be installed. Reference: https://lodash.com/docs/4.17.15#differenceWith JavaScript-Lodash JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to calculate the number of days between two dates in javascript? Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Convert a string to an integer in JavaScript File uploading in React.js 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": 37356, "s": 37328, "text": "\n08 May, 2020" }, { "code": null, "e": 37767, "s": 37356, "text": "The _.differenceWith() method is similar to _.difference() method that returns the array containing the values that are in the first array not in the second array but in _.differenceWith() all the elements of the first array are compared with the second array by applying comparison provided in third. It may be a little complex to understand by reading this but it will become simple when you see the example." }, { "code": null, "e": 37775, "s": 37767, "text": "Syntax:" }, { "code": null, "e": 37823, "s": 37775, "text": "_.differenceWith(array, [values], [comparator])" }, { "code": null, "e": 37911, "s": 37823, "text": "Parameters: This method accept three parameters as mentioned above and described below:" }, { "code": null, "e": 37985, "s": 37911, "text": "array: This parameter holds the array that values are checked or inspect." }, { "code": null, "e": 38049, "s": 37985, "text": "values: This parameter holds the value that need to be removed." }, { "code": null, "e": 38118, "s": 38049, "text": "comparator: This parameter holds the comparison invoked per element." }, { "code": null, "e": 38205, "s": 38118, "text": "Return Value: This method returns an array according to the condition explained above." }, { "code": null, "e": 38216, "s": 38205, "text": "Example 1:" }, { "code": "const _ = require('lodash') let x = [1, 2, 3] let y = [2, 4, 5] let result = _.differenceWith(x, y, _.isEqual); console.log(result);", "e": 38353, "s": 38216, "text": null }, { "code": null, "e": 38439, "s": 38353, "text": "Here, const _ = require('lodash') is used to import the lodash library into the file." }, { "code": null, "e": 38447, "s": 38439, "text": "Output:" }, { "code": null, "e": 38454, "s": 38447, "text": "[1, 3]" }, { "code": null, "e": 38653, "s": 38454, "text": "So, here each element of the first array is compared with each element of the second array according to the third comparator, in our case its _.isEqual. So, if the value becomes equal it removes it." }, { "code": null, "e": 38664, "s": 38653, "text": "Example 2:" }, { "code": "const _ = require('lodash'); let x = [{a: 1}, {b: 2}, 6] let y = [{a: 1}, 7, 6] let result = _.differenceWith(x, y, _.isEqual); console.log(result);", "e": 38817, "s": 38664, "text": null }, { "code": null, "e": 38825, "s": 38817, "text": "Output:" }, { "code": null, "e": 38835, "s": 38825, "text": "[{b: 2}]\n" }, { "code": null, "e": 38846, "s": 38835, "text": "Example 3:" }, { "code": "const _ = require('lodash'); let x1 = [1, 2, 3] let y1 = [2, 4, 5] let result1 = _.differenceWith(x1, y1, _.isEqual); console.log(result1); let x2 = [{a: 1}, {b: 2}, 6] let y2 = [{a: 1}, 7, 6] let result2 = _.differenceWith(x2, y2, _.isEqual); console.log('\\n\\n', result2);", "e": 39128, "s": 38846, "text": null }, { "code": null, "e": 39136, "s": 39128, "text": "Output:" }, { "code": null, "e": 39238, "s": 39136, "text": "Note: This will not work in normal JavaScript because it requires the library lodash to be installed." }, { "code": null, "e": 39296, "s": 39238, "text": "Reference: https://lodash.com/docs/4.17.15#differenceWith" }, { "code": null, "e": 39314, "s": 39296, "text": "JavaScript-Lodash" }, { "code": null, "e": 39325, "s": 39314, "text": "JavaScript" }, { "code": null, "e": 39342, "s": 39325, "text": "Web Technologies" }, { "code": null, "e": 39440, "s": 39342, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 39449, "s": 39440, "text": "Comments" }, { "code": null, "e": 39462, "s": 39449, "text": "Old Comments" }, { "code": null, "e": 39531, "s": 39462, "text": "How to calculate the number of days between two dates in javascript?" }, { "code": null, "e": 39592, "s": 39531, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 39664, "s": 39592, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 39709, "s": 39664, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 39736, "s": 39709, "text": "File uploading in React.js" }, { "code": null, "e": 39778, "s": 39736, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 39811, "s": 39778, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 39854, "s": 39811, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 39916, "s": 39854, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
C++ Program to Make a Simple Calculator to Add, Subtract, Multiply or Divide Using switch...case
Let us see a program to create a simple calculator in C++, with Add, Subtract, Multiply and Divide operations. Live Demo #include <iostream> using namespace std; void calculator(int a, int b, char op) { switch (op) { case '+': { cout<<"Sum of "<<a<<" and "<<b<<" is "<<a+b<<endl; break; } case '-': { cout<<"Difference of "<<a<<" and "<<b<<" is "<<a-b<<endl; break; } case '*': { cout<<"Product of "<<a<<" and "<<b<<" is "<<a*b<<endl; break; } case '/': { cout<<"Division of "<<a<<" and "<<b<<" is "<<a/b<<endl; break; } default: cout<<"Invalid Input"<<endl; } } int main() { calculator(5,4,'+'); calculator(10,3,'-'); calculator(3,2,'*'); calculator(20,5,'/'); calculator(5,2,'?'); return 0; } Sum of 5 and 4 is 9 Difference of 10 and 3 is 7 Product of 3 and 2 is 6 Division of 20 and 5 is 4 Invalid Input In the above program, a function calculator is used to add, subtract, multiply and divide two numbers. This is done using a switch case statement. The function takes 3 parameters i.e. two numbers on which the operation is to be performed and what operation is to be performed. This is shown as follows − void calculator(int a, int b, char op) There are 4 cases in the switch case statement and one default case. The first case is used when addition is to be performed. The two numbers are added and their sum is displayed. This is shown using the following code snippet. case '+': { cout<<"Sum of "<<a<<" and "<<b<<" is "<<a+b<<endl; break; } The second case is used when subtraction is to be performed. The two numbers are subtracted and their difference is displayed. This is shown using the following code snippet. case '-': { cout<<"Difference of "<<a<<" and "<<b<<" is "<<a-b<<endl; break; } The third case is used when multiplication is to be performed. The two numbers are multiplied and their product is displayed. This is shown using the following code snippet. case '*': { cout<<"Product of "<<a<<" and "<<b<<" is "<<a*b<<endl; break; } The fourth case is used when division is to be performed. The two numbers are divided and their division is displayed. This is shown using the following code snippet. case '/': { cout<<"Division of "<<a<<" and "<<b<<" is "<<a/b<<endl; break; } The default case is used for invalid operator provided.This is shown using the following code snippet. default: cout<<"Invalid Input"<<endl; The function calculator() is called from main() for different operations and using different operands. This is demonstrated by the following code snippet. calculator(5,4,'+'); calculator(10,3,'-'); calculator(3,2,'*'); calculator(20,5,'/'); calculator(5,2,'?');
[ { "code": null, "e": 1173, "s": 1062, "text": "Let us see a program to create a simple calculator in C++, with Add, Subtract, Multiply and Divide operations." }, { "code": null, "e": 1184, "s": 1173, "text": " Live Demo" }, { "code": null, "e": 1914, "s": 1184, "text": "#include <iostream>\nusing namespace std;\nvoid calculator(int a, int b, char op) {\n switch (op) {\n case '+': {\n cout<<\"Sum of \"<<a<<\" and \"<<b<<\" is \"<<a+b<<endl;\n break;\n }\n case '-': {\n cout<<\"Difference of \"<<a<<\" and \"<<b<<\" is \"<<a-b<<endl;\n break;\n }\n case '*': {\n cout<<\"Product of \"<<a<<\" and \"<<b<<\" is \"<<a*b<<endl;\n break;\n }\n case '/': {\n cout<<\"Division of \"<<a<<\" and \"<<b<<\" is \"<<a/b<<endl;\n break;\n }\n default:\n cout<<\"Invalid Input\"<<endl;\n }\n}\nint main() {\n calculator(5,4,'+');\n calculator(10,3,'-');\n calculator(3,2,'*');\n calculator(20,5,'/');\n calculator(5,2,'?');\n return 0;\n}" }, { "code": null, "e": 2026, "s": 1914, "text": "Sum of 5 and 4 is 9\nDifference of 10 and 3 is 7\nProduct of 3 and 2 is 6\nDivision of 20 and 5 is 4\nInvalid Input" }, { "code": null, "e": 2330, "s": 2026, "text": "In the above program, a function calculator is used to add, subtract, multiply and divide two numbers. This is done using a switch case statement. The function takes 3 parameters i.e. two numbers on which the operation is to be performed and what operation is to be performed. This is shown as follows −" }, { "code": null, "e": 2369, "s": 2330, "text": "void calculator(int a, int b, char op)" }, { "code": null, "e": 2597, "s": 2369, "text": "There are 4 cases in the switch case statement and one default case. The first case is used when addition is to be performed. The two numbers are added and their sum is displayed. This is shown using the following code snippet." }, { "code": null, "e": 2675, "s": 2597, "text": "case '+': {\n cout<<\"Sum of \"<<a<<\" and \"<<b<<\" is \"<<a+b<<endl;\n break;\n}" }, { "code": null, "e": 2850, "s": 2675, "text": "The second case is used when subtraction is to be performed. The two numbers are subtracted and their difference is displayed. This is shown using the following code snippet." }, { "code": null, "e": 2935, "s": 2850, "text": "case '-': {\n cout<<\"Difference of \"<<a<<\" and \"<<b<<\" is \"<<a-b<<endl;\n break;\n}" }, { "code": null, "e": 3109, "s": 2935, "text": "The third case is used when multiplication is to be performed. The two numbers are multiplied and their product is displayed. This is shown using the following code snippet." }, { "code": null, "e": 3191, "s": 3109, "text": "case '*': {\n cout<<\"Product of \"<<a<<\" and \"<<b<<\" is \"<<a*b<<endl;\n break;\n}" }, { "code": null, "e": 3358, "s": 3191, "text": "The fourth case is used when division is to be performed. The two numbers are divided and their division is displayed. This is shown using the following code snippet." }, { "code": null, "e": 3435, "s": 3358, "text": "case '/': {\ncout<<\"Division of \"<<a<<\" and \"<<b<<\" is \"<<a/b<<endl;\nbreak;\n}" }, { "code": null, "e": 3538, "s": 3435, "text": "The default case is used for invalid operator provided.This is shown using the following code snippet." }, { "code": null, "e": 3576, "s": 3538, "text": "default: cout<<\"Invalid Input\"<<endl;" }, { "code": null, "e": 3731, "s": 3576, "text": "The function calculator() is called from main() for different operations and using different operands. This is demonstrated by the following code snippet." }, { "code": null, "e": 3838, "s": 3731, "text": "calculator(5,4,'+');\ncalculator(10,3,'-');\ncalculator(3,2,'*');\ncalculator(20,5,'/');\ncalculator(5,2,'?');" } ]
A Beginners Guide to Match Any Pattern Using Regular Expressions in R | by Rashida Nasrin Sucky | Towards Data Science
The regular expression is nothing but a sequence of characters that matches a pattern in a piece of text or a text file. It is used in text mining in a lot of programming languages. The characters of the regular expression are pretty similar in all the languages. But the functions of extracting, locating, detecting, and replacing can be different in different languages. In this article, I will use R. But you can learn how to use the regular expression from this article even if you wish to use some other language. It may look too complicated when you do not know it. But as I mentioned at the top it is easier than you think it is. I will try to explain it as much as I can. You are welcome to ask me questions in the comment section if you did not understand any part. Here we will learn by doing. I will start with very basic ideas and slowly move towards more complicated patterns. I used RStudio for all the exercises in this article. Here is a set of 7 strings that contain, different patterns. We will use this to learn all the basics. ch = c('Nancy Smith', 'is there any solution?', ".[{(^$|?*+", "coreyms.com", "321-555-4321", "123.555.1234", "123*555*1234" ) Extract all the dots or periods from those texts: R has a function called ‘str_extract_all’ that will extract all the dots from these strings. This function takes two parameters. First the texts of interest and second, the element to be extracted. str_extract_all(ch, "\\.") Output: [[1]]character(0)[[2]]character(0)[[3]][1] "."[[4]][1] "."[[5]]character(0)[[6]][1] "." "."[[7]]character(0) Look at the output carefully. The Third-string has one dot. Forth string has one dot and the Sixth string has two dots. There is another function in R ‘str_extract’ that only extracts the first dot from each string. Try it yourself. I will use str_extract_all for all the demonstrations in this article to find it all. Before going into more workouts, it will be good to see a list of patterns of regular expressions: . = Matches Any Character . = Matches Any Character 2. \d = Digit (0–9) 3. \D = Not a digit (0–9) 4. \w = Word Character (a-z, A-Z, 0–9, _) 5. \W = Not a word character 6. \s = Whitespace (space, tab, newline) 7. \S = Not whitespace (space, tab, newline) 8. \b = Word Boundary 9. \B = Not a word boundary 10. ^ = Beginning of a string 11. $ = End of a String 12. [] = matches characters or brackets 13. [^ ] = matches characters Not in backets14. | = Either Or 15. ( ) = Group 16. *= 0 or more 17. + = 1 or more 18. ? = Yes or No 19. {x} = Exact Number 20. {x, y} = Range of Numbers (Maximum, Minimum) We will keep referring to this list of expressions while working later. We will work on all of them individually first and then in groups. As per the list above, ‘\d’ catches the digits. Extract all the digits from the ‘ch’: str_extract_all(ch, "\\d") Output: [[1]]character(0)[[2]]character(0)[[3]]character(0)[[4]]character(0)[[5]] [1] "3" "2" "1" "5" "5" "5" "4" "3" "2" "1"[[6]] [1] "1" "2" "3" "5" "5" "5" "1" "2" "3" "4"[[7]] [1] "1" "2" "3" "5" "5" "5" "1" "2" "3" "4" The first four strings do not have any digits. The last three strings are phone numbers. The expression above could catch all the digits from the last three strings. The capital ‘D’ will catch everything else but the digits. str_extract_all(ch, "\\D") Output: [[1]][1] "a" "b" "c" "d" "e" "f" "g" "h" "i"[[2]][1] "A" "B" "C" "D" "E" "F" "G" "H" "I"[[3]] [1] "T" "h" "i" "s" " " "i" "s" " " "m" "e"[[4]] [1] "." "[" "{" "(" "^" "$" "|" "?" "*" "+"[[5]] [1] "c" "o" "r" "e" "y" "m" "s" "." "c" "o" "m"[[6]][1] "-" "-"[[7]][1] "." "."[[8]][1] "*" "*" Look, it extracted letters, dots, and other special characters but did not extract any digits. ‘w’ matches word characters that include a-z, A-Z, 0–9, and ‘_’. Let’s check. str_extract_all(ch, "\\w") Output: [[1]][1] "a" "b" "c" "d" "e" "f" "g" "h" "i"[[2]][1] "A" "B" "C" "D" "E" "F" "G" "H" "I"[[3]][1] "T" "h" "i" "s" "i" "s" "m" "e"[[4]]character(0)[[5]] [1] "c" "o" "r" "e" "y" "m" "s" "c" "o" "m"[[6]] [1] "3" "2" "1" "5" "5" "5" "4" "3" "2" "1"[[7]] [1] "1" "2" "3" "5" "5" "5" "1" "2" "3" "4"[[8]] [1] "1" "2" "3" "5" "5" "5" "1" "2" "3" "4" It got everything except dots and special characters. However, ‘W’ extracts everything but the word characters. str_extract_all(ch, "\\W") Output: [[1]]character(0)[[2]]character(0)[[3]][1] " " " "[[4]] [1] "." "[" "{" "(" "^" "$" "|" "?" "*" "+"[[5]][1] "."[[6]][1] "-" "-" I will move to show ‘b’ and ‘B’ now. ‘b’ catches the word boundary. Here is an example: st = "This is Bliss"str_extract_all(st, "\\bis") Output: [[1]][1] "is" There is only one ‘is’ in the string. So we could catch it here. Let’s see the use of ‘B’ st = "This is Bliss"str_extract_all(st, "\\Bis") Output: [[1]][1] "is" "is" In the string ‘st’ there are two other ‘is’s that’s not in the boundary. That’s in the word ‘This’ and ‘Bliss’. When you use capital B, you catch those. Number 10 and 11 in the list of expression above are ‘^’ and ‘$’ which indicates the beginning and end of the strings respectively. Here is an example: sts = c("This is me", "That my house", "Hello, world!") Find all the exclamation points that end a sentence. str_extract_all(sts, "!$") Output: [[1]]character(0)[[2]]character(0)[[3]][1] "!" We have only one sentence that ends with an exclamation point. If R users want to find the sentence that ends with an exclamation point: sts[str_detect(sts, "!$")] Output: [1] "Hello, world!" Find the sentences that start with ‘This’. sts[str_detect(sts, "^This")] Output: [1] "This is me" That is also only one. Let’s find the sentences that start with “T”. sts[str_detect(sts, "^T")] Output: [1] "This is me" "That my house" ‘[]’ matches characters or ranges in it. For this demonstration, let’s go back to ‘ch’. Extract everything in between 2–4. str_extract_all(ch, "[2-4]") Output: [[1]]character(0)[[2]]character(0)[[3]]character(0)[[4]]character(0)[[5]][1] "3" "2" "4" "3" "2"[[6]][1] "2" "3" "2" "3" "4"[[7]][1] "2" "3" "2" "3" "4" Let’s move on to some bigger experiment Extract the phone numbers only from ‘ch’. I will explain the pattern after you see the output: str_extract(ch, "\\d\\d\\d.\\d\\d\\d.\\d\\d\\d\\d") Output: [1] NA NA NA [4] NA "321-555-4321" "123.555.1234"[7] "123*555*1234" In the regular expression above, each ‘\\d’ means a digit, and ‘.’ can match anything in between (look at the number 1 in the list of expressions in the beginning). So we got the digits, then a special character in between, three more digits, then special characters again, then 4 more digits. So anything that matches these criteria were extracted. The regular expression for the phone number above can be written as follows as well. str_extract(ch, "\\d{3}.\\d{3}.\\d{4}") Output: [1] NA NA NA [4] NA "321-555-4321" "123.555.1234"[7] "123*555*1234" Look at number 19 of the expression list. {x} means the exact number. Here we used {3} which means exactly 3 times. ‘\\d{3}’ means three digits. But look ‘*’ in-between digits is not a regular phone number format. Normally ‘-’ or ‘.’ may be used as a separator in phone numbers. Right? Let’s match that and exclude the phone number with ‘*’. Because that may look like a 10 digit phone number but it may not be a phone number. We want to stick to the regular phone number format. str_extract(ch, "\\d{3}[-.]\\d{3}[-.]\\d{4}") Output: [1] NA NA NA [4] NA "321-555-4321" "123.555.1234"[7] NA Look, this matches only the usual phone number format. In this expression, after three digits we explicitly mentioned ‘[-.]’ which means it is asking to match only ‘-’ or a dot (‘.’). Here is a list of phone numbers: ph = c("543-325-1278", "900-123-7865", "421.235.9845", "453*2389*4567", "800-565-1112", "361 234 4356" ) If we use the above expression on these phone numbers, this is what happens: str_extract(ph, "\\d{3}[-.]\\d{3}[-.]\\d{4}") Output: [1] "543-325-1278" "900-123-7865" "421.235.9845"[4] NA "800-565-1112" NA Look! This format excluded “361 234 4356”. Sometimes we do not use any separators in between and just use a space, right? Also, the first digit of a US phone number is not 0 or 1. It’s a number between 2–9. All the other digits can be anything between 0 and 9. Let’s take care of that pattern. p = "([2-9][0-9]{2})([- .]?)([0-9]{3})([- .])?([0-9]{4})"str_extract(ph, p) I saved the pattern separately here. In regular expression ‘()’ is used to denote a group. Look at number 15 of the list of expressions. Here is the breakdown of the expressions above. The first group was “([2–9][0–9]{2})”: ‘[2–9]’ represents one digit from 2 to 9 ‘[0–9]{2}’ represents two digits from 0 to 9 The second group was “([- .]?)”: ‘[-.]’ means it can be ‘-’ or ‘.’ using ‘?’ after that means ‘-’ and ‘.’ are optional. So, if it is blank that’s also ok. I guess the rest of the groups are also clear now. Here is the output of the expression above: [1] "543-325-1278" "900-123-7865" "421.235.9845"[4] NA "800-565-1112" "361 234 4356" It finds the phone number with ‘-’, ‘.’, and also with blanks as a separator. What if we need to find the phone number that starts with 800 and 900. p = "[89]00[-.]\\d{3}[-.]\\d{4}"str_extract_all(ph, p) Output: [[1]]character(0)[[2]][1] "900-123-7865"[[3]]character(0)[[4]]character(0)[[5]][1] "800-565-1112"[[6]]character(0) Let’s understand the regular expression above: “[89]00[-.]\\d{3}[-.]\\d{4}”. The first character should be 8 or 9. That can be achieved by [89]. The next two elements will be zeros. We explicitly mentioned that. Then ‘-’ or ‘.’ which can be obtained by [-.]. Next three digits = \\d{3} Again ‘-’ or ‘.’ = [-.] Four more digits at the end = \\d{4} Extract different formats of Email Addresses Email addresses are a little more complicated than phone numbers. Because an email address may contain upper case letters, lower case letters, digits, special characters everything. Here is a set of email addresses: email = c("[email protected]", "[email protected]", "[email protected]", "[email protected]") We will develop a regular expression that will extract all of those email addresses: First work on the part before the ‘@’ symbol. This part may have lower case letters that can be detected using [a-z], upper case letters that can be detected using [A-Z], digits that can be found using [0–9], and special characters like ‘.’, and ‘_’. All of them can be packed like this: “[a-zA-Z0–9-.]+” The ‘+’ sign indicates one or more of those characters (look at the number 17 of the list of expressions). Because we do not know how many different letters, digits or numbers can be there. So this time we cannot use {x} the way we did for phone numbers. Now work on the part in-between ‘@’ and ‘.’. This part may consist of upper case letters, lower case letters, and digits that can be detected as: “[a-zA_Z0–9]+” Finally, the part after ‘.’. Here we have four of them ‘com’, ‘net’, ‘edu’, ‘org’. These four can be caught using a group: “(com|edu|net|org”) Here ‘|’ symbol is used to denote either-or. Look at number 14 of the list of expressions in the beginning. Here is the full expression: p = "[a-zA-Z0-9-.]+@[a-zA_Z0-9]+\\.(com|edu|net|org)"str_extract_all(email, p) Output: [[1]][1] "[email protected]"[[2]][1] "[email protected]"[[3]][1] "[email protected]"[[4]][1] "[email protected]" It will also work if you do not mention the parts after the dots. Because we added a ‘+’ sign after the second part that means it will take any number of characters after that. But if you need some certain domain type like ‘com’ or ‘net’, you have to explicitly mention them as we did in the previous expression. p = "[a-zA-Z0-9-.]+@[a-zA_Z0-9-.]+"str_extract_all(email, p) Output: [[1]][1] "[email protected]"[[2]][1] "[email protected]"[[3]][1] "[email protected]"[[4]][1] "[email protected]" Another common complicated type is URLs Here is a list of URLs: urls = c("https://regenerativetoday.com", "http://setf.ml", "https://www.yahoo.com", "http://studio_base.net", ) It may start with ‘http’ or ‘https’. To detect that this expression can be used: ‘https?’ That means ‘http’ will stay intact. Then there is a ‘?’ sign after ‘s’. So, ‘s’ is optional. It may or may not be there. Another optional part is after ‘://’ term: ‘www.’ We can define it using: “(www\\.)?” As we worked before, ‘()’ is used to group some expressions. Here we are grouping ‘www’ and ‘.’. After the parenthesis that ‘?’ means this whole term inside the parenthesis is optional. They may or may not be there. Then domain name. In this set of email addresses, we only have lower case letters and ‘_’. So, [a-z-] will work. But in a general domain name may contain upper case letters and digits as well. So we will use: “\\w+” Look at the number 4 of the list of expressions. ‘\\w’ denotes word character that may include lower case letters, upper case letters, and digits. The ‘+’ sign indicates that there might be one or more of those characters. After domain, there is one more dot and then more characters. We will get them using: “\\.\\w+” Remember, if you use only dot(.) to match a dot it will not work. Because only a single dot matches any character. If you have to match only a literal dot(.), you need to put it as ‘\\.’ Here we used one dot denoted by “\\.”, then word characters “\\w” and a ‘+’ sign to indicate there are more characters. Let’s put it together: p = "https?://(www\\.)?\\w+\\.\\w+"str_extract_all(urls, p) Output: [[1]][1] "https://regenerativetoday.com"[[2]][1] "http://setf.ml"[[3]][1] "https://www.yahoo.com"[[4]][1] "http://studio_base.com" You may want to get only ‘.com or ‘.net’ domains. That can be explicitly mentioned. p = "https?://(www\\.)?(\\w+)(\\.)+(com|net)"str_extract_all(urls, p) Output: [[1]][1] "https://regenerativetoday.com"[[2]]character(0)[[3]][1] "https://www.yahoo.com"[[4]][1] "http://studio_base.com" See, it only gets ‘.com’ or ‘.net’ domains and excludes the ‘.ml’ domain that we had. Finally work on a set of names That can be a bit tricky too. Here is a set of names: name = c("Mr. Jon", "Mrs. Jon", "Mr Ron", "Ms. Reene", "Ms Julie") Look, it may start with Mr, Ms, or Mrs. Sometimes a dot after Mr, sometimes not. Let’s work on this part first. In all of them ‘M’ is common. Keep it intact and make a group using the rest like this: “M(r|s|rs)” After ‘M’ it may be ‘r’ or ‘s’, or ‘rs’. Then an optional dot that can be obtained by using: “\\.?” There is a space after that can be detected with: “\\s” After the space name starts with an upper case letter that can be brought using: [A-Z]” After that upper case letters, there are some lower case letters and we do not know exactly how many. So, we will use this: “\\w*” Look at the number 16 of the list of expressions. ‘*’ means 0 or more. So, we are saying there might be 0 or more word characters. Putting it all together: p = "M(r|s|rs)\\.?[A-Z\\s]\\w*"str_extract_all(name, p) Output: [[1]][1] "Mr. Jon"[[2]][1] "Mrs. Jon"[[3]][1] "Mr Ron"[[4]][1] "Ms. Reene"[[5]][1] "Ms Julie" Congratulation! You worked on some complicated and cool patterns that should give you enough knowledge to use a regular expression to match almost any pattern. This is not all. There are a lot more in the regular expression. But if you are a beginner, you should be proud of yourself that you came a long way. You should be able to match almost any pattern now. I will make another tutorial sometime later on the advanced regular expression. But you should be able to start using regular expressions now to do some cool thing. Feel free to follow me on Twitter and like my Facebook page.
[ { "code": null, "e": 545, "s": 172, "text": "The regular expression is nothing but a sequence of characters that matches a pattern in a piece of text or a text file. It is used in text mining in a lot of programming languages. The characters of the regular expression are pretty similar in all the languages. But the functions of extracting, locating, detecting, and replacing can be different in different languages." }, { "code": null, "e": 947, "s": 545, "text": "In this article, I will use R. But you can learn how to use the regular expression from this article even if you wish to use some other language. It may look too complicated when you do not know it. But as I mentioned at the top it is easier than you think it is. I will try to explain it as much as I can. You are welcome to ask me questions in the comment section if you did not understand any part." }, { "code": null, "e": 1062, "s": 947, "text": "Here we will learn by doing. I will start with very basic ideas and slowly move towards more complicated patterns." }, { "code": null, "e": 1116, "s": 1062, "text": "I used RStudio for all the exercises in this article." }, { "code": null, "e": 1219, "s": 1116, "text": "Here is a set of 7 strings that contain, different patterns. We will use this to learn all the basics." }, { "code": null, "e": 1389, "s": 1219, "text": "ch = c('Nancy Smith', 'is there any solution?', \".[{(^$|?*+\", \"coreyms.com\", \"321-555-4321\", \"123.555.1234\", \"123*555*1234\" )" }, { "code": null, "e": 1439, "s": 1389, "text": "Extract all the dots or periods from those texts:" }, { "code": null, "e": 1637, "s": 1439, "text": "R has a function called ‘str_extract_all’ that will extract all the dots from these strings. This function takes two parameters. First the texts of interest and second, the element to be extracted." }, { "code": null, "e": 1664, "s": 1637, "text": "str_extract_all(ch, \"\\\\.\")" }, { "code": null, "e": 1672, "s": 1664, "text": "Output:" }, { "code": null, "e": 1781, "s": 1672, "text": "[[1]]character(0)[[2]]character(0)[[3]][1] \".\"[[4]][1] \".\"[[5]]character(0)[[6]][1] \".\" \".\"[[7]]character(0)" }, { "code": null, "e": 1901, "s": 1781, "text": "Look at the output carefully. The Third-string has one dot. Forth string has one dot and the Sixth string has two dots." }, { "code": null, "e": 1997, "s": 1901, "text": "There is another function in R ‘str_extract’ that only extracts the first dot from each string." }, { "code": null, "e": 2100, "s": 1997, "text": "Try it yourself. I will use str_extract_all for all the demonstrations in this article to find it all." }, { "code": null, "e": 2199, "s": 2100, "text": "Before going into more workouts, it will be good to see a list of patterns of regular expressions:" }, { "code": null, "e": 2225, "s": 2199, "text": ". = Matches Any Character" }, { "code": null, "e": 2251, "s": 2225, "text": ". = Matches Any Character" }, { "code": null, "e": 2271, "s": 2251, "text": "2. \\d = Digit (0–9)" }, { "code": null, "e": 2297, "s": 2271, "text": "3. \\D = Not a digit (0–9)" }, { "code": null, "e": 2339, "s": 2297, "text": "4. \\w = Word Character (a-z, A-Z, 0–9, _)" }, { "code": null, "e": 2368, "s": 2339, "text": "5. \\W = Not a word character" }, { "code": null, "e": 2409, "s": 2368, "text": "6. \\s = Whitespace (space, tab, newline)" }, { "code": null, "e": 2454, "s": 2409, "text": "7. \\S = Not whitespace (space, tab, newline)" }, { "code": null, "e": 2476, "s": 2454, "text": "8. \\b = Word Boundary" }, { "code": null, "e": 2504, "s": 2476, "text": "9. \\B = Not a word boundary" }, { "code": null, "e": 2534, "s": 2504, "text": "10. ^ = Beginning of a string" }, { "code": null, "e": 2558, "s": 2534, "text": "11. $ = End of a String" }, { "code": null, "e": 2598, "s": 2558, "text": "12. [] = matches characters or brackets" }, { "code": null, "e": 2660, "s": 2598, "text": "13. [^ ] = matches characters Not in backets14. | = Either Or" }, { "code": null, "e": 2676, "s": 2660, "text": "15. ( ) = Group" }, { "code": null, "e": 2693, "s": 2676, "text": "16. *= 0 or more" }, { "code": null, "e": 2711, "s": 2693, "text": "17. + = 1 or more" }, { "code": null, "e": 2729, "s": 2711, "text": "18. ? = Yes or No" }, { "code": null, "e": 2752, "s": 2729, "text": "19. {x} = Exact Number" }, { "code": null, "e": 2801, "s": 2752, "text": "20. {x, y} = Range of Numbers (Maximum, Minimum)" }, { "code": null, "e": 2873, "s": 2801, "text": "We will keep referring to this list of expressions while working later." }, { "code": null, "e": 2940, "s": 2873, "text": "We will work on all of them individually first and then in groups." }, { "code": null, "e": 2988, "s": 2940, "text": "As per the list above, ‘\\d’ catches the digits." }, { "code": null, "e": 3026, "s": 2988, "text": "Extract all the digits from the ‘ch’:" }, { "code": null, "e": 3053, "s": 3026, "text": "str_extract_all(ch, \"\\\\d\")" }, { "code": null, "e": 3061, "s": 3053, "text": "Output:" }, { "code": null, "e": 3277, "s": 3061, "text": "[[1]]character(0)[[2]]character(0)[[3]]character(0)[[4]]character(0)[[5]] [1] \"3\" \"2\" \"1\" \"5\" \"5\" \"5\" \"4\" \"3\" \"2\" \"1\"[[6]] [1] \"1\" \"2\" \"3\" \"5\" \"5\" \"5\" \"1\" \"2\" \"3\" \"4\"[[7]] [1] \"1\" \"2\" \"3\" \"5\" \"5\" \"5\" \"1\" \"2\" \"3\" \"4\"" }, { "code": null, "e": 3443, "s": 3277, "text": "The first four strings do not have any digits. The last three strings are phone numbers. The expression above could catch all the digits from the last three strings." }, { "code": null, "e": 3502, "s": 3443, "text": "The capital ‘D’ will catch everything else but the digits." }, { "code": null, "e": 3529, "s": 3502, "text": "str_extract_all(ch, \"\\\\D\")" }, { "code": null, "e": 3537, "s": 3529, "text": "Output:" }, { "code": null, "e": 3825, "s": 3537, "text": "[[1]][1] \"a\" \"b\" \"c\" \"d\" \"e\" \"f\" \"g\" \"h\" \"i\"[[2]][1] \"A\" \"B\" \"C\" \"D\" \"E\" \"F\" \"G\" \"H\" \"I\"[[3]] [1] \"T\" \"h\" \"i\" \"s\" \" \" \"i\" \"s\" \" \" \"m\" \"e\"[[4]] [1] \".\" \"[\" \"{\" \"(\" \"^\" \"$\" \"|\" \"?\" \"*\" \"+\"[[5]] [1] \"c\" \"o\" \"r\" \"e\" \"y\" \"m\" \"s\" \".\" \"c\" \"o\" \"m\"[[6]][1] \"-\" \"-\"[[7]][1] \".\" \".\"[[8]][1] \"*\" \"*\"" }, { "code": null, "e": 3920, "s": 3825, "text": "Look, it extracted letters, dots, and other special characters but did not extract any digits." }, { "code": null, "e": 3998, "s": 3920, "text": "‘w’ matches word characters that include a-z, A-Z, 0–9, and ‘_’. Let’s check." }, { "code": null, "e": 4025, "s": 3998, "text": "str_extract_all(ch, \"\\\\w\")" }, { "code": null, "e": 4033, "s": 4025, "text": "Output:" }, { "code": null, "e": 4375, "s": 4033, "text": "[[1]][1] \"a\" \"b\" \"c\" \"d\" \"e\" \"f\" \"g\" \"h\" \"i\"[[2]][1] \"A\" \"B\" \"C\" \"D\" \"E\" \"F\" \"G\" \"H\" \"I\"[[3]][1] \"T\" \"h\" \"i\" \"s\" \"i\" \"s\" \"m\" \"e\"[[4]]character(0)[[5]] [1] \"c\" \"o\" \"r\" \"e\" \"y\" \"m\" \"s\" \"c\" \"o\" \"m\"[[6]] [1] \"3\" \"2\" \"1\" \"5\" \"5\" \"5\" \"4\" \"3\" \"2\" \"1\"[[7]] [1] \"1\" \"2\" \"3\" \"5\" \"5\" \"5\" \"1\" \"2\" \"3\" \"4\"[[8]] [1] \"1\" \"2\" \"3\" \"5\" \"5\" \"5\" \"1\" \"2\" \"3\" \"4\"" }, { "code": null, "e": 4429, "s": 4375, "text": "It got everything except dots and special characters." }, { "code": null, "e": 4487, "s": 4429, "text": "However, ‘W’ extracts everything but the word characters." }, { "code": null, "e": 4514, "s": 4487, "text": "str_extract_all(ch, \"\\\\W\")" }, { "code": null, "e": 4522, "s": 4514, "text": "Output:" }, { "code": null, "e": 4650, "s": 4522, "text": "[[1]]character(0)[[2]]character(0)[[3]][1] \" \" \" \"[[4]] [1] \".\" \"[\" \"{\" \"(\" \"^\" \"$\" \"|\" \"?\" \"*\" \"+\"[[5]][1] \".\"[[6]][1] \"-\" \"-\"" }, { "code": null, "e": 4738, "s": 4650, "text": "I will move to show ‘b’ and ‘B’ now. ‘b’ catches the word boundary. Here is an example:" }, { "code": null, "e": 4787, "s": 4738, "text": "st = \"This is Bliss\"str_extract_all(st, \"\\\\bis\")" }, { "code": null, "e": 4795, "s": 4787, "text": "Output:" }, { "code": null, "e": 4809, "s": 4795, "text": "[[1]][1] \"is\"" }, { "code": null, "e": 4899, "s": 4809, "text": "There is only one ‘is’ in the string. So we could catch it here. Let’s see the use of ‘B’" }, { "code": null, "e": 4948, "s": 4899, "text": "st = \"This is Bliss\"str_extract_all(st, \"\\\\Bis\")" }, { "code": null, "e": 4956, "s": 4948, "text": "Output:" }, { "code": null, "e": 4975, "s": 4956, "text": "[[1]][1] \"is\" \"is\"" }, { "code": null, "e": 5128, "s": 4975, "text": "In the string ‘st’ there are two other ‘is’s that’s not in the boundary. That’s in the word ‘This’ and ‘Bliss’. When you use capital B, you catch those." }, { "code": null, "e": 5260, "s": 5128, "text": "Number 10 and 11 in the list of expression above are ‘^’ and ‘$’ which indicates the beginning and end of the strings respectively." }, { "code": null, "e": 5280, "s": 5260, "text": "Here is an example:" }, { "code": null, "e": 5350, "s": 5280, "text": "sts = c(\"This is me\", \"That my house\", \"Hello, world!\")" }, { "code": null, "e": 5403, "s": 5350, "text": "Find all the exclamation points that end a sentence." }, { "code": null, "e": 5430, "s": 5403, "text": "str_extract_all(sts, \"!$\")" }, { "code": null, "e": 5438, "s": 5430, "text": "Output:" }, { "code": null, "e": 5485, "s": 5438, "text": "[[1]]character(0)[[2]]character(0)[[3]][1] \"!\"" }, { "code": null, "e": 5622, "s": 5485, "text": "We have only one sentence that ends with an exclamation point. If R users want to find the sentence that ends with an exclamation point:" }, { "code": null, "e": 5649, "s": 5622, "text": "sts[str_detect(sts, \"!$\")]" }, { "code": null, "e": 5657, "s": 5649, "text": "Output:" }, { "code": null, "e": 5677, "s": 5657, "text": "[1] \"Hello, world!\"" }, { "code": null, "e": 5720, "s": 5677, "text": "Find the sentences that start with ‘This’." }, { "code": null, "e": 5750, "s": 5720, "text": "sts[str_detect(sts, \"^This\")]" }, { "code": null, "e": 5758, "s": 5750, "text": "Output:" }, { "code": null, "e": 5775, "s": 5758, "text": "[1] \"This is me\"" }, { "code": null, "e": 5798, "s": 5775, "text": "That is also only one." }, { "code": null, "e": 5844, "s": 5798, "text": "Let’s find the sentences that start with “T”." }, { "code": null, "e": 5871, "s": 5844, "text": "sts[str_detect(sts, \"^T\")]" }, { "code": null, "e": 5879, "s": 5871, "text": "Output:" }, { "code": null, "e": 5915, "s": 5879, "text": "[1] \"This is me\" \"That my house\"" }, { "code": null, "e": 5956, "s": 5915, "text": "‘[]’ matches characters or ranges in it." }, { "code": null, "e": 6038, "s": 5956, "text": "For this demonstration, let’s go back to ‘ch’. Extract everything in between 2–4." }, { "code": null, "e": 6067, "s": 6038, "text": "str_extract_all(ch, \"[2-4]\")" }, { "code": null, "e": 6075, "s": 6067, "text": "Output:" }, { "code": null, "e": 6228, "s": 6075, "text": "[[1]]character(0)[[2]]character(0)[[3]]character(0)[[4]]character(0)[[5]][1] \"3\" \"2\" \"4\" \"3\" \"2\"[[6]][1] \"2\" \"3\" \"2\" \"3\" \"4\"[[7]][1] \"2\" \"3\" \"2\" \"3\" \"4\"" }, { "code": null, "e": 6268, "s": 6228, "text": "Let’s move on to some bigger experiment" }, { "code": null, "e": 6363, "s": 6268, "text": "Extract the phone numbers only from ‘ch’. I will explain the pattern after you see the output:" }, { "code": null, "e": 6415, "s": 6363, "text": "str_extract(ch, \"\\\\d\\\\d\\\\d.\\\\d\\\\d\\\\d.\\\\d\\\\d\\\\d\\\\d\")" }, { "code": null, "e": 6423, "s": 6415, "text": "Output:" }, { "code": null, "e": 6538, "s": 6423, "text": "[1] NA NA NA [4] NA \"321-555-4321\" \"123.555.1234\"[7] \"123*555*1234\"" }, { "code": null, "e": 6888, "s": 6538, "text": "In the regular expression above, each ‘\\\\d’ means a digit, and ‘.’ can match anything in between (look at the number 1 in the list of expressions in the beginning). So we got the digits, then a special character in between, three more digits, then special characters again, then 4 more digits. So anything that matches these criteria were extracted." }, { "code": null, "e": 6973, "s": 6888, "text": "The regular expression for the phone number above can be written as follows as well." }, { "code": null, "e": 7013, "s": 6973, "text": "str_extract(ch, \"\\\\d{3}.\\\\d{3}.\\\\d{4}\")" }, { "code": null, "e": 7021, "s": 7013, "text": "Output:" }, { "code": null, "e": 7136, "s": 7021, "text": "[1] NA NA NA [4] NA \"321-555-4321\" \"123.555.1234\"[7] \"123*555*1234\"" }, { "code": null, "e": 7281, "s": 7136, "text": "Look at number 19 of the expression list. {x} means the exact number. Here we used {3} which means exactly 3 times. ‘\\\\d{3}’ means three digits." }, { "code": null, "e": 7616, "s": 7281, "text": "But look ‘*’ in-between digits is not a regular phone number format. Normally ‘-’ or ‘.’ may be used as a separator in phone numbers. Right? Let’s match that and exclude the phone number with ‘*’. Because that may look like a 10 digit phone number but it may not be a phone number. We want to stick to the regular phone number format." }, { "code": null, "e": 7662, "s": 7616, "text": "str_extract(ch, \"\\\\d{3}[-.]\\\\d{3}[-.]\\\\d{4}\")" }, { "code": null, "e": 7670, "s": 7662, "text": "Output:" }, { "code": null, "e": 7773, "s": 7670, "text": "[1] NA NA NA [4] NA \"321-555-4321\" \"123.555.1234\"[7] NA" }, { "code": null, "e": 7957, "s": 7773, "text": "Look, this matches only the usual phone number format. In this expression, after three digits we explicitly mentioned ‘[-.]’ which means it is asking to match only ‘-’ or a dot (‘.’)." }, { "code": null, "e": 7990, "s": 7957, "text": "Here is a list of phone numbers:" }, { "code": null, "e": 8131, "s": 7990, "text": "ph = c(\"543-325-1278\", \"900-123-7865\", \"421.235.9845\", \"453*2389*4567\", \"800-565-1112\", \"361 234 4356\" )" }, { "code": null, "e": 8208, "s": 8131, "text": "If we use the above expression on these phone numbers, this is what happens:" }, { "code": null, "e": 8254, "s": 8208, "text": "str_extract(ph, \"\\\\d{3}[-.]\\\\d{3}[-.]\\\\d{4}\")" }, { "code": null, "e": 8262, "s": 8254, "text": "Output:" }, { "code": null, "e": 8347, "s": 8262, "text": "[1] \"543-325-1278\" \"900-123-7865\" \"421.235.9845\"[4] NA \"800-565-1112\" NA" }, { "code": null, "e": 8641, "s": 8347, "text": "Look! This format excluded “361 234 4356”. Sometimes we do not use any separators in between and just use a space, right? Also, the first digit of a US phone number is not 0 or 1. It’s a number between 2–9. All the other digits can be anything between 0 and 9. Let’s take care of that pattern." }, { "code": null, "e": 8717, "s": 8641, "text": "p = \"([2-9][0-9]{2})([- .]?)([0-9]{3})([- .])?([0-9]{4})\"str_extract(ph, p)" }, { "code": null, "e": 8754, "s": 8717, "text": "I saved the pattern separately here." }, { "code": null, "e": 8854, "s": 8754, "text": "In regular expression ‘()’ is used to denote a group. Look at number 15 of the list of expressions." }, { "code": null, "e": 8902, "s": 8854, "text": "Here is the breakdown of the expressions above." }, { "code": null, "e": 8941, "s": 8902, "text": "The first group was “([2–9][0–9]{2})”:" }, { "code": null, "e": 8982, "s": 8941, "text": "‘[2–9]’ represents one digit from 2 to 9" }, { "code": null, "e": 9027, "s": 8982, "text": "‘[0–9]{2}’ represents two digits from 0 to 9" }, { "code": null, "e": 9060, "s": 9027, "text": "The second group was “([- .]?)”:" }, { "code": null, "e": 9094, "s": 9060, "text": "‘[-.]’ means it can be ‘-’ or ‘.’" }, { "code": null, "e": 9182, "s": 9094, "text": "using ‘?’ after that means ‘-’ and ‘.’ are optional. So, if it is blank that’s also ok." }, { "code": null, "e": 9233, "s": 9182, "text": "I guess the rest of the groups are also clear now." }, { "code": null, "e": 9277, "s": 9233, "text": "Here is the output of the expression above:" }, { "code": null, "e": 9374, "s": 9277, "text": "[1] \"543-325-1278\" \"900-123-7865\" \"421.235.9845\"[4] NA \"800-565-1112\" \"361 234 4356\"" }, { "code": null, "e": 9452, "s": 9374, "text": "It finds the phone number with ‘-’, ‘.’, and also with blanks as a separator." }, { "code": null, "e": 9523, "s": 9452, "text": "What if we need to find the phone number that starts with 800 and 900." }, { "code": null, "e": 9578, "s": 9523, "text": "p = \"[89]00[-.]\\\\d{3}[-.]\\\\d{4}\"str_extract_all(ph, p)" }, { "code": null, "e": 9586, "s": 9578, "text": "Output:" }, { "code": null, "e": 9701, "s": 9586, "text": "[[1]]character(0)[[2]][1] \"900-123-7865\"[[3]]character(0)[[4]]character(0)[[5]][1] \"800-565-1112\"[[6]]character(0)" }, { "code": null, "e": 9778, "s": 9701, "text": "Let’s understand the regular expression above: “[89]00[-.]\\\\d{3}[-.]\\\\d{4}”." }, { "code": null, "e": 9846, "s": 9778, "text": "The first character should be 8 or 9. That can be achieved by [89]." }, { "code": null, "e": 9913, "s": 9846, "text": "The next two elements will be zeros. We explicitly mentioned that." }, { "code": null, "e": 9960, "s": 9913, "text": "Then ‘-’ or ‘.’ which can be obtained by [-.]." }, { "code": null, "e": 9987, "s": 9960, "text": "Next three digits = \\\\d{3}" }, { "code": null, "e": 10011, "s": 9987, "text": "Again ‘-’ or ‘.’ = [-.]" }, { "code": null, "e": 10048, "s": 10011, "text": "Four more digits at the end = \\\\d{4}" }, { "code": null, "e": 10093, "s": 10048, "text": "Extract different formats of Email Addresses" }, { "code": null, "e": 10309, "s": 10093, "text": "Email addresses are a little more complicated than phone numbers. Because an email address may contain upper case letters, lower case letters, digits, special characters everything. Here is a set of email addresses:" }, { "code": null, "e": 10439, "s": 10309, "text": "email = c(\"[email protected]\", \"[email protected]\", \"[email protected]\", \"[email protected]\")" }, { "code": null, "e": 10524, "s": 10439, "text": "We will develop a regular expression that will extract all of those email addresses:" }, { "code": null, "e": 10812, "s": 10524, "text": "First work on the part before the ‘@’ symbol. This part may have lower case letters that can be detected using [a-z], upper case letters that can be detected using [A-Z], digits that can be found using [0–9], and special characters like ‘.’, and ‘_’. All of them can be packed like this:" }, { "code": null, "e": 10829, "s": 10812, "text": "“[a-zA-Z0–9-.]+”" }, { "code": null, "e": 11084, "s": 10829, "text": "The ‘+’ sign indicates one or more of those characters (look at the number 17 of the list of expressions). Because we do not know how many different letters, digits or numbers can be there. So this time we cannot use {x} the way we did for phone numbers." }, { "code": null, "e": 11230, "s": 11084, "text": "Now work on the part in-between ‘@’ and ‘.’. This part may consist of upper case letters, lower case letters, and digits that can be detected as:" }, { "code": null, "e": 11245, "s": 11230, "text": "“[a-zA_Z0–9]+”" }, { "code": null, "e": 11368, "s": 11245, "text": "Finally, the part after ‘.’. Here we have four of them ‘com’, ‘net’, ‘edu’, ‘org’. These four can be caught using a group:" }, { "code": null, "e": 11388, "s": 11368, "text": "“(com|edu|net|org”)" }, { "code": null, "e": 11496, "s": 11388, "text": "Here ‘|’ symbol is used to denote either-or. Look at number 14 of the list of expressions in the beginning." }, { "code": null, "e": 11525, "s": 11496, "text": "Here is the full expression:" }, { "code": null, "e": 11604, "s": 11525, "text": "p = \"[a-zA-Z0-9-.]+@[a-zA_Z0-9]+\\\\.(com|edu|net|org)\"str_extract_all(email, p)" }, { "code": null, "e": 11612, "s": 11604, "text": "Output:" }, { "code": null, "e": 11719, "s": 11612, "text": "[[1]][1] \"[email protected]\"[[2]][1] \"[email protected]\"[[3]][1] \"[email protected]\"[[4]][1] \"[email protected]\"" }, { "code": null, "e": 11896, "s": 11719, "text": "It will also work if you do not mention the parts after the dots. Because we added a ‘+’ sign after the second part that means it will take any number of characters after that." }, { "code": null, "e": 12032, "s": 11896, "text": "But if you need some certain domain type like ‘com’ or ‘net’, you have to explicitly mention them as we did in the previous expression." }, { "code": null, "e": 12093, "s": 12032, "text": "p = \"[a-zA-Z0-9-.]+@[a-zA_Z0-9-.]+\"str_extract_all(email, p)" }, { "code": null, "e": 12101, "s": 12093, "text": "Output:" }, { "code": null, "e": 12208, "s": 12101, "text": "[[1]][1] \"[email protected]\"[[2]][1] \"[email protected]\"[[3]][1] \"[email protected]\"[[4]][1] \"[email protected]\"" }, { "code": null, "e": 12248, "s": 12208, "text": "Another common complicated type is URLs" }, { "code": null, "e": 12272, "s": 12248, "text": "Here is a list of URLs:" }, { "code": null, "e": 12417, "s": 12272, "text": "urls = c(\"https://regenerativetoday.com\", \"http://setf.ml\", \"https://www.yahoo.com\", \"http://studio_base.net\", )" }, { "code": null, "e": 12498, "s": 12417, "text": "It may start with ‘http’ or ‘https’. To detect that this expression can be used:" }, { "code": null, "e": 12507, "s": 12498, "text": "‘https?’" }, { "code": null, "e": 12628, "s": 12507, "text": "That means ‘http’ will stay intact. Then there is a ‘?’ sign after ‘s’. So, ‘s’ is optional. It may or may not be there." }, { "code": null, "e": 12702, "s": 12628, "text": "Another optional part is after ‘://’ term: ‘www.’ We can define it using:" }, { "code": null, "e": 12714, "s": 12702, "text": "“(www\\\\.)?”" }, { "code": null, "e": 12930, "s": 12714, "text": "As we worked before, ‘()’ is used to group some expressions. Here we are grouping ‘www’ and ‘.’. After the parenthesis that ‘?’ means this whole term inside the parenthesis is optional. They may or may not be there." }, { "code": null, "e": 13139, "s": 12930, "text": "Then domain name. In this set of email addresses, we only have lower case letters and ‘_’. So, [a-z-] will work. But in a general domain name may contain upper case letters and digits as well. So we will use:" }, { "code": null, "e": 13146, "s": 13139, "text": "“\\\\w+”" }, { "code": null, "e": 13369, "s": 13146, "text": "Look at the number 4 of the list of expressions. ‘\\\\w’ denotes word character that may include lower case letters, upper case letters, and digits. The ‘+’ sign indicates that there might be one or more of those characters." }, { "code": null, "e": 13455, "s": 13369, "text": "After domain, there is one more dot and then more characters. We will get them using:" }, { "code": null, "e": 13465, "s": 13455, "text": "“\\\\.\\\\w+”" }, { "code": null, "e": 13652, "s": 13465, "text": "Remember, if you use only dot(.) to match a dot it will not work. Because only a single dot matches any character. If you have to match only a literal dot(.), you need to put it as ‘\\\\.’" }, { "code": null, "e": 13772, "s": 13652, "text": "Here we used one dot denoted by “\\\\.”, then word characters “\\\\w” and a ‘+’ sign to indicate there are more characters." }, { "code": null, "e": 13795, "s": 13772, "text": "Let’s put it together:" }, { "code": null, "e": 13855, "s": 13795, "text": "p = \"https?://(www\\\\.)?\\\\w+\\\\.\\\\w+\"str_extract_all(urls, p)" }, { "code": null, "e": 13863, "s": 13855, "text": "Output:" }, { "code": null, "e": 13994, "s": 13863, "text": "[[1]][1] \"https://regenerativetoday.com\"[[2]][1] \"http://setf.ml\"[[3]][1] \"https://www.yahoo.com\"[[4]][1] \"http://studio_base.com\"" }, { "code": null, "e": 14078, "s": 13994, "text": "You may want to get only ‘.com or ‘.net’ domains. That can be explicitly mentioned." }, { "code": null, "e": 14148, "s": 14078, "text": "p = \"https?://(www\\\\.)?(\\\\w+)(\\\\.)+(com|net)\"str_extract_all(urls, p)" }, { "code": null, "e": 14156, "s": 14148, "text": "Output:" }, { "code": null, "e": 14279, "s": 14156, "text": "[[1]][1] \"https://regenerativetoday.com\"[[2]]character(0)[[3]][1] \"https://www.yahoo.com\"[[4]][1] \"http://studio_base.com\"" }, { "code": null, "e": 14365, "s": 14279, "text": "See, it only gets ‘.com’ or ‘.net’ domains and excludes the ‘.ml’ domain that we had." }, { "code": null, "e": 14396, "s": 14365, "text": "Finally work on a set of names" }, { "code": null, "e": 14450, "s": 14396, "text": "That can be a bit tricky too. Here is a set of names:" }, { "code": null, "e": 14549, "s": 14450, "text": "name = c(\"Mr. Jon\", \"Mrs. Jon\", \"Mr Ron\", \"Ms. Reene\", \"Ms Julie\")" }, { "code": null, "e": 14749, "s": 14549, "text": "Look, it may start with Mr, Ms, or Mrs. Sometimes a dot after Mr, sometimes not. Let’s work on this part first. In all of them ‘M’ is common. Keep it intact and make a group using the rest like this:" }, { "code": null, "e": 14761, "s": 14749, "text": "“M(r|s|rs)”" }, { "code": null, "e": 14802, "s": 14761, "text": "After ‘M’ it may be ‘r’ or ‘s’, or ‘rs’." }, { "code": null, "e": 14854, "s": 14802, "text": "Then an optional dot that can be obtained by using:" }, { "code": null, "e": 14861, "s": 14854, "text": "“\\\\.?”" }, { "code": null, "e": 14911, "s": 14861, "text": "There is a space after that can be detected with:" }, { "code": null, "e": 14917, "s": 14911, "text": "“\\\\s”" }, { "code": null, "e": 14998, "s": 14917, "text": "After the space name starts with an upper case letter that can be brought using:" }, { "code": null, "e": 15005, "s": 14998, "text": "[A-Z]”" }, { "code": null, "e": 15129, "s": 15005, "text": "After that upper case letters, there are some lower case letters and we do not know exactly how many. So, we will use this:" }, { "code": null, "e": 15136, "s": 15129, "text": "“\\\\w*”" }, { "code": null, "e": 15267, "s": 15136, "text": "Look at the number 16 of the list of expressions. ‘*’ means 0 or more. So, we are saying there might be 0 or more word characters." }, { "code": null, "e": 15292, "s": 15267, "text": "Putting it all together:" }, { "code": null, "e": 15348, "s": 15292, "text": "p = \"M(r|s|rs)\\\\.?[A-Z\\\\s]\\\\w*\"str_extract_all(name, p)" }, { "code": null, "e": 15356, "s": 15348, "text": "Output:" }, { "code": null, "e": 15450, "s": 15356, "text": "[[1]][1] \"Mr. Jon\"[[2]][1] \"Mrs. Jon\"[[3]][1] \"Mr Ron\"[[4]][1] \"Ms. Reene\"[[5]][1] \"Ms Julie\"" }, { "code": null, "e": 15610, "s": 15450, "text": "Congratulation! You worked on some complicated and cool patterns that should give you enough knowledge to use a regular expression to match almost any pattern." }, { "code": null, "e": 15977, "s": 15610, "text": "This is not all. There are a lot more in the regular expression. But if you are a beginner, you should be proud of yourself that you came a long way. You should be able to match almost any pattern now. I will make another tutorial sometime later on the advanced regular expression. But you should be able to start using regular expressions now to do some cool thing." } ]
Difference Between For and Foreach in PHP
In this post, we will understand the differences between 'for' and 'foreach' loops in PHP − It is an iterative loop that repeats a set of code till a specified condition is reached. It is used to execute a set of code for a specific number of times. Here, the number of times is the iterator variable. Syntax: for( initialization; condition; increment/decrement ) { // code to iterate and execute } Initialization: It is used to initialize the iterator variables. It also helps execute them one at a time without running the conditional statement at the beginning of the loop's condition. Condition: This statement is executed and if the condition returns a True value, the loop continues and the statements within it are executed. If the condition gives a False value, the execution comes out of the loop. Increment: It increments/increases the counter in the loop. It is executed at the end of every iteration without a break. It doesn't hide the iteration. It is complex in comparison to 'foreach' loop. It takes more time to execute in comparison to 'foreach' loop. Let us see an example − <?php for($i = 1; $i <= 2; $i++) { echo $i . " Hi \n"; } ?> It iterates over the elements of the array data structure. It hides the iteration. It is simple. It performs better in comparison to 'for' loop. It takes less time for the iteration. Syntax: foreach( $array as $element ) { // PHP Code to execute } foreach( $array as $key => $element) { // PHP Code to execute } <?php $peop = array( "Will", "Jane", "Harold" ); foreach( $ peop as $element ) { echo $element . "<br>"; } ?> Will Jane Harold Conclusion In this post, we understood about the significant differences between the 'for' and 'foreach' loop in PHP.
[ { "code": null, "e": 1154, "s": 1062, "text": "In this post, we will understand the differences between 'for' and 'foreach' loops in PHP −" }, { "code": null, "e": 1364, "s": 1154, "text": "It is an iterative loop that repeats a set of code till a specified condition is reached. It is used to execute a set of code for a specific number of times. Here, the number of times is the iterator variable." }, { "code": null, "e": 1372, "s": 1364, "text": "Syntax:" }, { "code": null, "e": 1464, "s": 1372, "text": "for( initialization; condition; increment/decrement ) {\n // code to iterate and execute\n}" }, { "code": null, "e": 1654, "s": 1464, "text": "Initialization: It is used to initialize the iterator variables. It also helps execute them one at a time without running the conditional statement at the beginning of the loop's condition." }, { "code": null, "e": 1872, "s": 1654, "text": "Condition: This statement is executed and if the condition returns a True value, the loop continues and the statements within it are executed. If the condition gives a False value, the execution comes out of the loop." }, { "code": null, "e": 1994, "s": 1872, "text": "Increment: It increments/increases the counter in the loop. It is executed at the end of every iteration without a break." }, { "code": null, "e": 2025, "s": 1994, "text": "It doesn't hide the iteration." }, { "code": null, "e": 2072, "s": 2025, "text": "It is complex in comparison to 'foreach' loop." }, { "code": null, "e": 2135, "s": 2072, "text": "It takes more time to execute in comparison to 'foreach' loop." }, { "code": null, "e": 2159, "s": 2135, "text": "Let us see an example −" }, { "code": null, "e": 2222, "s": 2159, "text": "<?php\nfor($i = 1; $i <= 2; $i++) {\n echo $i . \" Hi \\n\";\n}\n?>" }, { "code": null, "e": 2281, "s": 2222, "text": "It iterates over the elements of the array data structure." }, { "code": null, "e": 2305, "s": 2281, "text": "It hides the iteration." }, { "code": null, "e": 2319, "s": 2305, "text": "It is simple." }, { "code": null, "e": 2367, "s": 2319, "text": "It performs better in comparison to 'for' loop." }, { "code": null, "e": 2405, "s": 2367, "text": "It takes less time for the iteration." }, { "code": null, "e": 2413, "s": 2405, "text": "Syntax:" }, { "code": null, "e": 2540, "s": 2413, "text": "foreach( $array as $element ) {\n // PHP Code to execute\n}\nforeach( $array as $key => $element) {\n // PHP Code to execute\n}" }, { "code": null, "e": 2653, "s": 2540, "text": "<?php\n$peop = array( \"Will\", \"Jane\", \"Harold\" );\nforeach( $ peop as $element ) {\n echo $element . \"<br>\";\n}\n?>" }, { "code": null, "e": 2670, "s": 2653, "text": "Will\nJane\nHarold" }, { "code": null, "e": 2681, "s": 2670, "text": "Conclusion" }, { "code": null, "e": 2788, "s": 2681, "text": "In this post, we understood about the significant differences between the 'for' and 'foreach' loop in PHP." } ]
Iterate over lines from multiple input streams in Python
Python’s built-in open() function opens one file in read/write mode and read/write operations on it. To perform processing on multiple files in a batch, one has to use fileinput module of Python’s standard library. This module provides a Fileinput class with functionality of iterating over files. The module also defines helper functions for the same purpose. Primary interface to this module is input() function. This function returns instance of Fileinput class. fileinput.input(files, inplace, mode) The files parameter is name of one or more files to be read one by one. Each file acts as a generator and using a for loop it can be iterated upon. Each line in the file will be printed on Python console. >>> for line in fileinput.input('data.txt'): print (line) The files parameter can be a tuple consisting of many files. Contents of files will be displayed one by one. >>> for line in fileinput.input(files=('a.txt', 'b.txt')): print (line) The Fileinput class can also be used a context manager in the with statement. >>> with fileinput.input(files=('a.txt', 'b.txt')) as f: for line in f: print (line) The fileinput module has following functions defined in it. Following statement prints each line in the file along with the line number >>> for line in fileinput.input('books.py'): print ('{}->{}'.format(fileinput.filelineno(), line)) The sample output of above code is 1->import sqlite3 2->conn = sqlite3.connect('c:/python36/books.db') 3->cursor = conn.cursor() 4->cursor.execute("SELECT * from books;") 5->print(cursor.fetchall()) Following code print each file name in folder followed by numbered lines in it. In this program glob() function is used which returns list of files in current path optionally with matching wild cards. Here glob(‘*.py’) will return list of all files with .py extension in the current folder. This list is used as files parameter to fileinput.input() function. import fileinput, glob, sys for line in fileinput.input(glob.glob("*.py")): if fileinput.isfirstline(): print (fileinput.filename(),'>') sys.stdout.write ("{}.{}".format(fileinput.filelineno(),line)) Note the use of isfirstline() function. When iteration of new file starts, this function returns true and file name as returned by fileinput.filename() function is printed first and then the lines with numbers are displayed. For example 1.py > 1.a = 10 2.b = 20 3.print ('addition=',a+b) hello.py > 1.x = 10 2.y = 20 3.z = x+y 4.print ("x+y=",z) By default, inplace = False for fileinput.input() function. If it is set to True, it makes the input file writable. Assuming that there is a ‘msg.txt’ with following text in it. Hello Python. Good morning Following code opens the file using fileinput module and modifies its contents in place. >>> for line in fileinput.input(files='msg.txt',inplace = True): line = line.replace('morning', 'evening') sys.stdout.write(line) The ‘msg.txt’ will show the changes done.
[ { "code": null, "e": 1423, "s": 1062, "text": "Python’s built-in open() function opens one file in read/write mode and read/write operations on it. To perform processing on multiple files in a batch, one has to use fileinput module of Python’s standard library. This module provides a Fileinput class with functionality of iterating over files. The module also defines helper functions for the same purpose." }, { "code": null, "e": 1528, "s": 1423, "text": "Primary interface to this module is input() function. This function returns instance of Fileinput class." }, { "code": null, "e": 1566, "s": 1528, "text": "fileinput.input(files, inplace, mode)" }, { "code": null, "e": 1771, "s": 1566, "text": "The files parameter is name of one or more files to be read one by one. Each file acts as a generator and using a for loop it can be iterated upon. Each line in the file will be printed on Python console." }, { "code": null, "e": 1829, "s": 1771, "text": ">>> for line in fileinput.input('data.txt'):\nprint (line)" }, { "code": null, "e": 1938, "s": 1829, "text": "The files parameter can be a tuple consisting of many files. Contents of files will be displayed one by one." }, { "code": null, "e": 2010, "s": 1938, "text": ">>> for line in fileinput.input(files=('a.txt', 'b.txt')):\nprint (line)" }, { "code": null, "e": 2088, "s": 2010, "text": "The Fileinput class can also be used a context manager in the with statement." }, { "code": null, "e": 2173, "s": 2088, "text": ">>> with fileinput.input(files=('a.txt', 'b.txt')) as f:\nfor line in f:\nprint (line)" }, { "code": null, "e": 2233, "s": 2173, "text": "The fileinput module has following functions defined in it." }, { "code": null, "e": 2309, "s": 2233, "text": "Following statement prints each line in the file along with the line number" }, { "code": null, "e": 2408, "s": 2309, "text": ">>> for line in fileinput.input('books.py'):\nprint ('{}->{}'.format(fileinput.filelineno(), line))" }, { "code": null, "e": 2443, "s": 2408, "text": "The sample output of above code is" }, { "code": null, "e": 2607, "s": 2443, "text": "1->import sqlite3\n2->conn = sqlite3.connect('c:/python36/books.db')\n3->cursor = conn.cursor()\n4->cursor.execute(\"SELECT * from books;\")\n5->print(cursor.fetchall())" }, { "code": null, "e": 2966, "s": 2607, "text": "Following code print each file name in folder followed by numbered lines in it. In this program glob() function is used which returns list of files in current path optionally with matching wild cards. Here glob(‘*.py’) will return list of all files with .py extension in the current folder. This list is used as files parameter to fileinput.input() function." }, { "code": null, "e": 3166, "s": 2966, "text": "import fileinput, glob, sys\nfor line in fileinput.input(glob.glob(\"*.py\")):\nif fileinput.isfirstline():\nprint (fileinput.filename(),'>')\nsys.stdout.write (\"{}.{}\".format(fileinput.filelineno(),line))" }, { "code": null, "e": 3403, "s": 3166, "text": "Note the use of isfirstline() function. When iteration of new file starts, this function returns true and file name as returned by fileinput.filename() function is printed first and then the lines with numbers are displayed. For example" }, { "code": null, "e": 3512, "s": 3403, "text": "1.py >\n1.a = 10\n2.b = 20\n3.print ('addition=',a+b)\nhello.py >\n1.x = 10\n2.y = 20\n3.z = x+y\n4.print (\"x+y=\",z)" }, { "code": null, "e": 3628, "s": 3512, "text": "By default, inplace = False for fileinput.input() function. If it is set to True, it makes the input file writable." }, { "code": null, "e": 3690, "s": 3628, "text": "Assuming that there is a ‘msg.txt’ with following text in it." }, { "code": null, "e": 3717, "s": 3690, "text": "Hello Python. Good morning" }, { "code": null, "e": 3806, "s": 3717, "text": "Following code opens the file using fileinput module and modifies its contents in place." }, { "code": null, "e": 3936, "s": 3806, "text": ">>> for line in fileinput.input(files='msg.txt',inplace = True):\nline = line.replace('morning', 'evening')\nsys.stdout.write(line)" }, { "code": null, "e": 3978, "s": 3936, "text": "The ‘msg.txt’ will show the changes done." } ]
ASP.NET Core - Action Results
In this chapter, we will discuss the Action Results. In the previous chapters, we have been using plain simple C# classes as controllers. These classes don't derive from a base class, and you can use this approach with MVC, but it is more common to derive a controller from a controller base class provided in the Microsoft.AspNet.Mvc namespace. This base class gives us access to lots of contextual information about a request, as well as methods that help us build results to send back to the client. This base class gives us access to lots of contextual information about a request, as well as methods that help us build results to send back to the client. You can send back simple strings and integers in a response. You can also send back complex objects like an object to represent a student or university or restaurant etc. and all the data associated with that object. You can send back simple strings and integers in a response. You can also send back complex objects like an object to represent a student or university or restaurant etc. and all the data associated with that object. These results are typically encapsulated into an object that implements the IActionResult interface. These results are typically encapsulated into an object that implements the IActionResult interface. There are many different result types that implement this interface — result types that can contain models or the contents of a file for download. There are many different result types that implement this interface — result types that can contain models or the contents of a file for download. These different result types can allow us to send back JSON to a client or XML or a view that builds HTML. These different result types can allow us to send back JSON to a client or XML or a view that builds HTML. Actions basically return different types of Action Results. The ActionResult class is the base for all the action results. The following is a list of different kind of action results and their behavior. Let us perform a simple example by opening the HomeController class and derive it from the controller based class. This base class is in the Microsoft.AspNet.Mvc namespace. The following is the implementation of the HomeController class. using Microsoft.AspNet.Mvc; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace FirstAppdemo.Controllers { public class HomeController : Controller { public ContentResult Index() { return Content("Hello, World! this message is from Home Controller using the Action Result"); } } } You can now see that the index method is returning the ContentResult which is one of the result types and all these result types implement ultimately an interface, which is the ActionResult. In the Index method, we have passed a string into the Content method. This Content method produces a ContentResult; this means the Index method will now return ContentResult. Let us save the HomeController class and run the application in the browser. It will produce the following page. You can now see a response which doesn’t look any different from the response we had before. It is still just going to be a plain text response. You might be wondering what is the advantage of using something that produces an ActionResult. You might be wondering what is the advantage of using something that produces an ActionResult. The typical advantage is that it is just a formal way to encapsulate the decision of the controller. The typical advantage is that it is just a formal way to encapsulate the decision of the controller. The controller decides what to do next, either return a string or HTML or return a model object that might be serialized into JSON etc. The controller decides what to do next, either return a string or HTML or return a model object that might be serialized into JSON etc. All that the controller needs to do is make that decision and the controller does not have to write directly into the response the results of its decision. All that the controller needs to do is make that decision and the controller does not have to write directly into the response the results of its decision. It just needs to return the decision and then it is the framework that will take a result and understand how to transform that result into something that can be sent back over HTTP. It just needs to return the decision and then it is the framework that will take a result and understand how to transform that result into something that can be sent back over HTTP. Let us take another example. Create a new folder in the project and call it Models. Inside the Models folder, we want to add a class that can represent an Employee. Enter Employee.cs in the Name field as in the above screenshot. Here, the implementation of the Employee class contains two properties. using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace FirstAppDemo.Models { public class Employee { public int ID { get; set; } public string Name { get; set} } } Inside the Index action method of HomeController, we want to return an Employee object. The following is the implementation of HomeController. using FirstAppDemo.Models; using Microsoft.AspNet.Mvc; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace FirstAppdemo.Controllers { public class HomeController : Controller { public ObjectResult Index() { var employee = new Employee { ID = 1, Name = "Mark Upston"}; return new ObjectResult(employee); } } } Now, instead of returning the Content, we will return a different type of result which is known as ObjectResult. If we want an ObjectResult, we need to create or instantiate an ObjectResult and pass into it some model object. An ObjectResult is special in the MVC framework because when we return an ObjectResult, the MVC framework looks at this object. This object needs to be represented in the HTTP response. An ObjectResult is special in the MVC framework because when we return an ObjectResult, the MVC framework looks at this object. This object needs to be represented in the HTTP response. This object should be serialized into XML or JSON or some other format and ultimately, the decision will be made based on the configuration information that you give to the MVC at startup. If you don't configure anything, you just get some defaults, and the default is a JSON response. This object should be serialized into XML or JSON or some other format and ultimately, the decision will be made based on the configuration information that you give to the MVC at startup. If you don't configure anything, you just get some defaults, and the default is a JSON response. Save all your files and refresh the browser. You will see the following output. 51 Lectures 5.5 hours Anadi Sharma 44 Lectures 4.5 hours Kaushik Roy Chowdhury 42 Lectures 18 hours SHIVPRASAD KOIRALA 57 Lectures 3.5 hours University Code 40 Lectures 2.5 hours University Code 138 Lectures 9 hours Bhrugen Patel Print Add Notes Bookmark this page
[ { "code": null, "e": 2807, "s": 2461, "text": "In this chapter, we will discuss the Action Results. In the previous chapters, we have been using plain simple C# classes as controllers. These classes don't derive from a base class, and you can use this approach with MVC, but it is more common to derive a controller from a controller base class provided in the Microsoft.AspNet.Mvc namespace." }, { "code": null, "e": 2964, "s": 2807, "text": "This base class gives us access to lots of contextual information about a request, as well as methods that help us build results to send back to the client." }, { "code": null, "e": 3121, "s": 2964, "text": "This base class gives us access to lots of contextual information about a request, as well as methods that help us build results to send back to the client." }, { "code": null, "e": 3338, "s": 3121, "text": "You can send back simple strings and integers in a response. You can also send back complex objects like an object to represent a student or university or restaurant etc. and all the data associated with that object." }, { "code": null, "e": 3555, "s": 3338, "text": "You can send back simple strings and integers in a response. You can also send back complex objects like an object to represent a student or university or restaurant etc. and all the data associated with that object." }, { "code": null, "e": 3656, "s": 3555, "text": "These results are typically encapsulated into an object that implements the IActionResult interface." }, { "code": null, "e": 3757, "s": 3656, "text": "These results are typically encapsulated into an object that implements the IActionResult interface." }, { "code": null, "e": 3904, "s": 3757, "text": "There are many different result types that implement this interface — result types that can contain models or the contents of a file for download." }, { "code": null, "e": 4051, "s": 3904, "text": "There are many different result types that implement this interface — result types that can contain models or the contents of a file for download." }, { "code": null, "e": 4158, "s": 4051, "text": "These different result types can allow us to send back JSON to a client or XML or a view that builds HTML." }, { "code": null, "e": 4265, "s": 4158, "text": "These different result types can allow us to send back JSON to a client or XML or a view that builds HTML." }, { "code": null, "e": 4468, "s": 4265, "text": "Actions basically return different types of Action Results. The ActionResult class is the base for all the action results. The following is a list of different kind of action results and their behavior." }, { "code": null, "e": 4706, "s": 4468, "text": "Let us perform a simple example by opening the HomeController class and derive it from the controller based class. This base class is in the Microsoft.AspNet.Mvc namespace. The following is the implementation of the HomeController class." }, { "code": null, "e": 5096, "s": 4706, "text": "using Microsoft.AspNet.Mvc; \nusing System; \nusing System.Collections.Generic; \nusing System.Linq; \nusing System.Threading.Tasks; \n\nnamespace FirstAppdemo.Controllers { \n public class HomeController : Controller { \n public ContentResult Index() { \n return Content(\"Hello, World! this message is from \n Home Controller using the Action Result\"); \n } \n } \n}" }, { "code": null, "e": 5287, "s": 5096, "text": "You can now see that the index method is returning the ContentResult which is one of the result types and all these result types implement ultimately an interface, which is the ActionResult." }, { "code": null, "e": 5462, "s": 5287, "text": "In the Index method, we have passed a string into the Content method. This Content method produces a ContentResult; this means the Index method will now return ContentResult." }, { "code": null, "e": 5575, "s": 5462, "text": "Let us save the HomeController class and run the application in the browser. It will produce the following page." }, { "code": null, "e": 5720, "s": 5575, "text": "You can now see a response which doesn’t look any different from the response we had before. It is still just going to be a plain text response." }, { "code": null, "e": 5815, "s": 5720, "text": "You might be wondering what is the advantage of using something that produces an ActionResult." }, { "code": null, "e": 5910, "s": 5815, "text": "You might be wondering what is the advantage of using something that produces an ActionResult." }, { "code": null, "e": 6011, "s": 5910, "text": "The typical advantage is that it is just a formal way to encapsulate the decision of the controller." }, { "code": null, "e": 6112, "s": 6011, "text": "The typical advantage is that it is just a formal way to encapsulate the decision of the controller." }, { "code": null, "e": 6248, "s": 6112, "text": "The controller decides what to do next, either return a string or HTML or return a model object that might be serialized into JSON etc." }, { "code": null, "e": 6384, "s": 6248, "text": "The controller decides what to do next, either return a string or HTML or return a model object that might be serialized into JSON etc." }, { "code": null, "e": 6540, "s": 6384, "text": "All that the controller needs to do is make that decision and the controller does not have to write directly into the response the results of its decision." }, { "code": null, "e": 6696, "s": 6540, "text": "All that the controller needs to do is make that decision and the controller does not have to write directly into the response the results of its decision." }, { "code": null, "e": 6878, "s": 6696, "text": "It just needs to return the decision and then it is the framework that will take a result and understand how to transform that result into something that can be sent back over HTTP." }, { "code": null, "e": 7060, "s": 6878, "text": "It just needs to return the decision and then it is the framework that will take a result and understand how to transform that result into something that can be sent back over HTTP." }, { "code": null, "e": 7225, "s": 7060, "text": "Let us take another example. Create a new folder in the project and call it Models. Inside the Models folder, we want to add a class that can represent an Employee." }, { "code": null, "e": 7361, "s": 7225, "text": "Enter Employee.cs in the Name field as in the above screenshot. Here, the implementation of the Employee class contains two properties." }, { "code": null, "e": 7606, "s": 7361, "text": "using System; \nusing System.Collections.Generic; \nusing System.Linq; \nusing System.Threading.Tasks; \n\nnamespace FirstAppDemo.Models { \n public class Employee { \n public int ID { get; set; } \n public string Name { get; set} \n } \n}" }, { "code": null, "e": 7749, "s": 7606, "text": "Inside the Index action method of HomeController, we want to return an Employee object. The following is the implementation of HomeController." }, { "code": null, "e": 8166, "s": 7749, "text": "using FirstAppDemo.Models; \nusing Microsoft.AspNet.Mvc; \n\nusing System; \nusing System.Collections.Generic; \nusing System.Linq; \nusing System.Threading.Tasks; \n\nnamespace FirstAppdemo.Controllers { \n public class HomeController : Controller { \n public ObjectResult Index() { \n var employee = new Employee { ID = 1, Name = \"Mark Upston\"}; \n return new ObjectResult(employee); \n } \n } \n} " }, { "code": null, "e": 8392, "s": 8166, "text": "Now, instead of returning the Content, we will return a different type of result which is known as ObjectResult. If we want an ObjectResult, we need to create or instantiate an ObjectResult and pass into it some model object." }, { "code": null, "e": 8578, "s": 8392, "text": "An ObjectResult is special in the MVC framework because when we return an ObjectResult, the MVC framework looks at this object. This object needs to be represented in the HTTP response." }, { "code": null, "e": 8764, "s": 8578, "text": "An ObjectResult is special in the MVC framework because when we return an ObjectResult, the MVC framework looks at this object. This object needs to be represented in the HTTP response." }, { "code": null, "e": 9050, "s": 8764, "text": "This object should be serialized into XML or JSON or some other format and ultimately, the decision will be made based on the configuration information that you give to the MVC at startup. If you don't configure anything, you just get some defaults, and the default is a JSON response." }, { "code": null, "e": 9336, "s": 9050, "text": "This object should be serialized into XML or JSON or some other format and ultimately, the decision will be made based on the configuration information that you give to the MVC at startup. If you don't configure anything, you just get some defaults, and the default is a JSON response." }, { "code": null, "e": 9416, "s": 9336, "text": "Save all your files and refresh the browser. You will see the following output." }, { "code": null, "e": 9451, "s": 9416, "text": "\n 51 Lectures \n 5.5 hours \n" }, { "code": null, "e": 9465, "s": 9451, "text": " Anadi Sharma" }, { "code": null, "e": 9500, "s": 9465, "text": "\n 44 Lectures \n 4.5 hours \n" }, { "code": null, "e": 9523, "s": 9500, "text": " Kaushik Roy Chowdhury" }, { "code": null, "e": 9557, "s": 9523, "text": "\n 42 Lectures \n 18 hours \n" }, { "code": null, "e": 9577, "s": 9557, "text": " SHIVPRASAD KOIRALA" }, { "code": null, "e": 9612, "s": 9577, "text": "\n 57 Lectures \n 3.5 hours \n" }, { "code": null, "e": 9629, "s": 9612, "text": " University Code" }, { "code": null, "e": 9664, "s": 9629, "text": "\n 40 Lectures \n 2.5 hours \n" }, { "code": null, "e": 9681, "s": 9664, "text": " University Code" }, { "code": null, "e": 9715, "s": 9681, "text": "\n 138 Lectures \n 9 hours \n" }, { "code": null, "e": 9730, "s": 9715, "text": " Bhrugen Patel" }, { "code": null, "e": 9737, "s": 9730, "text": " Print" }, { "code": null, "e": 9748, "s": 9737, "text": " Add Notes" } ]
The Most Complete Guide to PyTorch for Data Scientists | by Rahul Agarwal | Towards Data Science
PyTorch has sort of became one of the de facto standards for creating Neural Networks now, and I love its interface. Yet, it is somehow a little difficult for beginners to get a hold of. I remember picking PyTorch up only after some extensive experimentation a couple of years back. To tell you the truth, it took me a lot of time to pick it up but am I glad that I moved from Keras to PyTorch. With its high customizability and pythonic syntax, PyTorch is just a joy to work with, and I would recommend it to anyone who wants to do some heavy lifting with Deep Learning. So, in this PyTorch guide, I will try to ease some of the pain with PyTorch for starters and go through some of the most important classes and modules that you will require while creating any Neural Network with Pytorch. But, that is not to say that this is aimed at beginners only as I will also talk about the high customizability PyTorch provides and will talk about custom Layers, Datasets, Dataloaders, and Loss functions. If you would like to get the full power out of Pytorch, Exxact Corporation has a great line of AI-based workstations and servers starting at $3,700, with a couple of NVIDIA RTX 30 Series GPUs, 3-year warranty, and a deep learning software stack. So let’s get some coffee ☕ ️and start it up. Here is a Table of Contents if you want to look at a particular section. · Tensors ∘ 1. Create a Tensor ∘ 2. Tensor Operations· The nn.Module· A word about Layers· Datasets and DataLoaders ∘ Understanding Custom Datasets ∘ Understanding Custom DataLoaders· Training a Neural Network· Loss functions ∘ Custom Loss Function· Optimizers· Using GPU/Multiple GPUs· Conclusion Tensors are the basic building blocks in PyTorch and put very simply, they are NumPy arrays but on GPU. In this part, I will list down some of the most used operations we can use while working with Tensors. This is by no means an exhaustive list of operations you can do with Tensors, but it is helpful to understand what tensors are before going towards the more exciting parts. We can create a PyTorch tensor in multiple ways. This includes converting to tensor from a NumPy array. Below is just a small gist with some examples to start with, but you can do a whole lot of more things with tensors just like you can do with NumPy arrays. Again, there are a lot of operations you can do on these tensors. The full list of functions can be found here. Note: What are PyTorch Variables? In the previous versions of Pytorch, Tensor and Variables used to be different and provided different functionality, but now the Variable API is deprecated, and all methods for variables work with Tensors. So, if you don’t know about them, it’s fine as they re not needed, and if you know them, you can forget about them. Here comes the fun part as we are now going to talk about some of the most used constructs in Pytorch while creating deep learning projects. nn.Module lets you create your Deep Learning models as a class. You can inherit from nn.Moduleto define any model as a class. Every model class necessarily contains an __init__ procedure block and a block for the forward pass. In the __init__ part, the user can define all the layers the network is going to have but doesn't yet define how those layers would be connected to each other. In the forward pass block, the user defines how data flows from one layer to another inside the network. So, put simply, any network we define will look like: Here we have defined a very simple Network that takes an input of size 784 and passes it through two linear layers in a sequential manner. But the thing to note is that we can define any sort of calculation while defining the forward pass, and that makes PyTorch highly customizable for research purposes. For example, in our crazy experimentation mode, we might have used the below network where we arbitrarily attach our layers. Here we send back the output from the second linear layer back again to the first one after adding the input to it(skip connection) back again(I honestly don’t know what that will do). We can also check if the neural network forward pass works. I usually do that by first creating some random input and just passing that through the network I have created. x = torch.randn((100,784))model = myCrazyNeuralNet()model(x).size()--------------------------torch.Size([100, 10]) Pytorch is pretty powerful, and you can actually create any new experimental layer by yourself using nn.Module. For example, rather than using the predefined Linear Layer nn.Linear from Pytorch above, we could have created our custom linear layer. You can see how we wrap our weights tensor in nn.Parameter. This is done to make the tensor to be considered as a model parameter. From PyTorch docs: Parameters are Tensor subclasses, that have a very special property when used with Module - when they’re assigned as Module attributes they are automatically added to the list of its parameters, and will appear in parameters() iterator As you will later see, the model.parameters() iterator will be an input to the optimizer. But more on that later. Right now, we can now use this custom layer in any PyTorch network, just like any other layer. But then again, Pytorch would not be so widely used if it didn’t provide a lot of ready to made layers used very frequently in wide varieties of Neural Network architectures. Some examples are:nn.Linear, nn.Conv2d, nn.MaxPool2d, nn.ReLU, nn.BatchNorm2d, nn.Dropout, nn.Embedding, nn.GRU/nn.LSTM, nn.Softmax, nn.LogSoftmax, nn.MultiheadAttention, nn.TransformerEncoder, nn.TransformerDecoder I have linked all the layers to their source where you could read all about them, but to show how I usually try to understand a layer and read the docs, I would try to look at a very simple convolutional layer here. So, a Conv2d Layer needs as input an Image of height H and width W, with Cin channels. Now, for the first layer in a convnet, the number of in_channels would be 3(RGB), and the number of out_channels can be defined by the user. The kernel_size mostly used is 3x3, and the stride normally used is 1. To check a new layer which I don’t know much about, I usually try to see the input as well as output for the layer like below where I would first initialize the layer: conv_layer = nn.Conv2d(in_channels = 3, out_channels = 64, kernel_size = (3,3), stride = 1, padding=1) And then pass some random input through it. Here 100 is the batch size. x = torch.randn((100,3,24,24))conv_layer(x).size()--------------------------------torch.Size([100, 64, 24, 24]) So, we get the output from the convolution operation as required, and I have sufficient information on how to use this layer in any Neural Network I design. How would we pass data to our Neural nets while training or while testing? We can definitely pass tensors as we have done above, but Pytorch also provides us with pre-built Datasets to make it easier for us to pass data to our neural nets. You can check out the complete list of datasets provided at torchvision.datasets and torchtext.datasets. But, to give a concrete example for datasets, let’s say we had to pass images to an Image Neural net using a folder which has images in this structure: data train sailboat kayak . . We can use torchvision.datasets.ImageFolder dataset to get an example image like below: This dataset has 847 images, and we can get an image and its label using an index. Now we can pass images one by one to any image neural network using a for loop: for i in range(0,len(train_dataset)): image ,label = train_dataset[i] pred = model(image) But that is not optimal. We want to do batching. We can actually write some more code to append images and labels in a batch and then pass it to the Neural network. But Pytorch provides us with a utility iterator torch.utils.data.DataLoader to do precisely that. Now we can simply wrap our train_dataset in the Dataloader, and we will get batches instead of individual examples. train_dataloader = DataLoader(train_dataset,batch_size = 64, shuffle=True, num_workers=10) We can simply iterate with batches using: for image_batch, label_batch in train_dataloader: print(image_batch.size(),label_batch.size()) break------------------------------------------------------------------torch.Size([64, 3, 224, 224]) torch.Size([64]) So actually, the whole process of using datasets and Dataloaders becomes: You can look at this particular example in action in my previous blogpost on Image classification using Deep Learning here. This is great, and Pytorch does provide a lot of functionality out of the box. But the main power of Pytorch comes with its immense customization. We can also create our own custom datasets if the datasets provided by PyTorch don’t fit our use case. To write our custom datasets, we can make use of the abstract class torch.utils.data.Dataset provided by Pytorch. We need to inherit this Dataset class and need to define two methods to create a custom Dataset. __len__ : a function that returns the size of the dataset. This one is pretty simple to write in most cases. __getitem__: a function that takes as input an index i and returns the sample at index i. For example, we can create a simple custom dataset that returns an image and a label from a folder. See that most of the tasks are happening in __init__ part where we use glob.glob to get image names and do some general preprocessing. Also, note that we open our images one at a time in the __getitem__ method and not while initializing. This is not done in __init__ because we don't want to load all our images in the memory and just need to load the required ones. We can now use this dataset with the utility Dataloader just like before. It works just like the previous dataset provided by PyTorch but without some utility functions. This particular section is a little advanced and can be skipped going through this post as it will not be needed in a lot of situations. But I am adding it for completeness here. So let’s say you are looking to provide batches to a network that processes text input, and the network could take sequences with any sequence size as long as the size remains constant in the batch. For example, we can have a BiLSTM network that can process sequences of any length. It’s alright if you don’t understand the layers used in it right now; just know that it can process sequences with variable sizes. This network expects its input to be of shape (batch_size, seq_length) and works with any seq_length. We can check this by passing our model two random batches with different sequence lengths(10 and 25). model = BiLSTM()input_batch_1 = torch.randint(low = 0,high = 10000, size = (100,10))input_batch_2 = torch.randint(low = 0,high = 10000, size = (100,25))print(model(input_batch_1).size())print(model(input_batch_2).size())------------------------------------------------------------------torch.Size([100, 1])torch.Size([100, 1]) Now, we want to provide tight batches to this model, such that each batch has the same sequence length based on the max sequence length in the batch to minimize padding. This has an added benefit of making the neural net run faster. It was, in fact, one of the methods used in the winning submission of the Quora Insincere challenge in Kaggle, where running time was of utmost importance. So, how do we do this? Let’s write a very simple custom dataset class first. Also, let’s generate some random data which we will use with this custom Dataset. We can use the custom dataset now using: train_dataset = CustomTextDataset(X,y) If we now try to use the Dataloader on this dataset with batch_size>1, we will get an error. Why is that? train_dataloader = DataLoader(train_dataset,batch_size = 64, shuffle=False, num_workers=10)for xb,yb in train_dataloader: print(xb.size(),yb.size()) This happens because the sequences have different lengths, and our data loader expects our sequences of the same length. Remember that in the previous image example, we resized all images to size 224 using the transforms, so we didn’t face this error. So, how do we iterate through this dataset so that each batch has sequences with the same length, but different batches may have different sequence lengths? We can use collate_fn parameter in the DataLoader that lets us define how to stack sequences in a particular batch. To use this, we need to define a function that takes as input a batch and returns (x_batch, y_batch ) with padded sequence lengths based on max_sequence_length in the batch. The functions I have used in the below function are simple NumPy operations. Also, the function is properly commented so you can understand what is happening. We can now use this collate_fn with our Dataloader as: train_dataloader = DataLoader(train_dataset,batch_size = 64, shuffle=False, num_workers=10,collate_fn = collate_text)for xb,yb in train_dataloader: print(xb.size(),yb.size()) It will work this time as we have provided a custom collate_fn. And see that the batches have different sequence lengths now. Thus we would be able to train our BiLSTM using variable input sizes just like we wanted. We know how to create a neural network using nn.Module. But how to train it? Any neural network that has to be trained will have a training loop that will look something similar to below: In the above code, we are running five epochs and in each epoch: We iterate through the dataset using a data loader.In each iteration, we do a forward pass using model(x_batch)We calculate the Loss using a loss_criterionWe back-propagate that loss using loss.backward() call. We don't have to worry about the calculation of the gradients at all, as this simple call does it all for us.Take an optimizer step to change the weights in the whole network using optimizer.step(). This is where weights of the network get modified using the gradients calculated in loss.backward() call.We go through the validation data loader to check the validation score/metrics. Before doing validation, we set the model to eval mode using model.eval().Please note we don't back-propagate losses in eval mode. We iterate through the dataset using a data loader. In each iteration, we do a forward pass using model(x_batch) We calculate the Loss using a loss_criterion We back-propagate that loss using loss.backward() call. We don't have to worry about the calculation of the gradients at all, as this simple call does it all for us. Take an optimizer step to change the weights in the whole network using optimizer.step(). This is where weights of the network get modified using the gradients calculated in loss.backward() call. We go through the validation data loader to check the validation score/metrics. Before doing validation, we set the model to eval mode using model.eval().Please note we don't back-propagate losses in eval mode. Till now, we have talked about how to use nn.Module to create networks and how to use Custom Datasets and Dataloaders with Pytorch. So let's talk about the various options available for Loss Functions and Optimizers. Pytorch provides us with a variety of loss functions for our most common tasks, like Classification and Regression. Some most used examples are nn.CrossEntropyLoss , nn.NLLLoss , nn.KLDivLoss and nn.MSELoss. You can read the documentation of each loss function, but to explain how to use these loss functions, I will go through the example of nn.NLLLoss The documentation for NLLLoss is pretty succinct. As in, this loss function is used for Multiclass classification, and based on the documentation: the input expected needs to be of size (batch_size x Num_Classes ) — These are the predictions from the Neural Network we have created. We need to have the log-probabilities of each class in the input — To get log-probabilities from a Neural Network, we can add a LogSoftmax Layer as the last layer of our network. The target needs to be a tensor of classes with class numbers in the range(0, C-1) where C is the number of classes. So, we can try to use this Loss function for a simple classification network. Please note the LogSoftmax layer after the final linear layer. If you don't want to use this LogSoftmax layer, you could have just used nn.CrossEntropyLoss Let’s define a random input to pass to our network to test it: # some random input:X = torch.randn(100,784)y = torch.randint(low = 0,high = 10,size = (100,)) And pass it through the model to get predictions: model = myClassificationNet()preds = model(X) We can now get the loss as: criterion = nn.NLLLoss()loss = criterion(preds,y)loss------------------------------------------tensor(2.4852, grad_fn=<NllLossBackward>) Defining your custom loss functions is again a piece of cake, and you should be okay as long as you use tensor operations in your loss function. For example, here is the customMseLoss def customMseLoss(output,target): loss = torch.mean((output - target)**2) return loss You can use this custom loss just like before. But note that we don’t instantiate the loss using criterion this time as we have defined it as a function. output = model(x)loss = customMseLoss(output, target)loss.backward() If we wanted, we could have also written it as a class using nn.Module , and then we would have been able to use it as an object. Here is an NLLLoss custom example: Once we get gradients using the loss.backward() call, we need to take an optimizer step to change the weights in the whole network. Pytorch provides a variety of different ready to use optimizers using the torch.optim module. For example: torch.optim.Adadelta , torch.optim.Adagrad , torch.optim.RMSprop and the most widely used torch.optim.Adam. To use the most used Adam optimizer from PyTorch, we can simply instantiate it with: optimizer = torch.optim.Adam(model.parameters(), lr=0.01, betas=(0.9, 0.999)) And then use optimizer.zero_grad() and optimizer.step() while training the model. I am not discussing how to write custom optimizers as it is an infrequent use case, but if you want to have more optimizers, do check out the pytorch-optimizer library, which provides a lot of other optimizers used in research papers. Also, if you anyhow want to create your own optimizers, you can take inspiration using the source code of implemented optimizers in PyTorch or pytorch-optimizers. Till now, whatever we have done is on the CPU. If you want to use a GPU, you can put your model to GPU using model.to('cuda'). Or if you want to use multiple GPUs, you can use nn.DataParallel. Here is a utility function that checks the number of GPUs in the machine and sets up parallel training automatically using DataParallel if needed. The only thing that we will need to change is that we will load our data to GPU while training if we have GPUs. It’s as simple as adding a few lines of code to our training loop. Pytorch provides a lot of customizability with minimal code. While at first, it might be hard to understand how the whole ecosystem is structured with classes, in the end, it is simple Python. In this post, I have tried to break down most of the parts you might need while using Pytorch, and I hope it makes a little more sense for you after reading this. You can find the code for this post here on my GitHub repo, where I keep codes for all my blogs. If you want to learn more about Pytorch using a course based structure, take a look at the Deep Neural Networks with PyTorch course by IBM on Coursera. Also, if you want to know more about Deep Learning, I would like to recommend this excellent course on Deep Learning in Computer Vision in the Advanced machine learning specialization. Thanks for the read. I am going to be writing more beginner-friendly posts in the future too. Follow me up at Medium or Subscribe to my blog to be informed about them. As always, I welcome feedback and constructive criticism and can be reached on Twitter @mlwhiz Also, a small disclaimer — There might be some affiliate links in this post to relevant resources, as sharing knowledge is never a bad idea.
[ { "code": null, "e": 358, "s": 171, "text": "PyTorch has sort of became one of the de facto standards for creating Neural Networks now, and I love its interface. Yet, it is somehow a little difficult for beginners to get a hold of." }, { "code": null, "e": 743, "s": 358, "text": "I remember picking PyTorch up only after some extensive experimentation a couple of years back. To tell you the truth, it took me a lot of time to pick it up but am I glad that I moved from Keras to PyTorch. With its high customizability and pythonic syntax, PyTorch is just a joy to work with, and I would recommend it to anyone who wants to do some heavy lifting with Deep Learning." }, { "code": null, "e": 964, "s": 743, "text": "So, in this PyTorch guide, I will try to ease some of the pain with PyTorch for starters and go through some of the most important classes and modules that you will require while creating any Neural Network with Pytorch." }, { "code": null, "e": 1171, "s": 964, "text": "But, that is not to say that this is aimed at beginners only as I will also talk about the high customizability PyTorch provides and will talk about custom Layers, Datasets, Dataloaders, and Loss functions." }, { "code": null, "e": 1417, "s": 1171, "text": "If you would like to get the full power out of Pytorch, Exxact Corporation has a great line of AI-based workstations and servers starting at $3,700, with a couple of NVIDIA RTX 30 Series GPUs, 3-year warranty, and a deep learning software stack." }, { "code": null, "e": 1462, "s": 1417, "text": "So let’s get some coffee ☕ ️and start it up." }, { "code": null, "e": 1535, "s": 1462, "text": "Here is a Table of Contents if you want to look at a particular section." }, { "code": null, "e": 1833, "s": 1535, "text": "· Tensors ∘ 1. Create a Tensor ∘ 2. Tensor Operations· The nn.Module· A word about Layers· Datasets and DataLoaders ∘ Understanding Custom Datasets ∘ Understanding Custom DataLoaders· Training a Neural Network· Loss functions ∘ Custom Loss Function· Optimizers· Using GPU/Multiple GPUs· Conclusion" }, { "code": null, "e": 2213, "s": 1833, "text": "Tensors are the basic building blocks in PyTorch and put very simply, they are NumPy arrays but on GPU. In this part, I will list down some of the most used operations we can use while working with Tensors. This is by no means an exhaustive list of operations you can do with Tensors, but it is helpful to understand what tensors are before going towards the more exciting parts." }, { "code": null, "e": 2473, "s": 2213, "text": "We can create a PyTorch tensor in multiple ways. This includes converting to tensor from a NumPy array. Below is just a small gist with some examples to start with, but you can do a whole lot of more things with tensors just like you can do with NumPy arrays." }, { "code": null, "e": 2585, "s": 2473, "text": "Again, there are a lot of operations you can do on these tensors. The full list of functions can be found here." }, { "code": null, "e": 2941, "s": 2585, "text": "Note: What are PyTorch Variables? In the previous versions of Pytorch, Tensor and Variables used to be different and provided different functionality, but now the Variable API is deprecated, and all methods for variables work with Tensors. So, if you don’t know about them, it’s fine as they re not needed, and if you know them, you can forget about them." }, { "code": null, "e": 3309, "s": 2941, "text": "Here comes the fun part as we are now going to talk about some of the most used constructs in Pytorch while creating deep learning projects. nn.Module lets you create your Deep Learning models as a class. You can inherit from nn.Moduleto define any model as a class. Every model class necessarily contains an __init__ procedure block and a block for the forward pass." }, { "code": null, "e": 3469, "s": 3309, "text": "In the __init__ part, the user can define all the layers the network is going to have but doesn't yet define how those layers would be connected to each other." }, { "code": null, "e": 3574, "s": 3469, "text": "In the forward pass block, the user defines how data flows from one layer to another inside the network." }, { "code": null, "e": 3628, "s": 3574, "text": "So, put simply, any network we define will look like:" }, { "code": null, "e": 4244, "s": 3628, "text": "Here we have defined a very simple Network that takes an input of size 784 and passes it through two linear layers in a sequential manner. But the thing to note is that we can define any sort of calculation while defining the forward pass, and that makes PyTorch highly customizable for research purposes. For example, in our crazy experimentation mode, we might have used the below network where we arbitrarily attach our layers. Here we send back the output from the second linear layer back again to the first one after adding the input to it(skip connection) back again(I honestly don’t know what that will do)." }, { "code": null, "e": 4416, "s": 4244, "text": "We can also check if the neural network forward pass works. I usually do that by first creating some random input and just passing that through the network I have created." }, { "code": null, "e": 4531, "s": 4416, "text": "x = torch.randn((100,784))model = myCrazyNeuralNet()model(x).size()--------------------------torch.Size([100, 10])" }, { "code": null, "e": 4779, "s": 4531, "text": "Pytorch is pretty powerful, and you can actually create any new experimental layer by yourself using nn.Module. For example, rather than using the predefined Linear Layer nn.Linear from Pytorch above, we could have created our custom linear layer." }, { "code": null, "e": 4929, "s": 4779, "text": "You can see how we wrap our weights tensor in nn.Parameter. This is done to make the tensor to be considered as a model parameter. From PyTorch docs:" }, { "code": null, "e": 5165, "s": 4929, "text": "Parameters are Tensor subclasses, that have a very special property when used with Module - when they’re assigned as Module attributes they are automatically added to the list of its parameters, and will appear in parameters() iterator" }, { "code": null, "e": 5279, "s": 5165, "text": "As you will later see, the model.parameters() iterator will be an input to the optimizer. But more on that later." }, { "code": null, "e": 5374, "s": 5279, "text": "Right now, we can now use this custom layer in any PyTorch network, just like any other layer." }, { "code": null, "e": 5765, "s": 5374, "text": "But then again, Pytorch would not be so widely used if it didn’t provide a lot of ready to made layers used very frequently in wide varieties of Neural Network architectures. Some examples are:nn.Linear, nn.Conv2d, nn.MaxPool2d, nn.ReLU, nn.BatchNorm2d, nn.Dropout, nn.Embedding, nn.GRU/nn.LSTM, nn.Softmax, nn.LogSoftmax, nn.MultiheadAttention, nn.TransformerEncoder, nn.TransformerDecoder" }, { "code": null, "e": 5981, "s": 5765, "text": "I have linked all the layers to their source where you could read all about them, but to show how I usually try to understand a layer and read the docs, I would try to look at a very simple convolutional layer here." }, { "code": null, "e": 6280, "s": 5981, "text": "So, a Conv2d Layer needs as input an Image of height H and width W, with Cin channels. Now, for the first layer in a convnet, the number of in_channels would be 3(RGB), and the number of out_channels can be defined by the user. The kernel_size mostly used is 3x3, and the stride normally used is 1." }, { "code": null, "e": 6448, "s": 6280, "text": "To check a new layer which I don’t know much about, I usually try to see the input as well as output for the layer like below where I would first initialize the layer:" }, { "code": null, "e": 6551, "s": 6448, "text": "conv_layer = nn.Conv2d(in_channels = 3, out_channels = 64, kernel_size = (3,3), stride = 1, padding=1)" }, { "code": null, "e": 6623, "s": 6551, "text": "And then pass some random input through it. Here 100 is the batch size." }, { "code": null, "e": 6735, "s": 6623, "text": "x = torch.randn((100,3,24,24))conv_layer(x).size()--------------------------------torch.Size([100, 64, 24, 24])" }, { "code": null, "e": 6892, "s": 6735, "text": "So, we get the output from the convolution operation as required, and I have sufficient information on how to use this layer in any Neural Network I design." }, { "code": null, "e": 7389, "s": 6892, "text": "How would we pass data to our Neural nets while training or while testing? We can definitely pass tensors as we have done above, but Pytorch also provides us with pre-built Datasets to make it easier for us to pass data to our neural nets. You can check out the complete list of datasets provided at torchvision.datasets and torchtext.datasets. But, to give a concrete example for datasets, let’s say we had to pass images to an Image Neural net using a folder which has images in this structure:" }, { "code": null, "e": 7450, "s": 7389, "text": "data train sailboat kayak . ." }, { "code": null, "e": 7538, "s": 7450, "text": "We can use torchvision.datasets.ImageFolder dataset to get an example image like below:" }, { "code": null, "e": 7701, "s": 7538, "text": "This dataset has 847 images, and we can get an image and its label using an index. Now we can pass images one by one to any image neural network using a for loop:" }, { "code": null, "e": 7797, "s": 7701, "text": "for i in range(0,len(train_dataset)): image ,label = train_dataset[i] pred = model(image)" }, { "code": null, "e": 8176, "s": 7797, "text": "But that is not optimal. We want to do batching. We can actually write some more code to append images and labels in a batch and then pass it to the Neural network. But Pytorch provides us with a utility iterator torch.utils.data.DataLoader to do precisely that. Now we can simply wrap our train_dataset in the Dataloader, and we will get batches instead of individual examples." }, { "code": null, "e": 8267, "s": 8176, "text": "train_dataloader = DataLoader(train_dataset,batch_size = 64, shuffle=True, num_workers=10)" }, { "code": null, "e": 8309, "s": 8267, "text": "We can simply iterate with batches using:" }, { "code": null, "e": 8528, "s": 8309, "text": "for image_batch, label_batch in train_dataloader: print(image_batch.size(),label_batch.size()) break------------------------------------------------------------------torch.Size([64, 3, 224, 224]) torch.Size([64])" }, { "code": null, "e": 8602, "s": 8528, "text": "So actually, the whole process of using datasets and Dataloaders becomes:" }, { "code": null, "e": 8726, "s": 8602, "text": "You can look at this particular example in action in my previous blogpost on Image classification using Deep Learning here." }, { "code": null, "e": 8976, "s": 8726, "text": "This is great, and Pytorch does provide a lot of functionality out of the box. But the main power of Pytorch comes with its immense customization. We can also create our own custom datasets if the datasets provided by PyTorch don’t fit our use case." }, { "code": null, "e": 9187, "s": 8976, "text": "To write our custom datasets, we can make use of the abstract class torch.utils.data.Dataset provided by Pytorch. We need to inherit this Dataset class and need to define two methods to create a custom Dataset." }, { "code": null, "e": 9296, "s": 9187, "text": "__len__ : a function that returns the size of the dataset. This one is pretty simple to write in most cases." }, { "code": null, "e": 9386, "s": 9296, "text": "__getitem__: a function that takes as input an index i and returns the sample at index i." }, { "code": null, "e": 9621, "s": 9386, "text": "For example, we can create a simple custom dataset that returns an image and a label from a folder. See that most of the tasks are happening in __init__ part where we use glob.glob to get image names and do some general preprocessing." }, { "code": null, "e": 9853, "s": 9621, "text": "Also, note that we open our images one at a time in the __getitem__ method and not while initializing. This is not done in __init__ because we don't want to load all our images in the memory and just need to load the required ones." }, { "code": null, "e": 10023, "s": 9853, "text": "We can now use this dataset with the utility Dataloader just like before. It works just like the previous dataset provided by PyTorch but without some utility functions." }, { "code": null, "e": 10202, "s": 10023, "text": "This particular section is a little advanced and can be skipped going through this post as it will not be needed in a lot of situations. But I am adding it for completeness here." }, { "code": null, "e": 10616, "s": 10202, "text": "So let’s say you are looking to provide batches to a network that processes text input, and the network could take sequences with any sequence size as long as the size remains constant in the batch. For example, we can have a BiLSTM network that can process sequences of any length. It’s alright if you don’t understand the layers used in it right now; just know that it can process sequences with variable sizes." }, { "code": null, "e": 10820, "s": 10616, "text": "This network expects its input to be of shape (batch_size, seq_length) and works with any seq_length. We can check this by passing our model two random batches with different sequence lengths(10 and 25)." }, { "code": null, "e": 11147, "s": 10820, "text": "model = BiLSTM()input_batch_1 = torch.randint(low = 0,high = 10000, size = (100,10))input_batch_2 = torch.randint(low = 0,high = 10000, size = (100,25))print(model(input_batch_1).size())print(model(input_batch_2).size())------------------------------------------------------------------torch.Size([100, 1])torch.Size([100, 1])" }, { "code": null, "e": 11536, "s": 11147, "text": "Now, we want to provide tight batches to this model, such that each batch has the same sequence length based on the max sequence length in the batch to minimize padding. This has an added benefit of making the neural net run faster. It was, in fact, one of the methods used in the winning submission of the Quora Insincere challenge in Kaggle, where running time was of utmost importance." }, { "code": null, "e": 11613, "s": 11536, "text": "So, how do we do this? Let’s write a very simple custom dataset class first." }, { "code": null, "e": 11695, "s": 11613, "text": "Also, let’s generate some random data which we will use with this custom Dataset." }, { "code": null, "e": 11736, "s": 11695, "text": "We can use the custom dataset now using:" }, { "code": null, "e": 11775, "s": 11736, "text": "train_dataset = CustomTextDataset(X,y)" }, { "code": null, "e": 11881, "s": 11775, "text": "If we now try to use the Dataloader on this dataset with batch_size>1, we will get an error. Why is that?" }, { "code": null, "e": 12033, "s": 11881, "text": "train_dataloader = DataLoader(train_dataset,batch_size = 64, shuffle=False, num_workers=10)for xb,yb in train_dataloader: print(xb.size(),yb.size())" }, { "code": null, "e": 12285, "s": 12033, "text": "This happens because the sequences have different lengths, and our data loader expects our sequences of the same length. Remember that in the previous image example, we resized all images to size 224 using the transforms, so we didn’t face this error." }, { "code": null, "e": 12442, "s": 12285, "text": "So, how do we iterate through this dataset so that each batch has sequences with the same length, but different batches may have different sequence lengths?" }, { "code": null, "e": 12891, "s": 12442, "text": "We can use collate_fn parameter in the DataLoader that lets us define how to stack sequences in a particular batch. To use this, we need to define a function that takes as input a batch and returns (x_batch, y_batch ) with padded sequence lengths based on max_sequence_length in the batch. The functions I have used in the below function are simple NumPy operations. Also, the function is properly commented so you can understand what is happening." }, { "code": null, "e": 12946, "s": 12891, "text": "We can now use this collate_fn with our Dataloader as:" }, { "code": null, "e": 13124, "s": 12946, "text": "train_dataloader = DataLoader(train_dataset,batch_size = 64, shuffle=False, num_workers=10,collate_fn = collate_text)for xb,yb in train_dataloader: print(xb.size(),yb.size())" }, { "code": null, "e": 13340, "s": 13124, "text": "It will work this time as we have provided a custom collate_fn. And see that the batches have different sequence lengths now. Thus we would be able to train our BiLSTM using variable input sizes just like we wanted." }, { "code": null, "e": 13528, "s": 13340, "text": "We know how to create a neural network using nn.Module. But how to train it? Any neural network that has to be trained will have a training loop that will look something similar to below:" }, { "code": null, "e": 13593, "s": 13528, "text": "In the above code, we are running five epochs and in each epoch:" }, { "code": null, "e": 14319, "s": 13593, "text": "We iterate through the dataset using a data loader.In each iteration, we do a forward pass using model(x_batch)We calculate the Loss using a loss_criterionWe back-propagate that loss using loss.backward() call. We don't have to worry about the calculation of the gradients at all, as this simple call does it all for us.Take an optimizer step to change the weights in the whole network using optimizer.step(). This is where weights of the network get modified using the gradients calculated in loss.backward() call.We go through the validation data loader to check the validation score/metrics. Before doing validation, we set the model to eval mode using model.eval().Please note we don't back-propagate losses in eval mode." }, { "code": null, "e": 14371, "s": 14319, "text": "We iterate through the dataset using a data loader." }, { "code": null, "e": 14432, "s": 14371, "text": "In each iteration, we do a forward pass using model(x_batch)" }, { "code": null, "e": 14477, "s": 14432, "text": "We calculate the Loss using a loss_criterion" }, { "code": null, "e": 14643, "s": 14477, "text": "We back-propagate that loss using loss.backward() call. We don't have to worry about the calculation of the gradients at all, as this simple call does it all for us." }, { "code": null, "e": 14839, "s": 14643, "text": "Take an optimizer step to change the weights in the whole network using optimizer.step(). This is where weights of the network get modified using the gradients calculated in loss.backward() call." }, { "code": null, "e": 15050, "s": 14839, "text": "We go through the validation data loader to check the validation score/metrics. Before doing validation, we set the model to eval mode using model.eval().Please note we don't back-propagate losses in eval mode." }, { "code": null, "e": 15267, "s": 15050, "text": "Till now, we have talked about how to use nn.Module to create networks and how to use Custom Datasets and Dataloaders with Pytorch. So let's talk about the various options available for Loss Functions and Optimizers." }, { "code": null, "e": 15621, "s": 15267, "text": "Pytorch provides us with a variety of loss functions for our most common tasks, like Classification and Regression. Some most used examples are nn.CrossEntropyLoss , nn.NLLLoss , nn.KLDivLoss and nn.MSELoss. You can read the documentation of each loss function, but to explain how to use these loss functions, I will go through the example of nn.NLLLoss" }, { "code": null, "e": 15768, "s": 15621, "text": "The documentation for NLLLoss is pretty succinct. As in, this loss function is used for Multiclass classification, and based on the documentation:" }, { "code": null, "e": 15904, "s": 15768, "text": "the input expected needs to be of size (batch_size x Num_Classes ) — These are the predictions from the Neural Network we have created." }, { "code": null, "e": 16083, "s": 15904, "text": "We need to have the log-probabilities of each class in the input — To get log-probabilities from a Neural Network, we can add a LogSoftmax Layer as the last layer of our network." }, { "code": null, "e": 16200, "s": 16083, "text": "The target needs to be a tensor of classes with class numbers in the range(0, C-1) where C is the number of classes." }, { "code": null, "e": 16434, "s": 16200, "text": "So, we can try to use this Loss function for a simple classification network. Please note the LogSoftmax layer after the final linear layer. If you don't want to use this LogSoftmax layer, you could have just used nn.CrossEntropyLoss" }, { "code": null, "e": 16497, "s": 16434, "text": "Let’s define a random input to pass to our network to test it:" }, { "code": null, "e": 16592, "s": 16497, "text": "# some random input:X = torch.randn(100,784)y = torch.randint(low = 0,high = 10,size = (100,))" }, { "code": null, "e": 16642, "s": 16592, "text": "And pass it through the model to get predictions:" }, { "code": null, "e": 16688, "s": 16642, "text": "model = myClassificationNet()preds = model(X)" }, { "code": null, "e": 16716, "s": 16688, "text": "We can now get the loss as:" }, { "code": null, "e": 16853, "s": 16716, "text": "criterion = nn.NLLLoss()loss = criterion(preds,y)loss------------------------------------------tensor(2.4852, grad_fn=<NllLossBackward>)" }, { "code": null, "e": 17037, "s": 16853, "text": "Defining your custom loss functions is again a piece of cake, and you should be okay as long as you use tensor operations in your loss function. For example, here is the customMseLoss" }, { "code": null, "e": 17134, "s": 17037, "text": "def customMseLoss(output,target): loss = torch.mean((output - target)**2) return loss" }, { "code": null, "e": 17288, "s": 17134, "text": "You can use this custom loss just like before. But note that we don’t instantiate the loss using criterion this time as we have defined it as a function." }, { "code": null, "e": 17357, "s": 17288, "text": "output = model(x)loss = customMseLoss(output, target)loss.backward()" }, { "code": null, "e": 17522, "s": 17357, "text": "If we wanted, we could have also written it as a class using nn.Module , and then we would have been able to use it as an object. Here is an NLLLoss custom example:" }, { "code": null, "e": 17869, "s": 17522, "text": "Once we get gradients using the loss.backward() call, we need to take an optimizer step to change the weights in the whole network. Pytorch provides a variety of different ready to use optimizers using the torch.optim module. For example: torch.optim.Adadelta , torch.optim.Adagrad , torch.optim.RMSprop and the most widely used torch.optim.Adam." }, { "code": null, "e": 17954, "s": 17869, "text": "To use the most used Adam optimizer from PyTorch, we can simply instantiate it with:" }, { "code": null, "e": 18032, "s": 17954, "text": "optimizer = torch.optim.Adam(model.parameters(), lr=0.01, betas=(0.9, 0.999))" }, { "code": null, "e": 18114, "s": 18032, "text": "And then use optimizer.zero_grad() and optimizer.step() while training the model." }, { "code": null, "e": 18512, "s": 18114, "text": "I am not discussing how to write custom optimizers as it is an infrequent use case, but if you want to have more optimizers, do check out the pytorch-optimizer library, which provides a lot of other optimizers used in research papers. Also, if you anyhow want to create your own optimizers, you can take inspiration using the source code of implemented optimizers in PyTorch or pytorch-optimizers." }, { "code": null, "e": 18852, "s": 18512, "text": "Till now, whatever we have done is on the CPU. If you want to use a GPU, you can put your model to GPU using model.to('cuda'). Or if you want to use multiple GPUs, you can use nn.DataParallel. Here is a utility function that checks the number of GPUs in the machine and sets up parallel training automatically using DataParallel if needed." }, { "code": null, "e": 19031, "s": 18852, "text": "The only thing that we will need to change is that we will load our data to GPU while training if we have GPUs. It’s as simple as adding a few lines of code to our training loop." }, { "code": null, "e": 19387, "s": 19031, "text": "Pytorch provides a lot of customizability with minimal code. While at first, it might be hard to understand how the whole ecosystem is structured with classes, in the end, it is simple Python. In this post, I have tried to break down most of the parts you might need while using Pytorch, and I hope it makes a little more sense for you after reading this." }, { "code": null, "e": 19484, "s": 19387, "text": "You can find the code for this post here on my GitHub repo, where I keep codes for all my blogs." }, { "code": null, "e": 19821, "s": 19484, "text": "If you want to learn more about Pytorch using a course based structure, take a look at the Deep Neural Networks with PyTorch course by IBM on Coursera. Also, if you want to know more about Deep Learning, I would like to recommend this excellent course on Deep Learning in Computer Vision in the Advanced machine learning specialization." }, { "code": null, "e": 20084, "s": 19821, "text": "Thanks for the read. I am going to be writing more beginner-friendly posts in the future too. Follow me up at Medium or Subscribe to my blog to be informed about them. As always, I welcome feedback and constructive criticism and can be reached on Twitter @mlwhiz" } ]
Minimum Spanning Tree | Practice | GeeksforGeeks
Given a weighted, undirected and connected graph of V vertices and E edges. The task is to find the sum of weights of the edges of the Minimum Spanning Tree. Example 1: Input: Output: 4 Explanation: The Spanning Tree resulting in a weight of 4 is shown above. Example 2: Input: Output: 5 Explanation: Only one Spanning Tree is possible which has a weight of 5. Your task: Since this is a functional problem you don't have to worry about input, you just have to complete the function spanningTree() which takes number of vertices V and an adjacency matrix adj as input parameters and returns an integer denoting the sum of weights of the edges of the Minimum Spanning Tree. Here adj[i] contains a list of lists containing two integers where the first integer a[i][0] denotes that there is an edge between i and a[i][0] and second integer a[i][1] denotes that the distance between edge i and a[i][0] is a[i][1]. Expected Time Complexity: O(ElogV). Expected Auxiliary Space: O(V2). Constraints: 2 ≤ V ≤ 1000 V-1 ≤ E ≤ (V*(V-1))/2 1 ≤ w ≤ 1000 Graph is connected and doesn't contain self loops & multiple edges. 0 amishasahu3285 days ago struct node { public: int u, v, wt; node(int first, int second, int weight){ u = first; v = second; wt = weight; } }; class Solution { int findPar(int u, vector<int> &parent) { if(u == parent[u]) return u; // path compression return parent[u] = findPar(parent[u], parent); } void unionn(int u, int v, vector<int> &parent, vector<int> &rank) { u = findPar(u, parent); v = findPar(v, parent); if(rank[u] < rank[v]) { parent[u] = v; } else if(rank[v] < rank[u]) { parent[v] = u; } else { // attach any to any and just inc the rank of node to which attached parent[v] = u; rank[u]++; } } static bool cmp(node &a, node &b){ return a.wt < b.wt; } public: int spanningTree(int V, vector<vector<int>> adj[]) { int cost = 0; vector<int> rank(V, 0); vector<int> parent(V); vector<pair<int,int>> mstSet; for(int i = 0; i < V; i++) parent[i] = i; vector<node> edges; for(int i = 0; i < V; i++){ for(auto vec: adj[i]){ edges.push_back(node(i, vec[0], vec[1])); } } sort(edges.begin(), edges.end(), cmp); for(auto it: edges){ if(findPar(it.u,parent) != findPar(it.v,parent)){ mstSet.push_back(make_pair(it.u,it.v)); unionn(it.u, it.v, parent, rank); cost += it.wt; } } return cost; } }; 0 amishasahu3281 week ago int spanningTree(int V, vector<vector<int>> adj[]) { // code here vector<int> parent(V, -1); vector<bool> mst(V, false); vector<int> key(V, INT_MAX); key[0] = 0; parent[0] = -1; priority_queue<pair<int, int>, vector<pair<int,int>>, greater<pair<int, int>>> pq; pq.push({0,0}); // node 0 and its key value -> 0 while(!pq.empty()) { int u = pq.top().second; pq.pop(); mst[u] = true; for(auto it: adj[u]) { int v = it[0]; int wt = it[1]; if(mst[v] == false && wt < key[v]) { key[v] = wt; parent[v] = u; pq.push({key[v], v}); } } } int sum = accumulate(key.begin(), key.end(), 0LL); return sum; } 0 itsmemritu1 week ago int spanningTree(int V, vector<vector<int>> adj[]) { // code here int ans=0; priority_queue<pii,vector<pii>,greater<pii>>pq; vector<bool>visited(V,false); pq.push({0,0}); while(!pq.empty()){ int k=pq.top().second; int t=pq.top().first; pq.pop(); if(visited[k]){ continue; } ans+=t; visited[k]=true; for(auto it:adj[k]){ int weight=it[1]; int v=it[0]; if(!visited[v]){ pq.push({weight,v}); } } } return ans; } 0 sunboykenneth1 week ago class Solution { public: //Function to find sum of weights of edges of the Minimum Spanning Tree. int spanningTree(int V, vector<vector<int>> adj[]) { if (V < 2) { return 0; } vector<int> spanningTreeDistances(V, INT_MAX); vector<int> inSpanningTree(V, false); spanningTreeDistances[0] = 0; int minSpanningTreeWeight = 0; while (true) { // Find the node which is not in MST yet and with minimum distance to MST int minDist = INT_MAX, minNode = -1; for (int i = 0; i < V; i++) { if (inSpanningTree[i]) { continue; } if (spanningTreeDistances[i] < minDist) { minDist = spanningTreeDistances[i]; minNode = i; } } if (minNode == -1) { break; } minSpanningTreeWeight += minDist; inSpanningTree[minNode] = true; // Update adjNodes vector<vector<int>> &adjNodes = adj[minNode]; for (auto i = adjNodes.begin(); i != adjNodes.end(); i++) { vector<int> &curAdjNode = *i; int adjNode = curAdjNode[0]; int weight = curAdjNode[1]; if (inSpanningTree[adjNode]) { continue; } if (weight < spanningTreeDistances[adjNode]) { spanningTreeDistances[adjNode] = weight; } } } return minSpanningTreeWeight; } }; +1 mayank963k2 weeks ago class Solution { public: int spanningTree(int V, vector<vector<int>> adj[]) { vector<int> dist(V, INT_MAX); vector<bool> mstSet(V, false); vector<int> parent(V, -1); dist[0] = 0; priority_queue<pair<int,int>, vector<pair<int,int>>, greater<pair<int,int>>> pq; pq.push({0, 0}); //DIst, Src; while(!pq.empty()) { int u = pq.top().second; pq.pop(); if(mstSet[u] == true) continue; mstSet[u] = true; for(auto x:adj[u]) { int v = x[0]; int weight = x[1]; if(mstSet[v] == false && weight < dist[v]) { dist[v] = weight; parent[v] = u; pq.push({dist[v], v}); } } } return accumulate(dist.begin(), dist.end(), 0); } }; 0 19bcs13143 weeks ago class Pair implements Comparable<Pair>{ int res; int v; Pair(int i,int res){ this.v=i; this.res=res; } public int compareTo(Pair obj){ return this.res-obj.res; } } class Solution { //Function to find sum of weights of edges of the Minimum Spanning Tree. static int spanningTree(int v, ArrayList<ArrayList<ArrayList<Integer>>> adj) { // Add your code here boolean[] visit=new boolean[v]; PriorityQueue<Pair> q=new PriorityQueue<>(); q.add(new Pair(0,0)); int ans=0; while(q.size()!=0){ Pair temp=q.remove(); int u=temp.v; if(visit[u]==true){ continue; } ans+=temp.res; visit[u]=true; ArrayList<ArrayList<Integer>> l=adj.get(u); for(ArrayList<Integer> list:l){ int vertex=list.get(0); int wt=list.get(1); if(visit[vertex]==false){ q.add(new Pair(vertex,wt)); } } } return ans; } } 0 ar44429883 weeks ago // { Driver Code Starts#include<bits/stdc++.h>using namespace std; // } Driver Code Ends class Solution{public:int findpar(int u,vector<int> &parent){ if(u==parent[u]) { return u; } return parent[u]=findpar(parent[u],parent);}void unite(int u,int v,vector<int> &parent,vector<int> &rank){ u=findpar(u,parent); v=findpar(v,parent); parent[v]=u;}//Function to find sum of weights of edges of the Minimum Spanning Tree. int spanningTree(int V, vector<vector<int>> adj[]) { int cost=0; priority_queue<pair<int,pair<int,int>>,vector<pair<int,pair<int,int>>>,greater<pair<int,pair<int,int>>>> minh; vector<int> parent(V); vector<int> rank(V); for(int i=0;i<V;i++) { parent[i]=i; rank[i]=0; } for(int i=0;i<V;i++) { for(auto it:adj[i]) { minh.push({it[1],{i,it[0]}}); } } while(!minh.empty()) { int wt=minh.top().first; int u=minh.top().second.first; int v=minh.top().second.second; minh.pop(); if(findpar(u,parent)!=findpar(v,parent)) { unite(u,v,parent,rank); cost+=wt; } } return cost; }}; // { Driver Code Starts. int main(){ int t; cin >> t; while (t--) { int V, E; cin >> V >> E; vector<vector<int>> adj[V]; int i=0; while (i++<E) { int u, v, w; cin >> u >> v >> w; vector<int> t1,t2; t1.push_back(v); t1.push_back(w); adj[u].push_back(t1); t2.push_back(u); t2.push_back(w); adj[v].push_back(t2); } Solution obj; cout << obj.spanningTree(V, adj) << "\n"; } return 0;} // } Driver Code Ends +1 rohitshinde1803011 month ago class Solution{ int* parent; int* rank; public:void DSU(int n){ parent = new int[n]; rank = new int[n]; for (int i = 0; i < n; i++) { parent[i] = -1; rank[i] = 1; } } int find(int i){ if (parent[i] == -1) return i; return parent[i] = find(parent[i]); } void unite(int x, int y, int s1, int s2){ if (rank[s1] < rank[s2]) { parent[s1] = s2; rank[s2] += rank[s1]; } else{ parent[s2] = s1; rank[s1] += rank[s2]; } } //Function to find sum of weights of edges of the Minimum Spanning Tree. int spanningTree(int V, vector<vector<int>> adj[]) { // code here vector<vector<int>> edgelist; for(int i=0;i<V;i++){ for(auto j:adj[i]){ edgelist.push_back({j[1],i,j[0]}); } } sort(edgelist.begin(), edgelist.end()); DSU (V); int ans=0; for (auto edge : edgelist) { int w = edge[0]; int x = edge[1]; int y = edge[2]; int s1 = find(x); int s2 = find(y); if (s1 != s2){ unite(x,y,s1,s2); ans += w; } } return ans; }}; 0 nehamittal8561 month ago static int findMin(int weight[],boolean[] mstSet){ int min = Integer.MAX_VALUE; int min_index=-1; for(int i=0;i<mstSet.length;i++){ if(!mstSet[i] && min>weight[i]){ min = weight[i]; min_index = i; } } return min_index; } //Function to find sum of weights of edges of the Minimum Spanning Tree. static int spanningTree(int V, ArrayList<ArrayList<ArrayList<Integer>>> adj) { int[] weight = new int[V]; boolean[] mstSet = new boolean[V]; int[] parent = new int[V]; Arrays.fill(mstSet,false); for(int i=1;i<V;i++){ weight[i] = Integer.MAX_VALUE; } weight[0] = 0; parent[0] = -1; for(int i=0;i<V;i++){ int u= findMin(weight,mstSet); mstSet[u] = true; for(ArrayList<Integer> x: adj.get(u)){ if(!mstSet[x.get(0)]){ if(x.get(1)<weight[x.get(0)]){ weight[x.get(0)] = x.get(1); parent[x.get(0)] = u; } } } } int total_weight = 0; for(int i=0;i<V;i++){ total_weight+=weight[i]; } return total_weight; } 0 aaishuagarwal1 month ago int spanningTree(int v, vector<vector<int>> adj[]) { // code here vector<int>key(v,INT_MAX); vector<bool>mst(v,false); priority_queue<pii,vector<pii>,greater<pii>>pq; pq.push({0,0}); mst[0]=true; key[0]=0; while(!pq.empty()) { int u=pq.top().second; pq.pop(); mst[u]=true; for(auto p:adj[u]) { int w=p[1]; int v=p[0]; if(!mst[v]) { if(key[v]>w) { key[v]=w; pq.push({key[v],v}); } } } } int w=0; for(auto x:key) { w+=x; } return w; } 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": 396, "s": 238, "text": "Given a weighted, undirected and connected graph of V vertices and E edges. The task is to find the sum of weights of the edges of the Minimum Spanning Tree." }, { "code": null, "e": 409, "s": 398, "text": "Example 1:" }, { "code": null, "e": 503, "s": 409, "text": "Input:\n\nOutput:\n4\nExplanation:\n\nThe Spanning Tree resulting in a weight\nof 4 is shown above.\n" }, { "code": null, "e": 514, "s": 503, "text": "Example 2:" }, { "code": null, "e": 606, "s": 514, "text": "Input:\n\nOutput:\n5\nExplanation:\nOnly one Spanning Tree is possible\nwhich has a weight of 5.\n" }, { "code": null, "e": 1158, "s": 608, "text": "Your task:\nSince this is a functional problem you don't have to worry about input, you just have to complete the function spanningTree() which takes number of vertices V and an adjacency matrix adj as input parameters and returns an integer denoting the sum of weights of the edges of the Minimum Spanning Tree. Here adj[i] contains a list of lists containing two integers where the first integer a[i][0] denotes that there is an edge between i and a[i][0] and second integer a[i][1] denotes that the distance between edge i and a[i][0] is a[i][1]." }, { "code": null, "e": 1229, "s": 1158, "text": "Expected Time Complexity: O(ElogV).\nExpected Auxiliary Space: O(V2).\n " }, { "code": null, "e": 1368, "s": 1229, "text": "Constraints:\n2 ≤ V ≤ 1000\nV-1 ≤ E ≤ (V*(V-1))/2\n1 ≤ w ≤ 1000\nGraph is connected and doesn't contain self loops & multiple edges." }, { "code": null, "e": 1370, "s": 1368, "text": "0" }, { "code": null, "e": 1394, "s": 1370, "text": "amishasahu3285 days ago" }, { "code": null, "e": 3055, "s": 1394, "text": "struct node\n{\n public:\n int u, v, wt;\n node(int first, int second, int weight){\n u = first;\n v = second;\n wt = weight;\n }\n};\nclass Solution\n{\nint findPar(int u, vector<int> &parent) {\n if(u == parent[u]) return u; \n // path compression\n return parent[u] = findPar(parent[u], parent); \n }\n \n void unionn(int u, int v, vector<int> &parent, vector<int> &rank) {\n u = findPar(u, parent);\n v = findPar(v, parent);\n if(rank[u] < rank[v]) {\n \tparent[u] = v;\n }\n else if(rank[v] < rank[u]) {\n \tparent[v] = u; \n }\n else { // attach any to any and just inc the rank of node to which attached\n \tparent[v] = u;\n \trank[u]++; \n }\n }\n static bool cmp(node &a, node &b){\n return a.wt < b.wt;\n }\n public:\n int spanningTree(int V, vector<vector<int>> adj[])\n {\n int cost = 0;\n vector<int> rank(V, 0);\n vector<int> parent(V);\n vector<pair<int,int>> mstSet;\n for(int i = 0; i < V; i++)\n parent[i] = i;\n \n \n vector<node> edges;\n for(int i = 0; i < V; i++){\n for(auto vec: adj[i]){\n edges.push_back(node(i, vec[0], vec[1]));\n }\n }\n \n \n sort(edges.begin(), edges.end(), cmp);\n \n for(auto it: edges){\n if(findPar(it.u,parent) != findPar(it.v,parent)){\n mstSet.push_back(make_pair(it.u,it.v));\n unionn(it.u, it.v, parent, rank);\n cost += it.wt;\n }\n }\n return cost;\n }\n};" }, { "code": null, "e": 3057, "s": 3055, "text": "0" }, { "code": null, "e": 3081, "s": 3057, "text": "amishasahu3281 week ago" }, { "code": null, "e": 4053, "s": 3081, "text": "int spanningTree(int V, vector<vector<int>> adj[])\n {\n // code here\n vector<int> parent(V, -1);\n vector<bool> mst(V, false);\n vector<int> key(V, INT_MAX);\n \n key[0] = 0;\n parent[0] = -1;\n \n priority_queue<pair<int, int>, vector<pair<int,int>>, greater<pair<int, int>>> pq;\n pq.push({0,0}); // node 0 and its key value -> 0\n \n \n while(!pq.empty())\n {\n int u = pq.top().second;\n pq.pop();\n \n mst[u] = true;\n for(auto it: adj[u])\n {\n int v = it[0];\n int wt = it[1];\n if(mst[v] == false && wt < key[v])\n {\n key[v] = wt;\n parent[v] = u;\n pq.push({key[v], v});\n }\n }\n }\n \n int sum = accumulate(key.begin(), key.end(), 0LL);\n return sum;\n }" }, { "code": null, "e": 4055, "s": 4053, "text": "0" }, { "code": null, "e": 4076, "s": 4055, "text": "itsmemritu1 week ago" }, { "code": null, "e": 4704, "s": 4076, "text": " int spanningTree(int V, vector<vector<int>> adj[]) { // code here int ans=0; priority_queue<pii,vector<pii>,greater<pii>>pq; vector<bool>visited(V,false); pq.push({0,0}); while(!pq.empty()){ int k=pq.top().second; int t=pq.top().first; pq.pop(); if(visited[k]){ continue; } ans+=t; visited[k]=true; for(auto it:adj[k]){ int weight=it[1]; int v=it[0]; if(!visited[v]){ pq.push({weight,v}); } } } return ans; }" }, { "code": null, "e": 4706, "s": 4704, "text": "0" }, { "code": null, "e": 4730, "s": 4706, "text": "sunboykenneth1 week ago" }, { "code": null, "e": 6471, "s": 4730, "text": "class Solution\n{\n\tpublic:\n\t//Function to find sum of weights of edges of the Minimum Spanning Tree.\n int spanningTree(int V, vector<vector<int>> adj[])\n {\n if (V < 2) {\n return 0;\n }\n \n vector<int> spanningTreeDistances(V, INT_MAX);\n vector<int> inSpanningTree(V, false);\n spanningTreeDistances[0] = 0;\n int minSpanningTreeWeight = 0;\n \n while (true) {\n // Find the node which is not in MST yet and with minimum distance to MST\n int minDist = INT_MAX, minNode = -1;\n for (int i = 0; i < V; i++) {\n if (inSpanningTree[i]) {\n continue;\n }\n \n if (spanningTreeDistances[i] < minDist) {\n minDist = spanningTreeDistances[i];\n minNode = i;\n }\n }\n \n if (minNode == -1) {\n break;\n }\n \n minSpanningTreeWeight += minDist;\n inSpanningTree[minNode] = true;\n \n // Update adjNodes\n vector<vector<int>> &adjNodes = adj[minNode];\n for (auto i = adjNodes.begin(); i != adjNodes.end(); i++) {\n vector<int> &curAdjNode = *i;\n int adjNode = curAdjNode[0];\n int weight = curAdjNode[1];\n \n if (inSpanningTree[adjNode]) {\n continue;\n }\n \n if (weight < spanningTreeDistances[adjNode]) {\n spanningTreeDistances[adjNode] = weight;\n }\n }\n }\n \n return minSpanningTreeWeight;\n }\n};" }, { "code": null, "e": 6474, "s": 6471, "text": "+1" }, { "code": null, "e": 6496, "s": 6474, "text": "mayank963k2 weeks ago" }, { "code": null, "e": 7518, "s": 6496, "text": "class Solution\n{\n\tpublic:\n int spanningTree(int V, vector<vector<int>> adj[])\n { \n vector<int> dist(V, INT_MAX);\n vector<bool> mstSet(V, false);\n vector<int> parent(V, -1);\n \n dist[0] = 0;\n \n priority_queue<pair<int,int>, vector<pair<int,int>>, greater<pair<int,int>>> pq;\n pq.push({0, 0}); //DIst, Src;\n \n while(!pq.empty())\n {\n int u = pq.top().second;\n pq.pop();\n \n if(mstSet[u] == true) continue;\n mstSet[u] = true;\n \n for(auto x:adj[u])\n {\n int v = x[0];\n int weight = x[1];\n \n if(mstSet[v] == false && weight < dist[v])\n { \n dist[v] = weight;\n parent[v] = u;\n pq.push({dist[v], v});\n }\n }\n }\n \n return accumulate(dist.begin(), dist.end(), 0);\n \n }\n};" }, { "code": null, "e": 7520, "s": 7518, "text": "0" }, { "code": null, "e": 7541, "s": 7520, "text": "19bcs13143 weeks ago" }, { "code": null, "e": 8698, "s": 7541, "text": "class Pair implements Comparable<Pair>{\n int res;\n int v;\n Pair(int i,int res){\n this.v=i;\n this.res=res;\n }\n public int compareTo(Pair obj){\n return this.res-obj.res;\n }\n}\n\n\nclass Solution\n{\n //Function to find sum of weights of edges of the Minimum Spanning Tree.\n static int spanningTree(int v, ArrayList<ArrayList<ArrayList<Integer>>> adj) \n {\n // Add your code here\n boolean[] visit=new boolean[v];\n PriorityQueue<Pair> q=new PriorityQueue<>();\n q.add(new Pair(0,0));\n int ans=0;\n while(q.size()!=0){\n Pair temp=q.remove();\n \n int u=temp.v;\n if(visit[u]==true){\n continue;\n }\n ans+=temp.res;\n visit[u]=true;\n \n ArrayList<ArrayList<Integer>> l=adj.get(u);\n \n for(ArrayList<Integer> list:l){\n int vertex=list.get(0);\n int wt=list.get(1);\n if(visit[vertex]==false){\n q.add(new Pair(vertex,wt));\n }\n }\n }\n return ans;\n }\n}" }, { "code": null, "e": 8700, "s": 8698, "text": "0" }, { "code": null, "e": 8721, "s": 8700, "text": "ar44429883 weeks ago" }, { "code": null, "e": 8788, "s": 8721, "text": "// { Driver Code Starts#include<bits/stdc++.h>using namespace std;" }, { "code": null, "e": 8810, "s": 8788, "text": "// } Driver Code Ends" }, { "code": null, "e": 9994, "s": 8810, "text": "class Solution{public:int findpar(int u,vector<int> &parent){ if(u==parent[u]) { return u; } return parent[u]=findpar(parent[u],parent);}void unite(int u,int v,vector<int> &parent,vector<int> &rank){ u=findpar(u,parent); v=findpar(v,parent); parent[v]=u;}//Function to find sum of weights of edges of the Minimum Spanning Tree. int spanningTree(int V, vector<vector<int>> adj[]) { int cost=0; priority_queue<pair<int,pair<int,int>>,vector<pair<int,pair<int,int>>>,greater<pair<int,pair<int,int>>>> minh; vector<int> parent(V); vector<int> rank(V); for(int i=0;i<V;i++) { parent[i]=i; rank[i]=0; } for(int i=0;i<V;i++) { for(auto it:adj[i]) { minh.push({it[1],{i,it[0]}}); } } while(!minh.empty()) { int wt=minh.top().first; int u=minh.top().second.first; int v=minh.top().second.second; minh.pop(); if(findpar(u,parent)!=findpar(v,parent)) { unite(u,v,parent,rank); cost+=wt; } } return cost; }};" }, { "code": null, "e": 10019, "s": 9994, "text": "// { Driver Code Starts." }, { "code": null, "e": 10514, "s": 10019, "text": "int main(){ int t; cin >> t; while (t--) { int V, E; cin >> V >> E; vector<vector<int>> adj[V]; int i=0; while (i++<E) { int u, v, w; cin >> u >> v >> w; vector<int> t1,t2; t1.push_back(v); t1.push_back(w); adj[u].push_back(t1); t2.push_back(u); t2.push_back(w); adj[v].push_back(t2); } Solution obj; cout << obj.spanningTree(V, adj) << \"\\n\"; }" }, { "code": null, "e": 10528, "s": 10514, "text": " return 0;}" }, { "code": null, "e": 10551, "s": 10528, "text": " // } Driver Code Ends" }, { "code": null, "e": 10554, "s": 10551, "text": "+1" }, { "code": null, "e": 10583, "s": 10554, "text": "rohitshinde1803011 month ago" }, { "code": null, "e": 10627, "s": 10583, "text": "class Solution{ int* parent; int* rank;" }, { "code": null, "e": 11146, "s": 10627, "text": "public:void DSU(int n){ parent = new int[n]; rank = new int[n]; for (int i = 0; i < n; i++) { parent[i] = -1; rank[i] = 1; } } int find(int i){ if (parent[i] == -1) return i; return parent[i] = find(parent[i]); } void unite(int x, int y, int s1, int s2){ if (rank[s1] < rank[s2]) { parent[s1] = s2; rank[s2] += rank[s1]; } else{ parent[s2] = s1; rank[s1] += rank[s2]; } }" }, { "code": null, "e": 11835, "s": 11146, "text": " //Function to find sum of weights of edges of the Minimum Spanning Tree. int spanningTree(int V, vector<vector<int>> adj[]) { // code here vector<vector<int>> edgelist; for(int i=0;i<V;i++){ for(auto j:adj[i]){ edgelist.push_back({j[1],i,j[0]}); } } sort(edgelist.begin(), edgelist.end()); DSU (V); int ans=0; for (auto edge : edgelist) { int w = edge[0]; int x = edge[1]; int y = edge[2]; int s1 = find(x); int s2 = find(y); if (s1 != s2){ unite(x,y,s1,s2); ans += w; } } return ans; }};" }, { "code": null, "e": 11839, "s": 11837, "text": "0" }, { "code": null, "e": 11864, "s": 11839, "text": "nehamittal8561 month ago" }, { "code": null, "e": 13107, "s": 11864, "text": "static int findMin(int weight[],boolean[] mstSet){ int min = Integer.MAX_VALUE; int min_index=-1; for(int i=0;i<mstSet.length;i++){ if(!mstSet[i] && min>weight[i]){ min = weight[i]; min_index = i; } } return min_index; } //Function to find sum of weights of edges of the Minimum Spanning Tree. static int spanningTree(int V, ArrayList<ArrayList<ArrayList<Integer>>> adj) { int[] weight = new int[V]; boolean[] mstSet = new boolean[V]; int[] parent = new int[V]; Arrays.fill(mstSet,false); for(int i=1;i<V;i++){ weight[i] = Integer.MAX_VALUE; } weight[0] = 0; parent[0] = -1; for(int i=0;i<V;i++){ int u= findMin(weight,mstSet); mstSet[u] = true; for(ArrayList<Integer> x: adj.get(u)){ if(!mstSet[x.get(0)]){ if(x.get(1)<weight[x.get(0)]){ weight[x.get(0)] = x.get(1); parent[x.get(0)] = u; } } } } int total_weight = 0; for(int i=0;i<V;i++){ total_weight+=weight[i]; } return total_weight; }" }, { "code": null, "e": 13109, "s": 13107, "text": "0" }, { "code": null, "e": 13134, "s": 13109, "text": "aaishuagarwal1 month ago" }, { "code": null, "e": 13899, "s": 13134, "text": "int spanningTree(int v, vector<vector<int>> adj[]) { // code here vector<int>key(v,INT_MAX); vector<bool>mst(v,false); priority_queue<pii,vector<pii>,greater<pii>>pq; pq.push({0,0}); mst[0]=true; key[0]=0; while(!pq.empty()) { int u=pq.top().second; pq.pop(); mst[u]=true; for(auto p:adj[u]) { int w=p[1]; int v=p[0]; if(!mst[v]) { if(key[v]>w) { key[v]=w; pq.push({key[v],v}); } } } } int w=0; for(auto x:key) { w+=x; } return w; }" }, { "code": null, "e": 14045, "s": 13899, "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": 14081, "s": 14045, "text": " Login to access your submissions. " }, { "code": null, "e": 14091, "s": 14081, "text": "\nProblem\n" }, { "code": null, "e": 14101, "s": 14091, "text": "\nContest\n" }, { "code": null, "e": 14164, "s": 14101, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 14312, "s": 14164, "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": 14520, "s": 14312, "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": 14626, "s": 14520, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Draw Cube and Cuboid in Python using Turtle
22 Jun, 2020 Prerequisite: Turtle Programming Basics Turtle is an inbuilt module in Python. It provides drawing using a screen (cardboard) and turtle (pen). To draw something on the screen, we need to move the turtle (pen). To move the turtle, there are some functions i.e forward(), backward(), etc. Following steps are used: First draw the front square Move to back square through one bottom left side Draw the back square Draw the remaining side as shown in code. Below is the implementation. Python3 #import the turtle modules import turtle # Forming the window screentut = turtle.Screen() # background color greentut.bgcolor("green") # window title Turtletut.title("Turtle")my_pen = turtle.Turtle() # object colormy_pen.color("orange")tut = turtle.Screen() # forming front square facefor i in range(4): my_pen.forward(100) my_pen.left(90) # bottom left sidemy_pen.goto(50,50) # forming back square facefor i in range(4): my_pen.forward(100) my_pen.left(90) # bottom right sidemy_pen.goto(150,50)my_pen.goto(100,0) # top right sidemy_pen.goto(100,100)my_pen.goto(150,150) # top left sidemy_pen.goto(50,150)my_pen.goto(0,100) Output : Following steps are used: First draw the front rectangle Move to back rectangle through one bottom left side Draw the back rectangle Draw the remaining side as shown in code. Below is the implementation. Python3 #import the turtle modules import turtle # Forming the window screentut = turtle.Screen() # background color greentut.bgcolor("green") # window title Turtletut.title("Turtle")my_pen = turtle.Turtle() # object colormy_pen.color("orange")tut=turtle.Screen() # forming front rectangle facefor i in range(2): my_pen.forward(100) my_pen.left(90) my_pen.forward(150) my_pen.left(90) # bottom left sidemy_pen.goto(50,50) # forming back rectangle facefor i in range(2): my_pen.forward(100) my_pen.left(90) my_pen.forward(150) my_pen.left(90) # bottom right sidemy_pen.goto(150,50)my_pen.goto(100,0) # top right sidemy_pen.goto(100,150)my_pen.goto(150,200) # top left sidemy_pen.goto(50,200)my_pen.goto(0,150) Output : Python-turtle Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n22 Jun, 2020" }, { "code": null, "e": 92, "s": 52, "text": "Prerequisite: Turtle Programming Basics" }, { "code": null, "e": 340, "s": 92, "text": "Turtle is an inbuilt module in Python. It provides drawing using a screen (cardboard) and turtle (pen). To draw something on the screen, we need to move the turtle (pen). To move the turtle, there are some functions i.e forward(), backward(), etc." }, { "code": null, "e": 366, "s": 340, "text": "Following steps are used:" }, { "code": null, "e": 394, "s": 366, "text": "First draw the front square" }, { "code": null, "e": 443, "s": 394, "text": "Move to back square through one bottom left side" }, { "code": null, "e": 464, "s": 443, "text": "Draw the back square" }, { "code": null, "e": 506, "s": 464, "text": "Draw the remaining side as shown in code." }, { "code": null, "e": 535, "s": 506, "text": "Below is the implementation." }, { "code": null, "e": 543, "s": 535, "text": "Python3" }, { "code": "#import the turtle modules import turtle # Forming the window screentut = turtle.Screen() # background color greentut.bgcolor(\"green\") # window title Turtletut.title(\"Turtle\")my_pen = turtle.Turtle() # object colormy_pen.color(\"orange\")tut = turtle.Screen() # forming front square facefor i in range(4): my_pen.forward(100) my_pen.left(90) # bottom left sidemy_pen.goto(50,50) # forming back square facefor i in range(4): my_pen.forward(100) my_pen.left(90) # bottom right sidemy_pen.goto(150,50)my_pen.goto(100,0) # top right sidemy_pen.goto(100,100)my_pen.goto(150,150) # top left sidemy_pen.goto(50,150)my_pen.goto(0,100)", "e": 1202, "s": 543, "text": null }, { "code": null, "e": 1211, "s": 1202, "text": "Output :" }, { "code": null, "e": 1237, "s": 1211, "text": "Following steps are used:" }, { "code": null, "e": 1268, "s": 1237, "text": "First draw the front rectangle" }, { "code": null, "e": 1320, "s": 1268, "text": "Move to back rectangle through one bottom left side" }, { "code": null, "e": 1344, "s": 1320, "text": "Draw the back rectangle" }, { "code": null, "e": 1386, "s": 1344, "text": "Draw the remaining side as shown in code." }, { "code": null, "e": 1415, "s": 1386, "text": "Below is the implementation." }, { "code": null, "e": 1423, "s": 1415, "text": "Python3" }, { "code": "#import the turtle modules import turtle # Forming the window screentut = turtle.Screen() # background color greentut.bgcolor(\"green\") # window title Turtletut.title(\"Turtle\")my_pen = turtle.Turtle() # object colormy_pen.color(\"orange\")tut=turtle.Screen() # forming front rectangle facefor i in range(2): my_pen.forward(100) my_pen.left(90) my_pen.forward(150) my_pen.left(90) # bottom left sidemy_pen.goto(50,50) # forming back rectangle facefor i in range(2): my_pen.forward(100) my_pen.left(90) my_pen.forward(150) my_pen.left(90) # bottom right sidemy_pen.goto(150,50)my_pen.goto(100,0) # top right sidemy_pen.goto(100,150)my_pen.goto(150,200) # top left sidemy_pen.goto(50,200)my_pen.goto(0,150)", "e": 2170, "s": 1423, "text": null }, { "code": null, "e": 2179, "s": 2170, "text": "Output :" }, { "code": null, "e": 2193, "s": 2179, "text": "Python-turtle" }, { "code": null, "e": 2200, "s": 2193, "text": "Python" } ]
What are the differences between HTTP module and Express.js module ?
05 Jul, 2022 HTTP and Express both are used in NodeJS for development. In this article, we’ll go through HTTP and express modules separately HTTP: It is an in-build module which is pre-installed along with NodeJS. It is used to create server and set up connections. Using this connection, data sending and receiving can be done as long as connections use a hypertext transfer protocol. Example: Creating a server using the HTTP module in NodeJS. index.js // Importing http module var http = require('http'); // Create a server object which listens on port 300http.createServer(function (req, res) { // Write a response to the client res.write('Hello World!'); // End the response res.end();}).listen(3000); Run the index.js file using the following command. node index.js Output: Express: Express as a whole is known as a framework, not just as a module. It gives you an API, submodules, functions, and methodology and conventions for quickly and easily typing together all the components necessary to put up a modern, functional web server with all the conveniences necessary for that (static asset hosting, templating, handling CSRF, CORS, cookie parsing, POST data handling, and many more functionalities. Module Installation: You can install the express module using the following command. npm i express Example: Creating a server using the express module in NodeJS. index.js // Importing expressconst express = require('express'); // Creating instance of expressconst app = express(); // Handling GET / Requestapp.get('/', function (req, res) { res.send("Hello World!, I am server created by expresss");}) // Listening to server at port 3000app.listen(3000, function () { console.log("server started");}) Run the index.js file using the following command. node index.js Output: Difference between HTTP module and Express.js module: HTTP Express venkatp30p Express.js http NodeJS-Questions Picked Difference Between Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Difference Between Method Overloading and Method Overriding in Java Similarities and Difference between Java and C++ Difference between Internal and External fragmentation Difference between MANET and VANET How to update Node.js and NPM to next version ? Installation of Node.js on Linux Node.js fs.readFileSync() Method How to install the previous version of node.js and npm ? Node.js fs.writeFile() Method
[ { "code": null, "e": 28, "s": 0, "text": "\n05 Jul, 2022" }, { "code": null, "e": 156, "s": 28, "text": "HTTP and Express both are used in NodeJS for development. In this article, we’ll go through HTTP and express modules separately" }, { "code": null, "e": 401, "s": 156, "text": "HTTP: It is an in-build module which is pre-installed along with NodeJS. It is used to create server and set up connections. Using this connection, data sending and receiving can be done as long as connections use a hypertext transfer protocol." }, { "code": null, "e": 461, "s": 401, "text": "Example: Creating a server using the HTTP module in NodeJS." }, { "code": null, "e": 470, "s": 461, "text": "index.js" }, { "code": "// Importing http module var http = require('http'); // Create a server object which listens on port 300http.createServer(function (req, res) { // Write a response to the client res.write('Hello World!'); // End the response res.end();}).listen(3000);", "e": 737, "s": 470, "text": null }, { "code": null, "e": 790, "s": 739, "text": "Run the index.js file using the following command." }, { "code": null, "e": 804, "s": 790, "text": "node index.js" }, { "code": null, "e": 812, "s": 804, "text": "Output:" }, { "code": null, "e": 1241, "s": 812, "text": "Express: Express as a whole is known as a framework, not just as a module. It gives you an API, submodules, functions, and methodology and conventions for quickly and easily typing together all the components necessary to put up a modern, functional web server with all the conveniences necessary for that (static asset hosting, templating, handling CSRF, CORS, cookie parsing, POST data handling, and many more functionalities." }, { "code": null, "e": 1326, "s": 1241, "text": "Module Installation: You can install the express module using the following command." }, { "code": null, "e": 1340, "s": 1326, "text": "npm i express" }, { "code": null, "e": 1403, "s": 1340, "text": "Example: Creating a server using the express module in NodeJS." }, { "code": null, "e": 1412, "s": 1403, "text": "index.js" }, { "code": "// Importing expressconst express = require('express'); // Creating instance of expressconst app = express(); // Handling GET / Requestapp.get('/', function (req, res) { res.send(\"Hello World!, I am server created by expresss\");}) // Listening to server at port 3000app.listen(3000, function () { console.log(\"server started\");})", "e": 1751, "s": 1412, "text": null }, { "code": null, "e": 1802, "s": 1751, "text": "Run the index.js file using the following command." }, { "code": null, "e": 1816, "s": 1802, "text": "node index.js" }, { "code": null, "e": 1824, "s": 1816, "text": "Output:" }, { "code": null, "e": 1878, "s": 1824, "text": "Difference between HTTP module and Express.js module:" }, { "code": null, "e": 1883, "s": 1878, "text": "HTTP" }, { "code": null, "e": 1891, "s": 1883, "text": "Express" }, { "code": null, "e": 1902, "s": 1891, "text": "venkatp30p" }, { "code": null, "e": 1913, "s": 1902, "text": "Express.js" }, { "code": null, "e": 1918, "s": 1913, "text": "http" }, { "code": null, "e": 1935, "s": 1918, "text": "NodeJS-Questions" }, { "code": null, "e": 1942, "s": 1935, "text": "Picked" }, { "code": null, "e": 1961, "s": 1942, "text": "Difference Between" }, { "code": null, "e": 1969, "s": 1961, "text": "Node.js" }, { "code": null, "e": 1986, "s": 1969, "text": "Web Technologies" }, { "code": null, "e": 2084, "s": 1986, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2145, "s": 2084, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2213, "s": 2145, "text": "Difference Between Method Overloading and Method Overriding in Java" }, { "code": null, "e": 2262, "s": 2213, "text": "Similarities and Difference between Java and C++" }, { "code": null, "e": 2317, "s": 2262, "text": "Difference between Internal and External fragmentation" }, { "code": null, "e": 2352, "s": 2317, "text": "Difference between MANET and VANET" }, { "code": null, "e": 2400, "s": 2352, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 2433, "s": 2400, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2466, "s": 2433, "text": "Node.js fs.readFileSync() Method" }, { "code": null, "e": 2523, "s": 2466, "text": "How to install the previous version of node.js and npm ?" } ]
Iterative Method to find Height of Binary Tree
21 Jun, 2022 There are two conventions to define the height of a Binary Tree Number of nodes on the longest path from the root to the deepest node. Number of edges on the longest path from the root to the deepest node. Number of nodes on the longest path from the root to the deepest node. Number of edges on the longest path from the root to the deepest node. In this post, the first convention is followed. For example, the height of the below tree is 3. Chapters descriptions off, selected captions settings, opens captions settings dialog captions off, selected English This is a modal window. Beginning of dialog window. Escape will cancel and close the window. End of dialog window. The recursive method to find the height of the Binary Tree is discussed here. How to find height without recursion? We can use level order traversal to find height without recursion. The idea is to traverse level by level. Whenever move down to a level, increment height by 1 (height is initialized as 0). Count number of nodes at each level, stop traversing when the count of nodes at the next level is 0. Following is a detailed algorithm to find level order traversal using a queue. Create a queue. Push root into the queue. height = 0 nodeCount = 0 // Number of nodes in the current level. // If the number of nodes in the queue is 0, it implies // that all the levels of the tree have been parsed. So, // return the height. Otherwise count the number of nodes // in the current level and push the children of all the // nodes in the current level to the queue. Loop nodeCount = size of queue // If the number of nodes at this level is 0, return height if nodeCount is 0 return Height; else increase Height // Remove nodes of this level and add nodes of // next level while (nodeCount > 0) push its children to queue pop node from front decrease nodeCount // At this point, queue has nodes of next level Following is the implementation of the above algorithm. C++ Java Python3 C# Javascript #include <iostream>#include <queue> using namespace std; // This approach counts the number of nodes from root to the// leaf to calculate the height of the tree. // Defining the structure of a Node. class Node {public: int data; Node* left; Node* right;}; // Helper function to create a newnode.// Input: Data for the newnode.// Return: Address of the newly created node. Node* createNode(int data){ Node* newnode = new Node(); newnode->data = data; newnode->left = NULL; newnode->right = NULL; return newnode;} // Function to calculate the height of given Binary Tree.// Input: Address of the root node of Binary Tree.// Return: Height of Binary Tree as a integer. This includes// the number of nodes from root to the leaf. int calculateHeight(Node* root){ queue<Node*> nodesInLevel; int height = 0; int nodeCount = 0; // Calculate number of nodes in a level. Node* currentNode; // Pointer to store the address of a // node in the current level. if (root == NULL) { return 0; } nodesInLevel.push(root); while (!nodesInLevel.empty()) { // This while loop runs for every level and // increases the height by 1 in each iteration. If // the queue is empty then it implies that the last // level of tree has been parsed. height++; // Create another while loop which will insert all // the child nodes of the current level in the // queue. nodeCount = nodesInLevel.size(); while (nodeCount--) { currentNode = nodesInLevel.front(); // Check if the current nodes has left child and // insert it in the queue. if (currentNode->left != NULL) { nodesInLevel.push(currentNode->left); } // Check if the current nodes has right child // and insert it in the queue. if (currentNode->right != NULL) { nodesInLevel.push(currentNode->right); } // Once the children of the current node are // inserted. Delete the current node. nodesInLevel.pop(); } } return height;} // Driver Function. int main(){ // Creating a binary tree. Node* root = NULL; root = createNode(1); root->left = createNode(2); root->left->left = createNode(4); root->left->right = createNode(5); root->right = createNode(3); cout << "The height of the binary tree using iterative " "method is: " << calculateHeight(root) << "."; return 0;} // An iterative java program to find height of binary tree import java.util.LinkedList;import java.util.Queue; // A binary tree nodeclass Node{ int data; Node left, right; Node(int item) { data = item; left = right; }} class BinaryTree{ Node root; // Iterative method to find height of Binary Tree int treeHeight(Node node) { // Base Case if (node == null) return 0; // Create an empty queue for level order traversal Queue<Node> q = new LinkedList(); // Enqueue Root and initialize height q.add(node); int height = 0; while (1 == 1) { // nodeCount (queue size) indicates number of nodes // at current level. int nodeCount = q.size(); if (nodeCount == 0) return height; height++; // Dequeue all nodes of current level and Enqueue all // nodes of next level while (nodeCount > 0) { Node newnode = q.peek(); q.remove(); if (newnode.left != null) q.add(newnode.left); if (newnode.right != null) q.add(newnode.right); nodeCount--; } } } // Driver program to test above functions public static void main(String args[]) { BinaryTree tree = new BinaryTree(); // Let us create a binary tree shown in above diagram tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); System.out.println("Height of tree is " + tree.treeHeight(tree.root)); }} // This code has been contributed by Mayank Jaiswal # Program to find height of tree by Iteration Method # A binary tree nodeclass Node: # Constructor to create new node def __init__(self, data): self.data = data self.left = None self.right = None # Iterative method to find height of Binary Treedef treeHeight(root): # Base Case if root is None: return 0 # Create a empty queue for level order traversal q = [] # Enqueue Root and Initialize Height q.append(root) height = 0 while(True): # nodeCount(queue size) indicates number of nodes # at current level nodeCount = len(q) if nodeCount == 0 : return height height += 1 # Dequeue all nodes of current level and Enqueue # all nodes of next level while(nodeCount > 0): node = q[0] q.pop(0) if node.left is not None: q.append(node.left) if node.right is not None: q.append(node.right) nodeCount -= 1 # Driver program to test above function# Let us create binary tree shown in above diagramroot = Node(1)root.left = Node(2)root.right = Node(3)root.left.left = Node(4)root.left.right = Node(5) print ("Height of tree is", treeHeight(root)) # This code is contributed by Nikhil Kumar Singh(nickzuck_007) // An iterative C# program to// find height of binary treeusing System;using System.Collections.Generic; // A binary tree nodeclass Node{ public int data; public Node left, right; public Node(int item) { data = item; left = right; }} public class BinaryTree{ Node root; // Iterative method to find // height of Binary Tree int treeHeight(Node node) { // Base Case if (node == null) return 0; // Create an empty queue // for level order traversal Queue<Node> q = new Queue<Node>(); // Enqueue Root and initialize height q.Enqueue(node); int height = 0; while (1 == 1) { // nodeCount (queue size) indicates // number of nodes at current level. int nodeCount = q.Count; if (nodeCount == 0) return height; height++; // Dequeue all nodes of current // level and Enqueue all // nodes of next level while (nodeCount > 0) { Node newnode = q.Peek(); q.Dequeue(); if (newnode.left != null) q.Enqueue(newnode.left); if (newnode.right != null) q.Enqueue(newnode.right); nodeCount--; } } } // Driver code public static void Main(String []args) { BinaryTree tree = new BinaryTree(); // Let us create a binary // tree shown in above diagram tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); Console.WriteLine("Height of tree is " + tree.treeHeight(tree.root)); }} // This code has been contributed by 29AjayKumar <script>// An iterative javascript program to find height of binary tree // A binary tree nodeclass Node{ constructor(item) { this.data = item; this.left = this.right=null; }} let root; // Iterative method to find height of Binary Treefunction treeHeight(node){ // Base Case if (node == null) return 0; // Create an empty queue for level order traversal let q = []; // Enqueue Root and initialize height q.push(node); let height = 0; while (1 == 1) { // nodeCount (queue size) indicates number of nodes // at current level. let nodeCount = q.length; if (nodeCount == 0) return height; height++; // Dequeue all nodes of current level and Enqueue all // nodes of next level while (nodeCount > 0) { let newnode = q.shift(); if (newnode.left != null) q.push(newnode.left); if (newnode.right != null) q.push(newnode.right); nodeCount--; } }} // Driver program to test above functions// Let us create a binary tree shown in above diagramroot = new Node(1);root.left = new Node(2);root.right = new Node(3);root.left.left = new Node(4);root.left.right = new Node(5);document.write("Height of tree is " + treeHeight(root)); // This code is contributed by rag2127</script> The height of the binary tree using iterative method is: 3. Time Complexity: O(n) where n is the number of nodes in a given binary tree.Space Complexity: O(n) where n is the number of nodes in a given binary tree. 29AjayKumar Akanksha_Rai CoderSaty rag2127 anikakapoor geekybhaalo surindertarika1234 simmytarika5 prateektiger58 amartyaghoshgfg hardikkoriintern Queue Tree Queue Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n21 Jun, 2022" }, { "code": null, "e": 117, "s": 52, "text": "There are two conventions to define the height of a Binary Tree " }, { "code": null, "e": 259, "s": 117, "text": "Number of nodes on the longest path from the root to the deepest node. Number of edges on the longest path from the root to the deepest node." }, { "code": null, "e": 331, "s": 259, "text": "Number of nodes on the longest path from the root to the deepest node. " }, { "code": null, "e": 402, "s": 331, "text": "Number of edges on the longest path from the root to the deepest node." }, { "code": null, "e": 499, "s": 402, "text": "In this post, the first convention is followed. For example, the height of the below tree is 3. " }, { "code": null, "e": 508, "s": 499, "text": "Chapters" }, { "code": null, "e": 535, "s": 508, "text": "descriptions off, selected" }, { "code": null, "e": 585, "s": 535, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 608, "s": 585, "text": "captions off, selected" }, { "code": null, "e": 616, "s": 608, "text": "English" }, { "code": null, "e": 640, "s": 616, "text": "This is a modal window." }, { "code": null, "e": 709, "s": 640, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 731, "s": 709, "text": "End of dialog window." }, { "code": null, "e": 1139, "s": 731, "text": "The recursive method to find the height of the Binary Tree is discussed here. How to find height without recursion? We can use level order traversal to find height without recursion. The idea is to traverse level by level. Whenever move down to a level, increment height by 1 (height is initialized as 0). Count number of nodes at each level, stop traversing when the count of nodes at the next level is 0. " }, { "code": null, "e": 1220, "s": 1139, "text": "Following is a detailed algorithm to find level order traversal using a queue. " }, { "code": null, "e": 2044, "s": 1220, "text": "Create a queue.\nPush root into the queue.\nheight = 0\nnodeCount = 0 // Number of nodes in the current level.\n\n// If the number of nodes in the queue is 0, it implies \n// that all the levels of the tree have been parsed. So, \n// return the height. Otherwise count the number of nodes \n// in the current level and push the children of all the \n// nodes in the current level to the queue. \n\nLoop\n nodeCount = size of queue\n \n // If the number of nodes at this level is 0, return height\n \n if nodeCount is 0\n return Height;\n else\n increase Height\n\n // Remove nodes of this level and add nodes of \n // next level\n while (nodeCount > 0)\n push its children to queue\n pop node from front\n decrease nodeCount\n // At this point, queue has nodes of next level" }, { "code": null, "e": 2102, "s": 2044, "text": "Following is the implementation of the above algorithm. " }, { "code": null, "e": 2106, "s": 2102, "text": "C++" }, { "code": null, "e": 2111, "s": 2106, "text": "Java" }, { "code": null, "e": 2119, "s": 2111, "text": "Python3" }, { "code": null, "e": 2122, "s": 2119, "text": "C#" }, { "code": null, "e": 2133, "s": 2122, "text": "Javascript" }, { "code": "#include <iostream>#include <queue> using namespace std; // This approach counts the number of nodes from root to the// leaf to calculate the height of the tree. // Defining the structure of a Node. class Node {public: int data; Node* left; Node* right;}; // Helper function to create a newnode.// Input: Data for the newnode.// Return: Address of the newly created node. Node* createNode(int data){ Node* newnode = new Node(); newnode->data = data; newnode->left = NULL; newnode->right = NULL; return newnode;} // Function to calculate the height of given Binary Tree.// Input: Address of the root node of Binary Tree.// Return: Height of Binary Tree as a integer. This includes// the number of nodes from root to the leaf. int calculateHeight(Node* root){ queue<Node*> nodesInLevel; int height = 0; int nodeCount = 0; // Calculate number of nodes in a level. Node* currentNode; // Pointer to store the address of a // node in the current level. if (root == NULL) { return 0; } nodesInLevel.push(root); while (!nodesInLevel.empty()) { // This while loop runs for every level and // increases the height by 1 in each iteration. If // the queue is empty then it implies that the last // level of tree has been parsed. height++; // Create another while loop which will insert all // the child nodes of the current level in the // queue. nodeCount = nodesInLevel.size(); while (nodeCount--) { currentNode = nodesInLevel.front(); // Check if the current nodes has left child and // insert it in the queue. if (currentNode->left != NULL) { nodesInLevel.push(currentNode->left); } // Check if the current nodes has right child // and insert it in the queue. if (currentNode->right != NULL) { nodesInLevel.push(currentNode->right); } // Once the children of the current node are // inserted. Delete the current node. nodesInLevel.pop(); } } return height;} // Driver Function. int main(){ // Creating a binary tree. Node* root = NULL; root = createNode(1); root->left = createNode(2); root->left->left = createNode(4); root->left->right = createNode(5); root->right = createNode(3); cout << \"The height of the binary tree using iterative \" \"method is: \" << calculateHeight(root) << \".\"; return 0;}", "e": 4697, "s": 2133, "text": null }, { "code": "// An iterative java program to find height of binary tree import java.util.LinkedList;import java.util.Queue; // A binary tree nodeclass Node{ int data; Node left, right; Node(int item) { data = item; left = right; }} class BinaryTree{ Node root; // Iterative method to find height of Binary Tree int treeHeight(Node node) { // Base Case if (node == null) return 0; // Create an empty queue for level order traversal Queue<Node> q = new LinkedList(); // Enqueue Root and initialize height q.add(node); int height = 0; while (1 == 1) { // nodeCount (queue size) indicates number of nodes // at current level. int nodeCount = q.size(); if (nodeCount == 0) return height; height++; // Dequeue all nodes of current level and Enqueue all // nodes of next level while (nodeCount > 0) { Node newnode = q.peek(); q.remove(); if (newnode.left != null) q.add(newnode.left); if (newnode.right != null) q.add(newnode.right); nodeCount--; } } } // Driver program to test above functions public static void main(String args[]) { BinaryTree tree = new BinaryTree(); // Let us create a binary tree shown in above diagram tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); System.out.println(\"Height of tree is \" + tree.treeHeight(tree.root)); }} // This code has been contributed by Mayank Jaiswal", "e": 6544, "s": 4697, "text": null }, { "code": "# Program to find height of tree by Iteration Method # A binary tree nodeclass Node: # Constructor to create new node def __init__(self, data): self.data = data self.left = None self.right = None # Iterative method to find height of Binary Treedef treeHeight(root): # Base Case if root is None: return 0 # Create a empty queue for level order traversal q = [] # Enqueue Root and Initialize Height q.append(root) height = 0 while(True): # nodeCount(queue size) indicates number of nodes # at current level nodeCount = len(q) if nodeCount == 0 : return height height += 1 # Dequeue all nodes of current level and Enqueue # all nodes of next level while(nodeCount > 0): node = q[0] q.pop(0) if node.left is not None: q.append(node.left) if node.right is not None: q.append(node.right) nodeCount -= 1 # Driver program to test above function# Let us create binary tree shown in above diagramroot = Node(1)root.left = Node(2)root.right = Node(3)root.left.left = Node(4)root.left.right = Node(5) print (\"Height of tree is\", treeHeight(root)) # This code is contributed by Nikhil Kumar Singh(nickzuck_007)", "e": 7890, "s": 6544, "text": null }, { "code": "// An iterative C# program to// find height of binary treeusing System;using System.Collections.Generic; // A binary tree nodeclass Node{ public int data; public Node left, right; public Node(int item) { data = item; left = right; }} public class BinaryTree{ Node root; // Iterative method to find // height of Binary Tree int treeHeight(Node node) { // Base Case if (node == null) return 0; // Create an empty queue // for level order traversal Queue<Node> q = new Queue<Node>(); // Enqueue Root and initialize height q.Enqueue(node); int height = 0; while (1 == 1) { // nodeCount (queue size) indicates // number of nodes at current level. int nodeCount = q.Count; if (nodeCount == 0) return height; height++; // Dequeue all nodes of current // level and Enqueue all // nodes of next level while (nodeCount > 0) { Node newnode = q.Peek(); q.Dequeue(); if (newnode.left != null) q.Enqueue(newnode.left); if (newnode.right != null) q.Enqueue(newnode.right); nodeCount--; } } } // Driver code public static void Main(String []args) { BinaryTree tree = new BinaryTree(); // Let us create a binary // tree shown in above diagram tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); Console.WriteLine(\"Height of tree is \" + tree.treeHeight(tree.root)); }} // This code has been contributed by 29AjayKumar", "e": 9793, "s": 7890, "text": null }, { "code": "<script>// An iterative javascript program to find height of binary tree // A binary tree nodeclass Node{ constructor(item) { this.data = item; this.left = this.right=null; }} let root; // Iterative method to find height of Binary Treefunction treeHeight(node){ // Base Case if (node == null) return 0; // Create an empty queue for level order traversal let q = []; // Enqueue Root and initialize height q.push(node); let height = 0; while (1 == 1) { // nodeCount (queue size) indicates number of nodes // at current level. let nodeCount = q.length; if (nodeCount == 0) return height; height++; // Dequeue all nodes of current level and Enqueue all // nodes of next level while (nodeCount > 0) { let newnode = q.shift(); if (newnode.left != null) q.push(newnode.left); if (newnode.right != null) q.push(newnode.right); nodeCount--; } }} // Driver program to test above functions// Let us create a binary tree shown in above diagramroot = new Node(1);root.left = new Node(2);root.right = new Node(3);root.left.left = new Node(4);root.left.right = new Node(5);document.write(\"Height of tree is \" + treeHeight(root)); // This code is contributed by rag2127</script>", "e": 11292, "s": 9793, "text": null }, { "code": null, "e": 11352, "s": 11292, "text": "The height of the binary tree using iterative method is: 3." }, { "code": null, "e": 11506, "s": 11352, "text": "Time Complexity: O(n) where n is the number of nodes in a given binary tree.Space Complexity: O(n) where n is the number of nodes in a given binary tree." }, { "code": null, "e": 11518, "s": 11506, "text": "29AjayKumar" }, { "code": null, "e": 11531, "s": 11518, "text": "Akanksha_Rai" }, { "code": null, "e": 11541, "s": 11531, "text": "CoderSaty" }, { "code": null, "e": 11549, "s": 11541, "text": "rag2127" }, { "code": null, "e": 11561, "s": 11549, "text": "anikakapoor" }, { "code": null, "e": 11573, "s": 11561, "text": "geekybhaalo" }, { "code": null, "e": 11592, "s": 11573, "text": "surindertarika1234" }, { "code": null, "e": 11605, "s": 11592, "text": "simmytarika5" }, { "code": null, "e": 11620, "s": 11605, "text": "prateektiger58" }, { "code": null, "e": 11636, "s": 11620, "text": "amartyaghoshgfg" }, { "code": null, "e": 11653, "s": 11636, "text": "hardikkoriintern" }, { "code": null, "e": 11659, "s": 11653, "text": "Queue" }, { "code": null, "e": 11664, "s": 11659, "text": "Tree" }, { "code": null, "e": 11670, "s": 11664, "text": "Queue" }, { "code": null, "e": 11675, "s": 11670, "text": "Tree" } ]
Conversion of J-K Flip-Flop into T Flip-Flop
17 Jun, 2022 Prerequisite – Flip-flop 1. J-K Flip-Flop: JK flip-flop shares the initials of Jack Kilby, who won a Nobel prize for his fabrication of the world’s first integrated circuit, some people speculate that this type of flip flop was named after him because a flip-flop was the first device that Kilby build when he was developing integrated circuits. J-K flip-flop is the gated version of SR flip-flop with an addition of extra input i.e. clock input. It prevents invalid output conditions when both the inputs are at the same value. 2. T Flip-Flop: T flip-flop means Toggle flip-flop. It changes the output on each clock edge and gives an output that is half the frequency of the signal to the input. Step-1: Construct the characteristic table of T flip-flop and excitation table of the J-K flip-flop. Step-2: Using the K map, find the boolean expression for J and K in terms of T. J = T K = T Step-3: Construct the circuit diagram for the conversion of the J-K flip-flop into a T flip-flop. dishaagrawal1 Digital Electronics & Logic Design 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": "\n17 Jun, 2022" }, { "code": null, "e": 80, "s": 54, "text": "Prerequisite – Flip-flop " }, { "code": null, "e": 586, "s": 80, "text": "1. J-K Flip-Flop: JK flip-flop shares the initials of Jack Kilby, who won a Nobel prize for his fabrication of the world’s first integrated circuit, some people speculate that this type of flip flop was named after him because a flip-flop was the first device that Kilby build when he was developing integrated circuits. J-K flip-flop is the gated version of SR flip-flop with an addition of extra input i.e. clock input. It prevents invalid output conditions when both the inputs are at the same value. " }, { "code": null, "e": 755, "s": 586, "text": "2. T Flip-Flop: T flip-flop means Toggle flip-flop. It changes the output on each clock edge and gives an output that is half the frequency of the signal to the input. " }, { "code": null, "e": 857, "s": 755, "text": "Step-1: Construct the characteristic table of T flip-flop and excitation table of the J-K flip-flop. " }, { "code": null, "e": 938, "s": 857, "text": "Step-2: Using the K map, find the boolean expression for J and K in terms of T. " }, { "code": null, "e": 951, "s": 938, "text": "J = T\nK = T " }, { "code": null, "e": 1050, "s": 951, "text": "Step-3: Construct the circuit diagram for the conversion of the J-K flip-flop into a T flip-flop. " }, { "code": null, "e": 1064, "s": 1050, "text": "dishaagrawal1" }, { "code": null, "e": 1099, "s": 1064, "text": "Digital Electronics & Logic Design" }, { "code": null, "e": 1107, "s": 1099, "text": "GATE CS" } ]
goto statement in C/C++
26 Aug, 2019 The goto statement is a jump statement which is sometimes also referred to as unconditional jump statement. The goto statement can be used to jump from anywhere to anywhere within a function.Syntax: Syntax1 | Syntax2 ---------------------------- goto label; | label: . | . . | . . | . label: | goto label; In the above syntax, the first line tells the compiler to go to or jump to the statement marked as a label. Here label is a user-defined identifier which indicates the target statement. The statement immediately followed after ‘label:’ is the destination statement. The ‘label:’ can also appear before the ‘goto label;’ statement in the above syntax.Below are some examples on how to use goto statement:Examples: Type 1: In this case, we will see a situation similar to as shown in Syntax1 above. Suppose we need to write a program where we need to check if a number is even or not and print accordingly using the goto statement. Below program explains how to do this:CC++C// C program to check if a number is// even or not using goto statement#include <stdio.h> // function to check even or notvoid checkEvenOrNot(int num){ if (num % 2 == 0) // jump to even goto even; else // jump to odd goto odd; even: printf("%d is even", num); // return if even return; odd: printf("%d is odd", num);} int main() { int num = 26; checkEvenOrNot(num); return 0;}C++// C++ program to check if a number is// even or not using goto statement#include <iostream>using namespace std; // function to check even or notvoid checkEvenOrNot(int num){ if (num % 2 == 0) // jump to even goto even; else // jump to odd goto odd; even: cout << num << " is even"; // return if even return; odd: cout << num << " is odd";} // Driver program to test above functionint main(){ int num = 26; checkEvenOrNot(num); return 0;}Output:26 is even C C++ // C program to check if a number is// even or not using goto statement#include <stdio.h> // function to check even or notvoid checkEvenOrNot(int num){ if (num % 2 == 0) // jump to even goto even; else // jump to odd goto odd; even: printf("%d is even", num); // return if even return; odd: printf("%d is odd", num);} int main() { int num = 26; checkEvenOrNot(num); return 0;} // C++ program to check if a number is// even or not using goto statement#include <iostream>using namespace std; // function to check even or notvoid checkEvenOrNot(int num){ if (num % 2 == 0) // jump to even goto even; else // jump to odd goto odd; even: cout << num << " is even"; // return if even return; odd: cout << num << " is odd";} // Driver program to test above functionint main(){ int num = 26; checkEvenOrNot(num); return 0;} 26 is even Type 2:: In this case, we will see a situation similar to as shown in Syntax1 above. Suppose we need to write a program which prints numbers from 1 to 10 using the goto statement. Below program explains how to do this.CC++C// C program to print numbers// from 1 to 10 using goto statement#include <stdio.h> // function to print numbers from 1 to 10void printNumbers(){ int n = 1;label: printf("%d ",n); n++; if (n <= 10) goto label;} // Driver program to test above functionint main() { printNumbers(); return 0;}C++// C++ program to print numbers// from 1 to 10 using goto statement#include <iostream>using namespace std; // function to print numbers from 1 to 10void printNumbers(){ int n = 1;label: cout << n << " "; n++; if (n <= 10) goto label;} // Driver program to test above functionint main(){ printNumbers(); return 0;}Output:1 2 3 4 5 6 7 8 9 10 C C++ // C program to print numbers// from 1 to 10 using goto statement#include <stdio.h> // function to print numbers from 1 to 10void printNumbers(){ int n = 1;label: printf("%d ",n); n++; if (n <= 10) goto label;} // Driver program to test above functionint main() { printNumbers(); return 0;} // C++ program to print numbers// from 1 to 10 using goto statement#include <iostream>using namespace std; // function to print numbers from 1 to 10void printNumbers(){ int n = 1;label: cout << n << " "; n++; if (n <= 10) goto label;} // Driver program to test above functionint main(){ printNumbers(); return 0;} 1 2 3 4 5 6 7 8 9 10 Disadvantages of using goto statement: The use of goto statement is highly discouraged as it makes the program logic very complex. use of goto makes the task of analyzing and verifying the correctness of programs (particularly those involving loops) very difficult. Use of goto can be simply avoided using break and continue statements. This article is contributed by Harsh Agarwal. 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. SonalSrivastava02 C Language C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n26 Aug, 2019" }, { "code": null, "e": 251, "s": 52, "text": "The goto statement is a jump statement which is sometimes also referred to as unconditional jump statement. The goto statement can be used to jump from anywhere to anywhere within a function.Syntax:" }, { "code": null, "e": 423, "s": 251, "text": "Syntax1 | Syntax2\n----------------------------\ngoto label; | label: \n. | .\n. | .\n. | .\nlabel: | goto label;\n" }, { "code": null, "e": 836, "s": 423, "text": "In the above syntax, the first line tells the compiler to go to or jump to the statement marked as a label. Here label is a user-defined identifier which indicates the target statement. The statement immediately followed after ‘label:’ is the destination statement. The ‘label:’ can also appear before the ‘goto label;’ statement in the above syntax.Below are some examples on how to use goto statement:Examples:" }, { "code": null, "e": 2044, "s": 836, "text": "Type 1: In this case, we will see a situation similar to as shown in Syntax1 above. Suppose we need to write a program where we need to check if a number is even or not and print accordingly using the goto statement. Below program explains how to do this:CC++C// C program to check if a number is// even or not using goto statement#include <stdio.h> // function to check even or notvoid checkEvenOrNot(int num){ if (num % 2 == 0) // jump to even goto even; else // jump to odd goto odd; even: printf(\"%d is even\", num); // return if even return; odd: printf(\"%d is odd\", num);} int main() { int num = 26; checkEvenOrNot(num); return 0;}C++// C++ program to check if a number is// even or not using goto statement#include <iostream>using namespace std; // function to check even or notvoid checkEvenOrNot(int num){ if (num % 2 == 0) // jump to even goto even; else // jump to odd goto odd; even: cout << num << \" is even\"; // return if even return; odd: cout << num << \" is odd\";} // Driver program to test above functionint main(){ int num = 26; checkEvenOrNot(num); return 0;}Output:26 is even\n" }, { "code": null, "e": 2046, "s": 2044, "text": "C" }, { "code": null, "e": 2050, "s": 2046, "text": "C++" }, { "code": "// C program to check if a number is// even or not using goto statement#include <stdio.h> // function to check even or notvoid checkEvenOrNot(int num){ if (num % 2 == 0) // jump to even goto even; else // jump to odd goto odd; even: printf(\"%d is even\", num); // return if even return; odd: printf(\"%d is odd\", num);} int main() { int num = 26; checkEvenOrNot(num); return 0;}", "e": 2487, "s": 2050, "text": null }, { "code": "// C++ program to check if a number is// even or not using goto statement#include <iostream>using namespace std; // function to check even or notvoid checkEvenOrNot(int num){ if (num % 2 == 0) // jump to even goto even; else // jump to odd goto odd; even: cout << num << \" is even\"; // return if even return; odd: cout << num << \" is odd\";} // Driver program to test above functionint main(){ int num = 26; checkEvenOrNot(num); return 0;}", "e": 2978, "s": 2487, "text": null }, { "code": null, "e": 2990, "s": 2978, "text": "26 is even\n" }, { "code": null, "e": 3902, "s": 2990, "text": "Type 2:: In this case, we will see a situation similar to as shown in Syntax1 above. Suppose we need to write a program which prints numbers from 1 to 10 using the goto statement. Below program explains how to do this.CC++C// C program to print numbers// from 1 to 10 using goto statement#include <stdio.h> // function to print numbers from 1 to 10void printNumbers(){ int n = 1;label: printf(\"%d \",n); n++; if (n <= 10) goto label;} // Driver program to test above functionint main() { printNumbers(); return 0;}C++// C++ program to print numbers// from 1 to 10 using goto statement#include <iostream>using namespace std; // function to print numbers from 1 to 10void printNumbers(){ int n = 1;label: cout << n << \" \"; n++; if (n <= 10) goto label;} // Driver program to test above functionint main(){ printNumbers(); return 0;}Output:1 2 3 4 5 6 7 8 9 10\n" }, { "code": null, "e": 3904, "s": 3902, "text": "C" }, { "code": null, "e": 3908, "s": 3904, "text": "C++" }, { "code": "// C program to print numbers// from 1 to 10 using goto statement#include <stdio.h> // function to print numbers from 1 to 10void printNumbers(){ int n = 1;label: printf(\"%d \",n); n++; if (n <= 10) goto label;} // Driver program to test above functionint main() { printNumbers(); return 0;}", "e": 4226, "s": 3908, "text": null }, { "code": "// C++ program to print numbers// from 1 to 10 using goto statement#include <iostream>using namespace std; // function to print numbers from 1 to 10void printNumbers(){ int n = 1;label: cout << n << \" \"; n++; if (n <= 10) goto label;} // Driver program to test above functionint main(){ printNumbers(); return 0;}", "e": 4567, "s": 4226, "text": null }, { "code": null, "e": 4589, "s": 4567, "text": "1 2 3 4 5 6 7 8 9 10\n" }, { "code": null, "e": 4628, "s": 4589, "text": "Disadvantages of using goto statement:" }, { "code": null, "e": 4720, "s": 4628, "text": "The use of goto statement is highly discouraged as it makes the program logic very complex." }, { "code": null, "e": 4855, "s": 4720, "text": "use of goto makes the task of analyzing and verifying the correctness of programs (particularly those involving loops) very difficult." }, { "code": null, "e": 4926, "s": 4855, "text": "Use of goto can be simply avoided using break and continue statements." }, { "code": null, "e": 5227, "s": 4926, "text": "This article is contributed by Harsh Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 5352, "s": 5227, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 5370, "s": 5352, "text": "SonalSrivastava02" }, { "code": null, "e": 5381, "s": 5370, "text": "C Language" }, { "code": null, "e": 5385, "s": 5381, "text": "C++" }, { "code": null, "e": 5389, "s": 5385, "text": "CPP" } ]
C# | SortedDictionary.Remove() Method
01 Feb, 2019 This method is used to remove the value with the specified key from the SortedDictionary<TKey, TValue>. Syntax: public bool Remove (TKey key); Return Value: This method returns true if the element is successfully found and removed; otherwise it returns false. This method returns false if key is not found in the SortedDictionary. Exception: This method will give ArgumentNullException if the key is null. Below are the programs to illustrate the use of the above-discussed method: Example 1: // C# code to remove the entry with// the specified key from the// SortedDictionaryusing System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Create a new dictionary of // strings, with string keys. SortedDictionary<string, string> myDict = new SortedDictionary<string, string>(); // Adding key/value pairs in myDict myDict.Add("Australia", "Canberra"); myDict.Add("Belgium", "Brussels"); myDict.Add("Netherlands", "Amsterdam"); myDict.Add("China", "Beijing"); myDict.Add("Russia", "Moscow"); myDict.Add("India", "New Delhi"); // To get count of key/value pairs in myDict Console.WriteLine("Total key/value pairs" + " in myDict are : " + myDict.Count); // Remove the entry with the specified // key from the Dictionary myDict.Remove("Russia"); Console.WriteLine("After remove operation"); // To get count of key/value pairs in myDict Console.WriteLine("Total key/value pairs" + " in myDict are : " + myDict.Count); }} Total key/value pairs in myDict are : 6 After remove operation Total key/value pairs in myDict are : 5 Example 2: // C# code to remove the entry with// the specified key from the// SortedDictionaryusing System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Create a new SortedDictionary // of ints, with int keys. SortedDictionary<int, int> myDict = new SortedDictionary<int, int>(); // Adding key/value pairs in myDict myDict.Add(9, 8); myDict.Add(3, 4); myDict.Add(4, 7); myDict.Add(1, 7); // To get count of key/value pairs in myDict Console.WriteLine("Total key/value pairs " + "in myDict are : " + myDict.Count); // Remove the entry with the specified // key from the Dictionary myDict.Remove(9); Console.WriteLine("After remove operation"); // To get count of key/value pairs in myDict Console.WriteLine("Total key/value pairs in" + " myDict are : " + myDict.Count); }} Total key/value pairs in myDict are : 4 After remove operation Total key/value pairs in myDict are : 3 Reference: https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.sorteddictionary-2.remove?view=netframework-4.7.2 CSharp SortedDictionary Class CSharp-Generic-Namespace CSharp-method C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Feb, 2019" }, { "code": null, "e": 132, "s": 28, "text": "This method is used to remove the value with the specified key from the SortedDictionary<TKey, TValue>." }, { "code": null, "e": 140, "s": 132, "text": "Syntax:" }, { "code": null, "e": 172, "s": 140, "text": "public bool Remove (TKey key);\n" }, { "code": null, "e": 360, "s": 172, "text": "Return Value: This method returns true if the element is successfully found and removed; otherwise it returns false. This method returns false if key is not found in the SortedDictionary." }, { "code": null, "e": 435, "s": 360, "text": "Exception: This method will give ArgumentNullException if the key is null." }, { "code": null, "e": 511, "s": 435, "text": "Below are the programs to illustrate the use of the above-discussed method:" }, { "code": null, "e": 522, "s": 511, "text": "Example 1:" }, { "code": "// C# code to remove the entry with// the specified key from the// SortedDictionaryusing System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Create a new dictionary of // strings, with string keys. SortedDictionary<string, string> myDict = new SortedDictionary<string, string>(); // Adding key/value pairs in myDict myDict.Add(\"Australia\", \"Canberra\"); myDict.Add(\"Belgium\", \"Brussels\"); myDict.Add(\"Netherlands\", \"Amsterdam\"); myDict.Add(\"China\", \"Beijing\"); myDict.Add(\"Russia\", \"Moscow\"); myDict.Add(\"India\", \"New Delhi\"); // To get count of key/value pairs in myDict Console.WriteLine(\"Total key/value pairs\" + \" in myDict are : \" + myDict.Count); // Remove the entry with the specified // key from the Dictionary myDict.Remove(\"Russia\"); Console.WriteLine(\"After remove operation\"); // To get count of key/value pairs in myDict Console.WriteLine(\"Total key/value pairs\" + \" in myDict are : \" + myDict.Count); }}", "e": 1670, "s": 522, "text": null }, { "code": null, "e": 1774, "s": 1670, "text": "Total key/value pairs in myDict are : 6\nAfter remove operation\nTotal key/value pairs in myDict are : 5\n" }, { "code": null, "e": 1785, "s": 1774, "text": "Example 2:" }, { "code": "// C# code to remove the entry with// the specified key from the// SortedDictionaryusing System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Create a new SortedDictionary // of ints, with int keys. SortedDictionary<int, int> myDict = new SortedDictionary<int, int>(); // Adding key/value pairs in myDict myDict.Add(9, 8); myDict.Add(3, 4); myDict.Add(4, 7); myDict.Add(1, 7); // To get count of key/value pairs in myDict Console.WriteLine(\"Total key/value pairs \" + \"in myDict are : \" + myDict.Count); // Remove the entry with the specified // key from the Dictionary myDict.Remove(9); Console.WriteLine(\"After remove operation\"); // To get count of key/value pairs in myDict Console.WriteLine(\"Total key/value pairs in\" + \" myDict are : \" + myDict.Count); }}", "e": 2769, "s": 1785, "text": null }, { "code": null, "e": 2873, "s": 2769, "text": "Total key/value pairs in myDict are : 4\nAfter remove operation\nTotal key/value pairs in myDict are : 3\n" }, { "code": null, "e": 2884, "s": 2873, "text": "Reference:" }, { "code": null, "e": 3005, "s": 2884, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.sorteddictionary-2.remove?view=netframework-4.7.2" }, { "code": null, "e": 3035, "s": 3005, "text": "CSharp SortedDictionary Class" }, { "code": null, "e": 3060, "s": 3035, "text": "CSharp-Generic-Namespace" }, { "code": null, "e": 3074, "s": 3060, "text": "CSharp-method" }, { "code": null, "e": 3077, "s": 3074, "text": "C#" } ]
Keyboard Events in ElectronJS
22 Jun, 2020 ElectronJS is an Open Source Framework used for building Cross-Platform native desktop applications using web technologies such as HTML, CSS, and JavaScript which are capable of running on Windows, macOS, and Linux operating systems. It combines the Chromium engine and NodeJS into a Single Runtime. In web development, the jQuery Keyboard Events provide a convenient way by which we can record the keypresses of the keyboard in a sequential order. These events include key combinations, special keys and modifiers and are fired as soon as the key is on its way down, is pressed and is released. These events are very important in case we want to track or trigger some functionality on certain key presses. In addition to providing Accelerators and the globalShortcut module, Electron also provide us with a way by which we can record the keyboard Events using the Instance methods and event of the built-in BrowserWindow object and the webContents property. This tutorial will demonstrate Keyboard Events in Electron. We assume that you are familiar with the prerequisites as covered in the above-mentioned link. For Electron to work, node and npm need to be pre-installed in the system. Project Structure: Example: Follow the Steps given in How to Find Text on Page in ElectronJS to setup the basic Electron Application. Copy the Boilerplate code for the main.js file and the index.html file as provided in the article. Also perform the necessary changes mentioned for the package.json file to launch the Electron Application. We will continue building our application using the same code base. The basic steps required to setup the Electron application remain the same. package.json: { "name": "electron-key", "version": "1.0.0", "description": "Key events in Electron", "main": "main.js", "scripts": { "start": "electron ." }, "keywords": [ "electron" ], "author": "Radhesh Khanna", "license": "ISC", "dependencies": { "electron": "^8.3.0" } } Output: At this point, our basic Electron Application is set up. Upon launching the application, we should see the following result Keyboard Events in Electron: The BrowserWindow Instance and webContents Property are part of the Main Process. To import and use BrowserWindow in the Renderer Process, we will be using Electron remote module. index.html: Add the following snippet in that file. html <h3>Key Events in Electron</h3> index.js: Add the following snippet in that file. javascript const electron = require("electron"); // Importing BrowserWindow from Main Process // using Electron remoteconst BrowserWindow = electron.remote.BrowserWindow;const win = BrowserWindow.getFocusedWindow(); // let win = BrowserWindow.getAllWindows()[0]; win.webContents.on("before-input-event", (event, input) => { console.log(input);}); The before-input-event of the webContents property works closely with the KeyboardEvent Web API. The KeyboardEvent describes a user interaction with the keyboard. It inherits the Instance method and properties of the UIEvent and the global Event object. The before-input-event Instance Event is emitted before dispatching the keydown and keyup events of the KeyboardEvent in the web page. This Instance event leverages the Constructor of the KeyboardEvent object. It returns the following parameters. event: The global Event object. input: Object It contains the following parameters.type: String This parameter defines the type of the KeyboardEvent that has occurred. Values can be either keyUp or keyDown. The before-input-event Event does not support keyPressed event since it has been deprecated from the KeyboardEvent Web API itself.key: String This parameter is equivalent to the KeyboardEvent.key parameter. It is a Readonly property. This value returns a DOMString representing the key value of the key pressed. code: String This parameter is equivalent to the KeyboardEvent.code parameter. It is a Readonly property. This value returns a DOMString with the code value of the key pressed. isAutoRepeat: Boolean This parameter is equivalent to the KeyboardEvent.repeat parameter. It is a Readonly property. This value returns true if the key is being held down for longer durations such that it is automatically repeating. Default value is false.shift: Boolean This parameter is equivalent to the KeyboardEvent.shiftKey parameter. It is a Readonly property. This value returns true if the Shift key is active when the key is pressed.control: Boolean This parameter is equivalent to the KeyboardEvent.controlKey parameter. It is a Readonly property. This value returns true if the Ctrl key is active when the key is pressed. Default value is false.alt: Boolean This parameter is equivalent to the KeyboardEvent.altKey parameter. It is a Readonly property. This value returns true if the Alt key on Windows and Linux is active when the key is pressed (Equivalent to the Options key on macOS).Default value is false.meta: Boolean This parameter is equivalent to the KeyboardEvent.metaKey parameter. It is a Readonly property. This value returns true if the windows key on Windows and Linux is active when the key is pressed (Equivalent to the Command key on macOS). Default value is false. type: String This parameter defines the type of the KeyboardEvent that has occurred. Values can be either keyUp or keyDown. The before-input-event Event does not support keyPressed event since it has been deprecated from the KeyboardEvent Web API itself. key: String This parameter is equivalent to the KeyboardEvent.key parameter. It is a Readonly property. This value returns a DOMString representing the key value of the key pressed. code: String This parameter is equivalent to the KeyboardEvent.code parameter. It is a Readonly property. This value returns a DOMString with the code value of the key pressed. isAutoRepeat: Boolean This parameter is equivalent to the KeyboardEvent.repeat parameter. It is a Readonly property. This value returns true if the key is being held down for longer durations such that it is automatically repeating. Default value is false. shift: Boolean This parameter is equivalent to the KeyboardEvent.shiftKey parameter. It is a Readonly property. This value returns true if the Shift key is active when the key is pressed. control: Boolean This parameter is equivalent to the KeyboardEvent.controlKey parameter. It is a Readonly property. This value returns true if the Ctrl key is active when the key is pressed. Default value is false. alt: Boolean This parameter is equivalent to the KeyboardEvent.altKey parameter. It is a Readonly property. This value returns true if the Alt key on Windows and Linux is active when the key is pressed (Equivalent to the Options key on macOS).Default value is false. meta: Boolean This parameter is equivalent to the KeyboardEvent.metaKey parameter. It is a Readonly property. This value returns true if the windows key on Windows and Linux is active when the key is pressed (Equivalent to the Command key on macOS). Default value is false. To get the current BrowserWindow Instance in the Renderer Process, we can use some of the Static Methods provided by the BrowserWindow object. BrowserWindow.getAllWindows(): This method returns an Array of active/opened BrowserWindow Instances. In this application, we have only one active BrowserWindow Instance and it can be directly refered from the Array as shown in the code. BrowserWindow.getFocusedWindow(): This method returns the BrowserWindow Instance which is focused in the Application. If no current BrowserWindow Instance is found, it returns null. In this application, we only have one active BrowserWindow Instance and it can be directly referred using this method as shown in the code. Output: At this point, we should be able to successfully trigger the KeyboardEvents in Electron. ElectronJS CSS HTML JavaScript Node.js Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Types of CSS (Cascading Style Sheet) How to set space between the flexbox ? Design a Tribute Page using HTML & CSS How to position a div at the bottom of its container using CSS? How to Upload Image into Database and Display it using PHP ? REST API (Introduction) Hide or show elements in HTML using display property How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ? Types of CSS (Cascading Style Sheet)
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Jun, 2020" }, { "code": null, "e": 328, "s": 28, "text": "ElectronJS is an Open Source Framework used for building Cross-Platform native desktop applications using web technologies such as HTML, CSS, and JavaScript which are capable of running on Windows, macOS, and Linux operating systems. It combines the Chromium engine and NodeJS into a Single Runtime." }, { "code": null, "e": 1048, "s": 328, "text": "In web development, the jQuery Keyboard Events provide a convenient way by which we can record the keypresses of the keyboard in a sequential order. These events include key combinations, special keys and modifiers and are fired as soon as the key is on its way down, is pressed and is released. These events are very important in case we want to track or trigger some functionality on certain key presses. In addition to providing Accelerators and the globalShortcut module, Electron also provide us with a way by which we can record the keyboard Events using the Instance methods and event of the built-in BrowserWindow object and the webContents property. This tutorial will demonstrate Keyboard Events in Electron. " }, { "code": null, "e": 1218, "s": 1048, "text": "We assume that you are familiar with the prerequisites as covered in the above-mentioned link. For Electron to work, node and npm need to be pre-installed in the system." }, { "code": null, "e": 1238, "s": 1218, "text": "Project Structure: " }, { "code": null, "e": 1705, "s": 1238, "text": "Example: Follow the Steps given in How to Find Text on Page in ElectronJS to setup the basic Electron Application. Copy the Boilerplate code for the main.js file and the index.html file as provided in the article. Also perform the necessary changes mentioned for the package.json file to launch the Electron Application. We will continue building our application using the same code base. The basic steps required to setup the Electron application remain the same. " }, { "code": null, "e": 1720, "s": 1705, "text": "package.json: " }, { "code": null, "e": 2018, "s": 1720, "text": "{\n \"name\": \"electron-key\",\n \"version\": \"1.0.0\",\n \"description\": \"Key events in Electron\",\n \"main\": \"main.js\",\n \"scripts\": {\n \"start\": \"electron .\"\n },\n \"keywords\": [\n \"electron\"\n ],\n \"author\": \"Radhesh Khanna\",\n \"license\": \"ISC\",\n \"dependencies\": {\n \"electron\": \"^8.3.0\"\n }\n}\n" }, { "code": null, "e": 2151, "s": 2018, "text": "Output: At this point, our basic Electron Application is set up. Upon launching the application, we should see the following result " }, { "code": null, "e": 2361, "s": 2151, "text": "Keyboard Events in Electron: The BrowserWindow Instance and webContents Property are part of the Main Process. To import and use BrowserWindow in the Renderer Process, we will be using Electron remote module. " }, { "code": null, "e": 2414, "s": 2361, "text": "index.html: Add the following snippet in that file. " }, { "code": null, "e": 2419, "s": 2414, "text": "html" }, { "code": "<h3>Key Events in Electron</h3>", "e": 2451, "s": 2419, "text": null }, { "code": null, "e": 2503, "s": 2451, "text": "index.js: Add the following snippet in that file. " }, { "code": null, "e": 2514, "s": 2503, "text": "javascript" }, { "code": "const electron = require(\"electron\"); // Importing BrowserWindow from Main Process // using Electron remoteconst BrowserWindow = electron.remote.BrowserWindow;const win = BrowserWindow.getFocusedWindow(); // let win = BrowserWindow.getAllWindows()[0]; win.webContents.on(\"before-input-event\", (event, input) => { console.log(input);});", "e": 2856, "s": 2514, "text": null }, { "code": null, "e": 3358, "s": 2856, "text": "The before-input-event of the webContents property works closely with the KeyboardEvent Web API. The KeyboardEvent describes a user interaction with the keyboard. It inherits the Instance method and properties of the UIEvent and the global Event object. The before-input-event Instance Event is emitted before dispatching the keydown and keyup events of the KeyboardEvent in the web page. This Instance event leverages the Constructor of the KeyboardEvent object. It returns the following parameters. " }, { "code": null, "e": 3390, "s": 3358, "text": "event: The global Event object." }, { "code": null, "e": 5252, "s": 3390, "text": "input: Object It contains the following parameters.type: String This parameter defines the type of the KeyboardEvent that has occurred. Values can be either keyUp or keyDown. The before-input-event Event does not support keyPressed event since it has been deprecated from the KeyboardEvent Web API itself.key: String This parameter is equivalent to the KeyboardEvent.key parameter. It is a Readonly property. This value returns a DOMString representing the key value of the key pressed. code: String This parameter is equivalent to the KeyboardEvent.code parameter. It is a Readonly property. This value returns a DOMString with the code value of the key pressed. isAutoRepeat: Boolean This parameter is equivalent to the KeyboardEvent.repeat parameter. It is a Readonly property. This value returns true if the key is being held down for longer durations such that it is automatically repeating. Default value is false.shift: Boolean This parameter is equivalent to the KeyboardEvent.shiftKey parameter. It is a Readonly property. This value returns true if the Shift key is active when the key is pressed.control: Boolean This parameter is equivalent to the KeyboardEvent.controlKey parameter. It is a Readonly property. This value returns true if the Ctrl key is active when the key is pressed. Default value is false.alt: Boolean This parameter is equivalent to the KeyboardEvent.altKey parameter. It is a Readonly property. This value returns true if the Alt key on Windows and Linux is active when the key is pressed (Equivalent to the Options key on macOS).Default value is false.meta: Boolean This parameter is equivalent to the KeyboardEvent.metaKey parameter. It is a Readonly property. This value returns true if the windows key on Windows and Linux is active when the key is pressed (Equivalent to the Command key on macOS). Default value is false." }, { "code": null, "e": 5507, "s": 5252, "text": "type: String This parameter defines the type of the KeyboardEvent that has occurred. Values can be either keyUp or keyDown. The before-input-event Event does not support keyPressed event since it has been deprecated from the KeyboardEvent Web API itself." }, { "code": null, "e": 5690, "s": 5507, "text": "key: String This parameter is equivalent to the KeyboardEvent.key parameter. It is a Readonly property. This value returns a DOMString representing the key value of the key pressed. " }, { "code": null, "e": 5868, "s": 5690, "text": "code: String This parameter is equivalent to the KeyboardEvent.code parameter. It is a Readonly property. This value returns a DOMString with the code value of the key pressed. " }, { "code": null, "e": 6126, "s": 5868, "text": "isAutoRepeat: Boolean This parameter is equivalent to the KeyboardEvent.repeat parameter. It is a Readonly property. This value returns true if the key is being held down for longer durations such that it is automatically repeating. Default value is false." }, { "code": null, "e": 6314, "s": 6126, "text": "shift: Boolean This parameter is equivalent to the KeyboardEvent.shiftKey parameter. It is a Readonly property. This value returns true if the Shift key is active when the key is pressed." }, { "code": null, "e": 6529, "s": 6314, "text": "control: Boolean This parameter is equivalent to the KeyboardEvent.controlKey parameter. It is a Readonly property. This value returns true if the Ctrl key is active when the key is pressed. Default value is false." }, { "code": null, "e": 6796, "s": 6529, "text": "alt: Boolean This parameter is equivalent to the KeyboardEvent.altKey parameter. It is a Readonly property. This value returns true if the Alt key on Windows and Linux is active when the key is pressed (Equivalent to the Options key on macOS).Default value is false." }, { "code": null, "e": 7070, "s": 6796, "text": "meta: Boolean This parameter is equivalent to the KeyboardEvent.metaKey parameter. It is a Readonly property. This value returns true if the windows key on Windows and Linux is active when the key is pressed (Equivalent to the Command key on macOS). Default value is false." }, { "code": null, "e": 7214, "s": 7070, "text": "To get the current BrowserWindow Instance in the Renderer Process, we can use some of the Static Methods provided by the BrowserWindow object. " }, { "code": null, "e": 7452, "s": 7214, "text": "BrowserWindow.getAllWindows(): This method returns an Array of active/opened BrowserWindow Instances. In this application, we have only one active BrowserWindow Instance and it can be directly refered from the Array as shown in the code." }, { "code": null, "e": 7775, "s": 7452, "text": "BrowserWindow.getFocusedWindow(): This method returns the BrowserWindow Instance which is focused in the Application. If no current BrowserWindow Instance is found, it returns null. In this application, we only have one active BrowserWindow Instance and it can be directly referred using this method as shown in the code. " }, { "code": null, "e": 7874, "s": 7775, "text": "Output: At this point, we should be able to successfully trigger the KeyboardEvents in Electron. " }, { "code": null, "e": 7885, "s": 7874, "text": "ElectronJS" }, { "code": null, "e": 7889, "s": 7885, "text": "CSS" }, { "code": null, "e": 7894, "s": 7889, "text": "HTML" }, { "code": null, "e": 7905, "s": 7894, "text": "JavaScript" }, { "code": null, "e": 7913, "s": 7905, "text": "Node.js" }, { "code": null, "e": 7930, "s": 7913, "text": "Web Technologies" }, { "code": null, "e": 7935, "s": 7930, "text": "HTML" }, { "code": null, "e": 8033, "s": 7935, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8070, "s": 8033, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 8109, "s": 8070, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 8148, "s": 8109, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 8212, "s": 8148, "text": "How to position a div at the bottom of its container using CSS?" }, { "code": null, "e": 8273, "s": 8212, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 8297, "s": 8273, "text": "REST API (Introduction)" }, { "code": null, "e": 8350, "s": 8297, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 8410, "s": 8350, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 8471, "s": 8410, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" } ]
Parallel vs Sequential Stream in Java
15 Oct, 2020 Prerequisite: Streams in Java A stream in Java is a sequence of objects which operates on a data source such as an array or a collection and supports various methods. It was introduced in Java 8’s java.util.stream package. Stream supports many aggregate operations like filter, map, limit, reduce, find, and match to customize the original data into a different form according to the need of the programmer. The operations performed on a stream do not modify its source hence a new stream is created according to the operation applied to it. The new data is a transformed copy of the original form. Sequential Streams are non-parallel streams that use a single thread to process the pipelining. Any stream operation without explicitly specified as parallel is treated as a sequential stream. Sequential stream’s objects are pipelined in a single stream on the same processing system hence it never takes the advantage of the multi-core system even though the underlying system supports parallel execution. Sequential stream performs operation one by one. stream() method returns a sequential stream in Java. Example: Java // Java program to understand execution// of sequential streams import java.io.*;import java.util.*;import java.util.stream.*; class SequentialStreamDemo { public static void main(String[] args) { // create a list List<String> list = Arrays.asList( "Hello ", "G", "E", "E", "K", "S!"); // we are using stream() method // for sequential stream // Iterate and print each element // of the stream list.stream().forEach(System.out::print); }} Hello GEEKS! In this example the list.stream() works in sequence on a single thread with the print() operation and in the output of the preceding program, the content of the list is printed in an ordered sequence as this is a sequential stream. It is a very useful feature of Java to use parallel processing, even if the whole program may not be parallelized. Parallel stream leverage multi-core processors, which increases its performance. Using parallel streams, our code gets divide into multiple streams which can be executed parallelly on separate cores of the system and the final result is shown as the combination of all the individual core’s outcomes. It is always not necessary that the whole program be parallelized, but at least some parts should be parallelized which handles the stream. The order of execution is not under our control and can give us unpredictably unordered results and like any other parallel programming, they are complex and error-prone. The Java stream library provides a couple of ways to do it. easily, and in a reliable manner. One of the simple ways to obtain a parallel stream is by invoking the parallelStream() method of Collection interface. Another way is to invoke the parallel() method of BaseStream interface on a sequential stream. It is important to ensure that the result of the parallel stream is the same as is obtained through the sequential stream, so the parallel streams must be stateless, non-interfering, and associative. Example: Java // Java code to demonstrate// ParallelStreams import java.io.*;import java.util.*;import java.util.stream.*; class ParallelStreamExample { public static void main(String[] args) { // create a list List<String> list = Arrays.asList("Hello ", "G", "E", "E", "K", "S!"); // using parallelStream() // method for parallel stream list.parallelStream().forEach(System.out::print); }} ES!KGEHello Here we can see the order is not maintained as the list.parallelStream() works parallelly on multiple threads. If we run this code multiple times then we can also see that each time we are getting a different order as output but this parallel stream boosts the performance so the situation where the order is not important is the best technique to use. Note: If we want to make each element in the parallel stream to be ordered, we can use the forEachOrdered() method, instead of the forEach() method. Example: Java // Java code to demonstrate Iterating in // the same order via parallelStream import java.io.*;import java.util.*;import java.util.stream.*; class ParallelStreamWithOrderedIteration { public static void main(String[] args) { // create a list List<String> list = Arrays.asList("Hello ","G", "E", "E", "K", "S!"); // using parallelStream() method for parallel stream list.parallelStream().forEachOrdered(System.out::print); }} Hello GEEKS! We can always switch between parallel and sequential very easily according to our requirements. If we want to change the parallel stream as sequential, then we should use the sequential() method specified by BaseStream Interface. Differences between Sequential Stream and Parallel Stream Sequential Stream Parallel Stream The stream APIs have been a part of Java for a long time for its intriguing feature. It is also very much popular for parallel processing capability and improved performance. In this era literally, every modern machine is multi-core so to this core efficiently we should use parallel streams however parallel programming design is complex. So it’s completely up to the programmer whether he wants to use parallel streams or sequential streams based on the requirements. java-stream Difference Between Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n15 Oct, 2020" }, { "code": null, "e": 83, "s": 53, "text": "Prerequisite: Streams in Java" }, { "code": null, "e": 654, "s": 83, "text": "A stream in Java is a sequence of objects which operates on a data source such as an array or a collection and supports various methods. It was introduced in Java 8’s java.util.stream package. Stream supports many aggregate operations like filter, map, limit, reduce, find, and match to customize the original data into a different form according to the need of the programmer. The operations performed on a stream do not modify its source hence a new stream is created according to the operation applied to it. The new data is a transformed copy of the original form. " }, { "code": null, "e": 1110, "s": 654, "text": "Sequential Streams are non-parallel streams that use a single thread to process the pipelining. Any stream operation without explicitly specified as parallel is treated as a sequential stream. Sequential stream’s objects are pipelined in a single stream on the same processing system hence it never takes the advantage of the multi-core system even though the underlying system supports parallel execution. Sequential stream performs operation one by one." }, { "code": null, "e": 1163, "s": 1110, "text": "stream() method returns a sequential stream in Java." }, { "code": null, "e": 1173, "s": 1163, "text": "Example: " }, { "code": null, "e": 1178, "s": 1173, "text": "Java" }, { "code": "// Java program to understand execution// of sequential streams import java.io.*;import java.util.*;import java.util.stream.*; class SequentialStreamDemo { public static void main(String[] args) { // create a list List<String> list = Arrays.asList( \"Hello \", \"G\", \"E\", \"E\", \"K\", \"S!\"); // we are using stream() method // for sequential stream // Iterate and print each element // of the stream list.stream().forEach(System.out::print); }}", "e": 1713, "s": 1178, "text": null }, { "code": null, "e": 1726, "s": 1713, "text": "Hello GEEKS!" }, { "code": null, "e": 1958, "s": 1726, "text": "In this example the list.stream() works in sequence on a single thread with the print() operation and in the output of the preceding program, the content of the list is printed in an ordered sequence as this is a sequential stream." }, { "code": null, "e": 2686, "s": 1958, "text": "It is a very useful feature of Java to use parallel processing, even if the whole program may not be parallelized. Parallel stream leverage multi-core processors, which increases its performance. Using parallel streams, our code gets divide into multiple streams which can be executed parallelly on separate cores of the system and the final result is shown as the combination of all the individual core’s outcomes. It is always not necessary that the whole program be parallelized, but at least some parts should be parallelized which handles the stream. The order of execution is not under our control and can give us unpredictably unordered results and like any other parallel programming, they are complex and error-prone. " }, { "code": null, "e": 2781, "s": 2686, "text": "The Java stream library provides a couple of ways to do it. easily, and in a reliable manner. " }, { "code": null, "e": 2900, "s": 2781, "text": "One of the simple ways to obtain a parallel stream is by invoking the parallelStream() method of Collection interface." }, { "code": null, "e": 2995, "s": 2900, "text": "Another way is to invoke the parallel() method of BaseStream interface on a sequential stream." }, { "code": null, "e": 3195, "s": 2995, "text": "It is important to ensure that the result of the parallel stream is the same as is obtained through the sequential stream, so the parallel streams must be stateless, non-interfering, and associative." }, { "code": null, "e": 3204, "s": 3195, "text": "Example:" }, { "code": null, "e": 3209, "s": 3204, "text": "Java" }, { "code": "// Java code to demonstrate// ParallelStreams import java.io.*;import java.util.*;import java.util.stream.*; class ParallelStreamExample { public static void main(String[] args) { // create a list List<String> list = Arrays.asList(\"Hello \", \"G\", \"E\", \"E\", \"K\", \"S!\"); // using parallelStream() // method for parallel stream list.parallelStream().forEach(System.out::print); }}", "e": 3660, "s": 3209, "text": null }, { "code": null, "e": 3672, "s": 3660, "text": "ES!KGEHello" }, { "code": null, "e": 4025, "s": 3672, "text": "Here we can see the order is not maintained as the list.parallelStream() works parallelly on multiple threads. If we run this code multiple times then we can also see that each time we are getting a different order as output but this parallel stream boosts the performance so the situation where the order is not important is the best technique to use." }, { "code": null, "e": 4174, "s": 4025, "text": "Note: If we want to make each element in the parallel stream to be ordered, we can use the forEachOrdered() method, instead of the forEach() method." }, { "code": null, "e": 4184, "s": 4174, "text": "Example: " }, { "code": null, "e": 4189, "s": 4184, "text": "Java" }, { "code": "// Java code to demonstrate Iterating in // the same order via parallelStream import java.io.*;import java.util.*;import java.util.stream.*; class ParallelStreamWithOrderedIteration { public static void main(String[] args) { // create a list List<String> list = Arrays.asList(\"Hello \",\"G\", \"E\", \"E\", \"K\", \"S!\"); // using parallelStream() method for parallel stream list.parallelStream().forEachOrdered(System.out::print); }}", "e": 4678, "s": 4189, "text": null }, { "code": null, "e": 4691, "s": 4678, "text": "Hello GEEKS!" }, { "code": null, "e": 4921, "s": 4691, "text": "We can always switch between parallel and sequential very easily according to our requirements. If we want to change the parallel stream as sequential, then we should use the sequential() method specified by BaseStream Interface." }, { "code": null, "e": 4979, "s": 4921, "text": "Differences between Sequential Stream and Parallel Stream" }, { "code": null, "e": 4997, "s": 4979, "text": "Sequential Stream" }, { "code": null, "e": 5013, "s": 4997, "text": "Parallel Stream" }, { "code": null, "e": 5484, "s": 5013, "text": "The stream APIs have been a part of Java for a long time for its intriguing feature. It is also very much popular for parallel processing capability and improved performance. In this era literally, every modern machine is multi-core so to this core efficiently we should use parallel streams however parallel programming design is complex. So it’s completely up to the programmer whether he wants to use parallel streams or sequential streams based on the requirements." }, { "code": null, "e": 5496, "s": 5484, "text": "java-stream" }, { "code": null, "e": 5515, "s": 5496, "text": "Difference Between" }, { "code": null, "e": 5520, "s": 5515, "text": "Java" }, { "code": null, "e": 5525, "s": 5520, "text": "Java" } ]
Find maximum element of each row in a matrix
10 Jun, 2022 Given a matrix, the task is to find the maximum element of each row.Examples: Input : [1, 2, 3] [1, 4, 9] [76, 34, 21] Output : 3 9 76 Input : [1, 2, 3, 21] [12, 1, 65, 9] [1, 56, 34, 2] Output : 21 65 56 Approach : Approach is very simple. The idea is to run the loop for no_of_rows. Check each element inside the row and find for the maximum element. Finally, print the element. Below is the implementation : C++ Java Python C# PHP Javascript // C++ program to find maximum// element of each row in a matrix#include<bits/stdc++.h>using namespace std;const int N = 4; // Print array element void printArray(int result[], int no_of_rows) { for (int i = 0; i < no_of_rows; i++) { cout<< result[i]<<"\n"; } } // Function to get max element void maxelement(int no_of_rows, int arr[][N]) { int i = 0; // Initialize max to 0 at beginning // of finding max element of each row int max = 0; int result[no_of_rows]; while (i < no_of_rows) { for (int j = 0; j < N; j++) { if (arr[i][j] > max) { max = arr[i][j]; } } result[i] = max; max = 0; i++; } printArray(result,no_of_rows); } // Driver code int main() { int arr[][N] = { {3, 4, 1, 8}, {1, 4, 9, 11}, {76, 34, 21, 1}, {2, 1, 4, 5} }; // Calling the function maxelement(4, arr); } // This code is contributed by Rajput-Ji // Java program to find maximum// element of each row in a matrixpublic class GFG{ // Function to get max element public static void maxelement(int no_of_rows, int[][] arr) { int i = 0; // Initialize max to 0 at beginning // of finding max element of each row int max = 0; int[] result = new int[no_of_rows]; while (i < no_of_rows) { for (int j = 0; j < arr[i].length; j++) { if (arr[i][j] > max) { max = arr[i][j]; } } result[i] = max; max =0; i++; } printArray(result); } // Print array element private static void printArray(int[] result) { for (int i =0; i<result.length;i++) { System.out.println(result[i]); } } // Driver code public static void main(String[] args) { int[][] arr = new int[][] { {3, 4, 1, 8}, {1, 4, 9, 11}, {76, 34, 21, 1}, {2, 1, 4, 5} }; // Calling the function maxelement(4, arr); }} # Python program to find maximum# element of each row in a matrix # importing numpyimport numpy # Function to get max elementdef maxelement(arr): # get number of rows and columns no_of_rows = len(arr) no_of_column = len(arr[0]) for i in range(no_of_rows): # Initialize max1 to 0 at beginning # of finding max element of each row max1 = 0 for j in range(no_of_column): if arr[i][j] > max1 : max1 = arr[i][j] # print maximum element of each row print(max1) # Driver Codearr = [[3, 4, 1, 8], [1, 4, 9, 11], [76, 34, 21, 1], [2, 1, 4, 5]] # Calling the function maxelement(arr) // C# program to find maximum// element of each row in a matrixusing System; class GFG{ // Function to get max elementpublic static void maxelement(int no_of_rows, int[][] arr){ int i = 0; // Initialize max to 0 at beginning // of finding max element of each row int max = 0; int[] result = new int[no_of_rows]; while (i < no_of_rows) { for (int j = 0; j < arr[i].Length; j++) { if (arr[i][j] > max) { max = arr[i][j]; } } result[i] = max; max = 0; i++; } printArray(result); } // Print array elementprivate static void printArray(int[] result){ for (int i = 0; i < result.Length;i++) { Console.WriteLine(result[i]); } } // Driver codepublic static void Main(string[] args){ int[][] arr = new int[][] { new int[] {3, 4, 1, 8}, new int[] {1, 4, 9, 11}, new int[] {76, 34, 21, 1}, new int[] {2, 1, 4, 5} }; // Calling the function maxelement(4, arr);}} // This code is contributed by Shrikant13 <?php// PHP program to find maximum// element of each row in a matrix$N = 4; // Print array elementfunction printArray($result, $no_of_rows){ for ($i = 0; $i < $no_of_rows; $i++) { echo $result[$i]."\n"; } } // Function to get max elementfunction maxelement($no_of_rows, $arr){ global $N; $i = 0; // Initialize max to 0 at beginning // of finding max element of each row $max = 0; $result=array_fill(0,$no_of_rows,0); while ($i < $no_of_rows) { for ($j = 0; $j < $N; $j++) { if ($arr[$i][$j] > $max) { $max = $arr[$i][$j]; } } $result[$i] = $max; $max = 0; $i++; } printArray($result,$no_of_rows); } // Driver code$arr = array(array(3, 4, 1, 8), array(1, 4, 9, 11), array(76, 34, 21, 1), array(2, 1, 4, 5));// Calling the functionmaxelement(4, $arr); // This code is contributed by mits?> <script>// javascript program to find maximum// element of each row in a matrix// Function to get max elementfunction maxelement(no_of_rows, arr){ var i = 0; // Initialize max to 0 at beginning // of finding max element of each row var max = 0; var result = Array.from({length: no_of_rows}, (_, i) => 0); while (i < no_of_rows) { for (var j = 0; j < arr[i].length; j++) { if (arr[i][j] > max) { max = arr[i][j]; } } result[i] = max; max = 0; i++; } printArray(result); } // Print array elementfunction printArray(result){ for (var i = 0; i < result.length; i++) { document.write(result[i]+"<br>"); } } // Driver code var arr = [[3, 4, 1, 8], [ 1, 4, 9, 11], [ 76, 34, 21, 1], [ 2, 1, 4, 5] ]; // Calling the function maxelement(4, arr); // This code is contributed by 29AjayKumar</script> Output : 8 11 76 5 Time Complexity: O(n*m) (where, n refers to no. of rows and m refers to no. of columns) Auxiliary Space: O(n) (where, n refers to no. of rows) ApoorvaSaxena shrikanth13 Rajput-Ji Mithun Kumar shubham_singh 29AjayKumar ankita_saini ajaymakvana Matrix Searching Technical Scripter Searching Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n10 Jun, 2022" }, { "code": null, "e": 133, "s": 53, "text": "Given a matrix, the task is to find the maximum element of each row.Examples: " }, { "code": null, "e": 297, "s": 133, "text": "Input : [1, 2, 3]\n [1, 4, 9]\n [76, 34, 21]\n\nOutput :\n3\n9\n76\n\nInput : [1, 2, 3, 21]\n [12, 1, 65, 9]\n [1, 56, 34, 2]\nOutput :\n21\n65\n56" }, { "code": null, "e": 509, "s": 299, "text": "Approach : Approach is very simple. The idea is to run the loop for no_of_rows. Check each element inside the row and find for the maximum element. Finally, print the element. Below is the implementation : " }, { "code": null, "e": 513, "s": 509, "text": "C++" }, { "code": null, "e": 518, "s": 513, "text": "Java" }, { "code": null, "e": 525, "s": 518, "text": "Python" }, { "code": null, "e": 528, "s": 525, "text": "C#" }, { "code": null, "e": 532, "s": 528, "text": "PHP" }, { "code": null, "e": 543, "s": 532, "text": "Javascript" }, { "code": "// C++ program to find maximum// element of each row in a matrix#include<bits/stdc++.h>using namespace std;const int N = 4; // Print array element void printArray(int result[], int no_of_rows) { for (int i = 0; i < no_of_rows; i++) { cout<< result[i]<<\"\\n\"; } } // Function to get max element void maxelement(int no_of_rows, int arr[][N]) { int i = 0; // Initialize max to 0 at beginning // of finding max element of each row int max = 0; int result[no_of_rows]; while (i < no_of_rows) { for (int j = 0; j < N; j++) { if (arr[i][j] > max) { max = arr[i][j]; } } result[i] = max; max = 0; i++; } printArray(result,no_of_rows); } // Driver code int main() { int arr[][N] = { {3, 4, 1, 8}, {1, 4, 9, 11}, {76, 34, 21, 1}, {2, 1, 4, 5} }; // Calling the function maxelement(4, arr); } // This code is contributed by Rajput-Ji", "e": 1682, "s": 543, "text": null }, { "code": "// Java program to find maximum// element of each row in a matrixpublic class GFG{ // Function to get max element public static void maxelement(int no_of_rows, int[][] arr) { int i = 0; // Initialize max to 0 at beginning // of finding max element of each row int max = 0; int[] result = new int[no_of_rows]; while (i < no_of_rows) { for (int j = 0; j < arr[i].length; j++) { if (arr[i][j] > max) { max = arr[i][j]; } } result[i] = max; max =0; i++; } printArray(result); } // Print array element private static void printArray(int[] result) { for (int i =0; i<result.length;i++) { System.out.println(result[i]); } } // Driver code public static void main(String[] args) { int[][] arr = new int[][] { {3, 4, 1, 8}, {1, 4, 9, 11}, {76, 34, 21, 1}, {2, 1, 4, 5} }; // Calling the function maxelement(4, arr); }}", "e": 2844, "s": 1682, "text": null }, { "code": "# Python program to find maximum# element of each row in a matrix # importing numpyimport numpy # Function to get max elementdef maxelement(arr): # get number of rows and columns no_of_rows = len(arr) no_of_column = len(arr[0]) for i in range(no_of_rows): # Initialize max1 to 0 at beginning # of finding max element of each row max1 = 0 for j in range(no_of_column): if arr[i][j] > max1 : max1 = arr[i][j] # print maximum element of each row print(max1) # Driver Codearr = [[3, 4, 1, 8], [1, 4, 9, 11], [76, 34, 21, 1], [2, 1, 4, 5]] # Calling the function maxelement(arr)", "e": 3558, "s": 2844, "text": null }, { "code": "// C# program to find maximum// element of each row in a matrixusing System; class GFG{ // Function to get max elementpublic static void maxelement(int no_of_rows, int[][] arr){ int i = 0; // Initialize max to 0 at beginning // of finding max element of each row int max = 0; int[] result = new int[no_of_rows]; while (i < no_of_rows) { for (int j = 0; j < arr[i].Length; j++) { if (arr[i][j] > max) { max = arr[i][j]; } } result[i] = max; max = 0; i++; } printArray(result); } // Print array elementprivate static void printArray(int[] result){ for (int i = 0; i < result.Length;i++) { Console.WriteLine(result[i]); } } // Driver codepublic static void Main(string[] args){ int[][] arr = new int[][] { new int[] {3, 4, 1, 8}, new int[] {1, 4, 9, 11}, new int[] {76, 34, 21, 1}, new int[] {2, 1, 4, 5} }; // Calling the function maxelement(4, arr);}} // This code is contributed by Shrikant13", "e": 4679, "s": 3558, "text": null }, { "code": "<?php// PHP program to find maximum// element of each row in a matrix$N = 4; // Print array elementfunction printArray($result, $no_of_rows){ for ($i = 0; $i < $no_of_rows; $i++) { echo $result[$i].\"\\n\"; } } // Function to get max elementfunction maxelement($no_of_rows, $arr){ global $N; $i = 0; // Initialize max to 0 at beginning // of finding max element of each row $max = 0; $result=array_fill(0,$no_of_rows,0); while ($i < $no_of_rows) { for ($j = 0; $j < $N; $j++) { if ($arr[$i][$j] > $max) { $max = $arr[$i][$j]; } } $result[$i] = $max; $max = 0; $i++; } printArray($result,$no_of_rows); } // Driver code$arr = array(array(3, 4, 1, 8), array(1, 4, 9, 11), array(76, 34, 21, 1), array(2, 1, 4, 5));// Calling the functionmaxelement(4, $arr); // This code is contributed by mits?>", "e": 5656, "s": 4679, "text": null }, { "code": "<script>// javascript program to find maximum// element of each row in a matrix// Function to get max elementfunction maxelement(no_of_rows, arr){ var i = 0; // Initialize max to 0 at beginning // of finding max element of each row var max = 0; var result = Array.from({length: no_of_rows}, (_, i) => 0); while (i < no_of_rows) { for (var j = 0; j < arr[i].length; j++) { if (arr[i][j] > max) { max = arr[i][j]; } } result[i] = max; max = 0; i++; } printArray(result); } // Print array elementfunction printArray(result){ for (var i = 0; i < result.length; i++) { document.write(result[i]+\"<br>\"); } } // Driver code var arr = [[3, 4, 1, 8], [ 1, 4, 9, 11], [ 76, 34, 21, 1], [ 2, 1, 4, 5] ]; // Calling the function maxelement(4, arr); // This code is contributed by 29AjayKumar</script>", "e": 6599, "s": 5656, "text": null }, { "code": null, "e": 6608, "s": 6599, "text": "Output :" }, { "code": null, "e": 6618, "s": 6608, "text": "8\n11\n76\n5" }, { "code": null, "e": 6706, "s": 6618, "text": "Time Complexity: O(n*m) (where, n refers to no. of rows and m refers to no. of columns)" }, { "code": null, "e": 6761, "s": 6706, "text": "Auxiliary Space: O(n) (where, n refers to no. of rows)" }, { "code": null, "e": 6775, "s": 6761, "text": "ApoorvaSaxena" }, { "code": null, "e": 6787, "s": 6775, "text": "shrikanth13" }, { "code": null, "e": 6797, "s": 6787, "text": "Rajput-Ji" }, { "code": null, "e": 6810, "s": 6797, "text": "Mithun Kumar" }, { "code": null, "e": 6824, "s": 6810, "text": "shubham_singh" }, { "code": null, "e": 6836, "s": 6824, "text": "29AjayKumar" }, { "code": null, "e": 6849, "s": 6836, "text": "ankita_saini" }, { "code": null, "e": 6861, "s": 6849, "text": "ajaymakvana" }, { "code": null, "e": 6868, "s": 6861, "text": "Matrix" }, { "code": null, "e": 6878, "s": 6868, "text": "Searching" }, { "code": null, "e": 6897, "s": 6878, "text": "Technical Scripter" }, { "code": null, "e": 6907, "s": 6897, "text": "Searching" }, { "code": null, "e": 6914, "s": 6907, "text": "Matrix" } ]
How to count number of NULLs in a row with MySQL?
Use ISNULL() from MySQL. Let us first create a table − mysql> create table DemoTable -> ( -> Number1 int, -> Number2 int -> ); Query OK, 0 rows affected (0.59 sec) Insert some records in the table using insert command − mysql> insert into DemoTable values(10,NULL); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable values(NULL,NULL); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable values(29,98); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable values(NULL,119); Query OK, 1 row affected (0.15 sec) Display all records from the table using select statement. mysql> select *from DemoTable; This will produce the following output − +---------+---------+ | Number1 | Number2 | +---------+---------+ | 10 | NULL | | NULL | NULL | | 29 | 98 | | NULL | 119 | +---------+---------+ 4 rows in set (0.00 sec) Following is the query to count the number of NULLs in a row. mysql> select Number1,Number2,isnull(Number1)+isnull(Number2) AS NumberofNULLS from DemoTable; This will produce the following output − +---------+---------+--------------+ | Number1 | Number2 | NumberofNULLS| +---------+---------+--------------+ | 10 | NULL | 1 | | NULL | NULL | 2 | | 29 | 98 | 0 | | NULL | 119 | 1 | +---------+---------+--------------+ 4 rows in set (0.00 sec)
[ { "code": null, "e": 1117, "s": 1062, "text": "Use ISNULL() from MySQL. Let us first create a table −" }, { "code": null, "e": 1238, "s": 1117, "text": "mysql> create table DemoTable\n -> (\n -> Number1 int,\n -> Number2 int\n -> );\nQuery OK, 0 rows affected (0.59 sec)" }, { "code": null, "e": 1294, "s": 1238, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 1626, "s": 1294, "text": "mysql> insert into DemoTable values(10,NULL);\nQuery OK, 1 row affected (0.17 sec)\n\nmysql> insert into DemoTable values(NULL,NULL);\nQuery OK, 1 row affected (0.10 sec)\n\nmysql> insert into DemoTable values(29,98);\nQuery OK, 1 row affected (0.14 sec)\n\nmysql> insert into DemoTable values(NULL,119);\nQuery OK, 1 row affected (0.15 sec)" }, { "code": null, "e": 1685, "s": 1626, "text": "Display all records from the table using select statement." }, { "code": null, "e": 1716, "s": 1685, "text": "mysql> select *from DemoTable;" }, { "code": null, "e": 1757, "s": 1716, "text": "This will produce the following output −" }, { "code": null, "e": 1958, "s": 1757, "text": "+---------+---------+\n| Number1 | Number2 |\n+---------+---------+\n| 10 | NULL |\n| NULL | NULL |\n| 29 | 98 |\n| NULL | 119 |\n+---------+---------+\n4 rows in set (0.00 sec)" }, { "code": null, "e": 2020, "s": 1958, "text": "Following is the query to count the number of NULLs in a row." }, { "code": null, "e": 2115, "s": 2020, "text": "mysql> select Number1,Number2,isnull(Number1)+isnull(Number2) AS NumberofNULLS from DemoTable;" }, { "code": null, "e": 2156, "s": 2115, "text": "This will produce the following output −" }, { "code": null, "e": 2477, "s": 2156, "text": "+---------+---------+--------------+\n| Number1 | Number2 | NumberofNULLS|\n+---------+---------+--------------+\n| 10 | NULL | 1 |\n| NULL | NULL | 2 |\n| 29 | 98 | 0 |\n| NULL | 119 | 1 |\n+---------+---------+--------------+\n4 rows in set (0.00 sec)" } ]
Monte Carlo Integration and Sampling Methods | by Mengsay Loem | Towards Data Science
Integration is a critical calculation used frequently in problem solving. With a probability task, an expectation value of a continuous random variable x is defined by the following integration where p(x) is a probability density function of x. However, to calculate this value is not an easy process with a computer. To effectively define this integration, numerical approximation methods are used. Here, I will introduce a simple approximation method, Monte Carlo Integration Monte Carlo Integration is a numerical integration calculation method that uses random numbers to approximate the integration value. Consider the following calculation of the expectation value of f(x). Here, p(x) is a probability density function of x. In this method, we choose n samples {x_i} (i=1,2,...,n) independent and identically distributed (i.i.d) from the probability identity function p(x). The integration value is approximated by the mean of f(x) for all sample x. From the law of large numbers, a limitation of the Monte Carlo integration when n →∞ converges to the expectation value of f(x). Let’s calculate an approximate value of π with the Monte Carlo integration method. Consider a square with side-length 1 and a unit circle as shown in the following figure. The area of the circle is π. Now let f(x,y) be a function which outputs 1 when (x,y) lies inside the circle, and otherwise 0. Let p(x,y) be a uniform distribution on [-1,1]2. In this case, the area of the unit circle π can be written as With Monte Carlo integration, this integration (π) can be approximate by using i.i.d samples from p(x,y). n_(in circle) is the number of samples that lie in the unit circle. The following figure shows the convergence of Monte Carlo integration when n is large enough. With the Monte Carlo integration, we can simply compute the integration value with random numbers. However, the problem is “how to generate random numbers?” Of course, if the probability distribution is a well-known one, uniform distribution, Gaussian distribution, for example, we can easily implement the random number generator with some library. What if we have to generate random numbers from a distribution density function that is not implemented in any library? To solve this problem, sampling methods are used. A frequently used method is Importance Sampling. In this method, a proxy distribution is introduced to sample random numbers from any distribution. In most cases, we choose a well-known distribution such as Gaussian distribution, uniform distribution as a proxy distribution. The main concept of this method can be simply written in the following form, where q(x) is a proxy distribution. With Importance Sampling, instead of generating random numbers from p(x), we choose i.i.d samples {x’_i} (i=1,2,...,n) from a proxy distribution q(x) and approximate the integration value with the following calculation. Here, p(x)/q(x) is called importance of the sampling. Now, let’s use a Laplace distribution’ variance calculation as an example. Consider f(x)=x2 and a probability density function p(x)=1/2 Exp(-|x|). The distribution with density function like p(x) is called Laplace distribution. If we choose a uniform distribution as a proxy distribution, the variance of the Laplace distribution can be approximately calculated by With paper and a pencil, we can easily calculate the Var[x]. The value of this calculation is 2. Now, let’s confirm the result of the Importance Sampling method. In Importance Sampling, we use random numbers (samples) generated from a proxy distribution to approximate the integration value. To directly generated samples from a distribution with any probability density function, I introduce the following sampling method. In Inverse Transform Sampling method, we use a random number u generated from a 1-dimensional uniform distribution to generate a random number x of any 1-dimensional probability density function p(x). In this case, we use the inverse function of the cumulative distribution function of p(x). If the cumulative distribution function of p(x) is P(x), then the inverse function of u=P(x) is x =P^-1 (u). Now, x = P^-1 (u) has p(x) as probability density function on [0,1]. Therefore, with n samples from uniform distribution on [0,1] {u_i} (i=1,2,...,n), we can generate n sample of p(x) distribution {x_i} (i=1,2,...,n) by calculate x_i = P^-1(u_i). Again, let's consider the Laplace distribution’s variance calculation as an example. This time we directly generate random numbers (samples) from the Laplace distribution’s probability density function using the Inverse Transform Sampling method. With these random numbers, we will again recalculate the approximated value of Var[x]. Let’s check the result of this method. The following figure shows the approximated value of Laplace distribution variance V[x] using Inverse Transform Sampling method. From this result, it is straight forward that using directly generated random numbers from a distribution offers a better approximation compared to a case of proxy distribution. However, with the Inverse Transform Sampling method, it is impossible to directly generate random numbers from only 2 or higher dimension distribution. To do this, Rejection Sampling method is used. The idea in Rejection Sampling is to use a proxy distribution (Gaussian or uniform distribution, etc.) called q(x) to generate a random number and use another uniform distribution to evaluate the generated sample whether or not to accept it as a sample generated from p(x). With this method, we can also generate random numbers from a higher dimensional distribution. As preparation in generating random numbers with this method, we need to know a finite value of L where max[p(x)/q(x)] < L. Here, q(x) is a proxy distribution. First, we generate a random number x’ from a proxy distribution q(x). This x’ is called a proposal point. Next, generate a random number v from a uniform distribution on [0, L]. This v will be used to evaluate the proposal point, whether to be fine considering generated from p(x). If v ≤ p(x’)/q(x’), then x’ is accepted as a random number generated by p(x), else, x’ is rejected. The algorithm in generating n random numbers with Rejection Sampling is Result on random number generating and Laplace distribution variance calculation (Proxy distribution: Gaussian distribution) In the Rejection sampling method, it is impossible to generate random numbers when the upper boundary L is not known. MCMC method is an effective solution to this problem. MCMC method uses the concept of a stochastic process (Markov chain in this case). In this case, the generation of i-th sample x_i depends on the previous sample x_(i-1). x1, x2, ...,xn with this concept is called a Markov chain. Here, I introduce one of the MCMC methods, the Metropolis-Hastings method. The process in this method is similar to Rejection sampling. But here, a proxy distribution density function is represented by a conditional probability q(x|x_i), and the evaluation index v is generated from a uniform distribution on [0,1]. First, we generate a random number x’ from a proxy distribution q(x|x_i). This x’ is called a proposal point. Next, generate a random number v from a uniform distribution on [0, 1]. This v will be used to evaluate the proposal point, whether to be fine considering generated from p(x). If v ≤ p(x’)q(x_i|x’)/(p(x_i)q(x’|x_i)), then x’ is accepted as a random number generated by p(x), else, x’ is rejected. The algorithm in generating n random numbers with Rejection Sampling is Result on random number generating and Laplace distribution variance calculation (Proxy distribution: Gaussian distribution) import randomimport numpy as npfrom scipy.stats import norm def f(x,y): if (x*x+y*y<=1): return 1 else: return 0n = 10N = []P = []while n <= 100000: s = np.random.uniform(-1,1,(n,2)) nn = 0 for x in s: nn+=f(x[0],x[1]) pi = 4*nn/n N.append(n) P.append(pi) n = n*2 def f(x): return x*xdef p_pdf(x): return 0.5*np.exp(-abs(x))def imp_pdf(x): return norm.pdf(x)n = 10N = []P = []while n <= 100000: s = np.random.normal(0,1,n) nn = 0 for x in s: nn+=f(x)*p_pdf(x)/imp_pdf(x) p = nn/n N.append(n) P.append(p) n = n*2 def sgn(x): if x>0: return 1 elif x==0: return 0 else: return -1 def p_laplace(x): return 0.5*np.exp(-abs(x))#def P_laplace_cum(x): #return 0.5*((1+sgn(x))(1-np.exp(-abs(x))))def P_laplace_inv(u): k = 1-2*abs(u-0.5) return -1*sgn(u-0.5)*np.log(k)# random number generatordef reverse_generator(X): res = [] for u in X: res.append(P_laplace_inv(u)) return resn_sample = 50s = np.random.uniform(0,1,n_sample)theta = reverse_generator(s) print("n_sample = ",n_sample)gen_xx =random.sample(theta,n_sample)plt.scatter(gen_xx,[0]*n_sample,marker='x')xx=np.linspace(-15,15,1000)plt.plot(xx,[p_laplace(i) for i in xx],c='red')plt.legend(['Laplace Distribution','generated number'])plt.title("Random Numbers directly generated from p(x)")plt.show()# Laplace distribution variance calculationN = []P = []n= 10while n <= 100000: s = np.random.uniform(0,1,n) theta = reverse_generator(s) p = 0 for x in theta: p += x*x N.append(n) P.append(p/n) n = n*2 P_r = [2]*len(N)plt.plot(N,P)plt.plot(N,P_r,c='red')plt.legend(["Inverse Transform Sampling value","true value(2)"])plt.xlabel("number of samples (n) ")plt.show() def p_laplace(x): return 0.5*np.exp(-abs(x))def p_proxy(x): return norm.pdf(x)# random number generatordef rejection_generator(n): xx = np.linspace(0,1,100) K = max(p_laplace(xx)/p_proxy(xx))+1 random_samples = [] while len(random_samples) < n: proposal = np.random.randn() v = np.random.uniform(0,K) if v <= (p_laplace(proposal)/p_proxy(proposal)): random_samples.append(proposal) return random_samplesprint("generating...")random_samples = rejection_generator(n=50)print("n_sample = ",len(random_samples))plt.scatter(random_samples,[0]*len(random_samples),marker='x')xx=np.linspace(-15,15,1000)plt.plot(xx,[p_laplace(i) for i in xx],c='red')plt.legend(['true','gen'])plt.show()# Laplace distribution variance calculationN = []P = []n= 10while n <= 100000: theta = rejection_generator(n) p = 0 for x in theta: p += x*x N.append(n) P.append(p/n) n = n*2 P_r = [2]*len(N)plt.plot(N,P)plt.plot(N,P_r,c='red')plt.legend(["Rejection Sampling value","true value(2)"])plt.xlabel("number of samples (n) ")plt.show() def p_laplace(x): return 0.5*np.exp(-abs(x))def p_proxy(x,theta,sigma): return norm.pdf(x,theta,sigma)def MCMC_generator(n): random_samples = [] theta_i = 0 while len(random_samples) < n: proposal = np.random.normal(loc=theta_i,scale=1) v = np.random.uniform(0,1) a = p_laplace(proposal)*p_proxy(theta_i,proposal,1) b = p_laplace(theta_i)*p_proxy(proposal,theta_i,1) if v <= (a/b): random_samples.append(proposal) theta_i = proposal return random_samplesn = 50random_samples = MCMC_generator(n)print("n_sample = ",n)plt.scatter(random_samples,[0]*n,marker='x')xx=np.linspace(-15,15,1000)plt.plot(xx,[p_laplace(i) for i in xx],c='red')plt.legend(['true','gen'])plt.show()N = []P = []n= 10while n <= 10000: theta = MCMC_generator(n=n) p = 0 for x in theta: p += x*x N.append(n) P.append(p/n) n = n*2 P_r = [2]*len(N)plt.plot(N,P)plt.plot(N,P_r,c='red')plt.legend(["Rejection Sampling value","true value(2)"])plt.xlabel("number of samples (n) ")plt.show() M.Yamasugi. Statistical Machine Learning-generative model-based pattern recognition-. Ohmsha, Japan, 2019 M.Yamasugi. Statistical Machine Learning-generative model-based pattern recognition-. Ohmsha, Japan, 2019
[ { "code": null, "e": 417, "s": 172, "text": "Integration is a critical calculation used frequently in problem solving. With a probability task, an expectation value of a continuous random variable x is defined by the following integration where p(x) is a probability density function of x." }, { "code": null, "e": 650, "s": 417, "text": "However, to calculate this value is not an easy process with a computer. To effectively define this integration, numerical approximation methods are used. Here, I will introduce a simple approximation method, Monte Carlo Integration" }, { "code": null, "e": 903, "s": 650, "text": "Monte Carlo Integration is a numerical integration calculation method that uses random numbers to approximate the integration value. Consider the following calculation of the expectation value of f(x). Here, p(x) is a probability density function of x." }, { "code": null, "e": 1128, "s": 903, "text": "In this method, we choose n samples {x_i} (i=1,2,...,n) independent and identically distributed (i.i.d) from the probability identity function p(x). The integration value is approximated by the mean of f(x) for all sample x." }, { "code": null, "e": 1257, "s": 1128, "text": "From the law of large numbers, a limitation of the Monte Carlo integration when n →∞ converges to the expectation value of f(x)." }, { "code": null, "e": 1429, "s": 1257, "text": "Let’s calculate an approximate value of π with the Monte Carlo integration method. Consider a square with side-length 1 and a unit circle as shown in the following figure." }, { "code": null, "e": 1666, "s": 1429, "text": "The area of the circle is π. Now let f(x,y) be a function which outputs 1 when (x,y) lies inside the circle, and otherwise 0. Let p(x,y) be a uniform distribution on [-1,1]2. In this case, the area of the unit circle π can be written as" }, { "code": null, "e": 1840, "s": 1666, "text": "With Monte Carlo integration, this integration (π) can be approximate by using i.i.d samples from p(x,y). n_(in circle) is the number of samples that lie in the unit circle." }, { "code": null, "e": 1934, "s": 1840, "text": "The following figure shows the convergence of Monte Carlo integration when n is large enough." }, { "code": null, "e": 2454, "s": 1934, "text": "With the Monte Carlo integration, we can simply compute the integration value with random numbers. However, the problem is “how to generate random numbers?” Of course, if the probability distribution is a well-known one, uniform distribution, Gaussian distribution, for example, we can easily implement the random number generator with some library. What if we have to generate random numbers from a distribution density function that is not implemented in any library? To solve this problem, sampling methods are used." }, { "code": null, "e": 2843, "s": 2454, "text": "A frequently used method is Importance Sampling. In this method, a proxy distribution is introduced to sample random numbers from any distribution. In most cases, we choose a well-known distribution such as Gaussian distribution, uniform distribution as a proxy distribution. The main concept of this method can be simply written in the following form, where q(x) is a proxy distribution." }, { "code": null, "e": 3117, "s": 2843, "text": "With Importance Sampling, instead of generating random numbers from p(x), we choose i.i.d samples {x’_i} (i=1,2,...,n) from a proxy distribution q(x) and approximate the integration value with the following calculation. Here, p(x)/q(x) is called importance of the sampling." }, { "code": null, "e": 3482, "s": 3117, "text": "Now, let’s use a Laplace distribution’ variance calculation as an example. Consider f(x)=x2 and a probability density function p(x)=1/2 Exp(-|x|). The distribution with density function like p(x) is called Laplace distribution. If we choose a uniform distribution as a proxy distribution, the variance of the Laplace distribution can be approximately calculated by" }, { "code": null, "e": 3644, "s": 3482, "text": "With paper and a pencil, we can easily calculate the Var[x]. The value of this calculation is 2. Now, let’s confirm the result of the Importance Sampling method." }, { "code": null, "e": 3906, "s": 3644, "text": "In Importance Sampling, we use random numbers (samples) generated from a proxy distribution to approximate the integration value. To directly generated samples from a distribution with any probability density function, I introduce the following sampling method." }, { "code": null, "e": 4554, "s": 3906, "text": "In Inverse Transform Sampling method, we use a random number u generated from a 1-dimensional uniform distribution to generate a random number x of any 1-dimensional probability density function p(x). In this case, we use the inverse function of the cumulative distribution function of p(x). If the cumulative distribution function of p(x) is P(x), then the inverse function of u=P(x) is x =P^-1 (u). Now, x = P^-1 (u) has p(x) as probability density function on [0,1]. Therefore, with n samples from uniform distribution on [0,1] {u_i} (i=1,2,...,n), we can generate n sample of p(x) distribution {x_i} (i=1,2,...,n) by calculate x_i = P^-1(u_i)." }, { "code": null, "e": 4888, "s": 4554, "text": "Again, let's consider the Laplace distribution’s variance calculation as an example. This time we directly generate random numbers (samples) from the Laplace distribution’s probability density function using the Inverse Transform Sampling method. With these random numbers, we will again recalculate the approximated value of Var[x]." }, { "code": null, "e": 4927, "s": 4888, "text": "Let’s check the result of this method." }, { "code": null, "e": 5056, "s": 4927, "text": "The following figure shows the approximated value of Laplace distribution variance V[x] using Inverse Transform Sampling method." }, { "code": null, "e": 5433, "s": 5056, "text": "From this result, it is straight forward that using directly generated random numbers from a distribution offers a better approximation compared to a case of proxy distribution. However, with the Inverse Transform Sampling method, it is impossible to directly generate random numbers from only 2 or higher dimension distribution. To do this, Rejection Sampling method is used." }, { "code": null, "e": 5801, "s": 5433, "text": "The idea in Rejection Sampling is to use a proxy distribution (Gaussian or uniform distribution, etc.) called q(x) to generate a random number and use another uniform distribution to evaluate the generated sample whether or not to accept it as a sample generated from p(x). With this method, we can also generate random numbers from a higher dimensional distribution." }, { "code": null, "e": 5961, "s": 5801, "text": "As preparation in generating random numbers with this method, we need to know a finite value of L where max[p(x)/q(x)] < L. Here, q(x) is a proxy distribution." }, { "code": null, "e": 6067, "s": 5961, "text": "First, we generate a random number x’ from a proxy distribution q(x). This x’ is called a proposal point." }, { "code": null, "e": 6243, "s": 6067, "text": "Next, generate a random number v from a uniform distribution on [0, L]. This v will be used to evaluate the proposal point, whether to be fine considering generated from p(x)." }, { "code": null, "e": 6343, "s": 6243, "text": "If v ≤ p(x’)/q(x’), then x’ is accepted as a random number generated by p(x), else, x’ is rejected." }, { "code": null, "e": 6415, "s": 6343, "text": "The algorithm in generating n random numbers with Rejection Sampling is" }, { "code": null, "e": 6540, "s": 6415, "text": "Result on random number generating and Laplace distribution variance calculation (Proxy distribution: Gaussian distribution)" }, { "code": null, "e": 7016, "s": 6540, "text": "In the Rejection sampling method, it is impossible to generate random numbers when the upper boundary L is not known. MCMC method is an effective solution to this problem. MCMC method uses the concept of a stochastic process (Markov chain in this case). In this case, the generation of i-th sample x_i depends on the previous sample x_(i-1). x1, x2, ...,xn with this concept is called a Markov chain. Here, I introduce one of the MCMC methods, the Metropolis-Hastings method." }, { "code": null, "e": 7257, "s": 7016, "text": "The process in this method is similar to Rejection sampling. But here, a proxy distribution density function is represented by a conditional probability q(x|x_i), and the evaluation index v is generated from a uniform distribution on [0,1]." }, { "code": null, "e": 7367, "s": 7257, "text": "First, we generate a random number x’ from a proxy distribution q(x|x_i). This x’ is called a proposal point." }, { "code": null, "e": 7543, "s": 7367, "text": "Next, generate a random number v from a uniform distribution on [0, 1]. This v will be used to evaluate the proposal point, whether to be fine considering generated from p(x)." }, { "code": null, "e": 7664, "s": 7543, "text": "If v ≤ p(x’)q(x_i|x’)/(p(x_i)q(x’|x_i)), then x’ is accepted as a random number generated by p(x), else, x’ is rejected." }, { "code": null, "e": 7736, "s": 7664, "text": "The algorithm in generating n random numbers with Rejection Sampling is" }, { "code": null, "e": 7861, "s": 7736, "text": "Result on random number generating and Laplace distribution variance calculation (Proxy distribution: Gaussian distribution)" }, { "code": null, "e": 7921, "s": 7861, "text": "import randomimport numpy as npfrom scipy.stats import norm" }, { "code": null, "e": 8181, "s": 7921, "text": "def f(x,y): if (x*x+y*y<=1): return 1 else: return 0n = 10N = []P = []while n <= 100000: s = np.random.uniform(-1,1,(n,2)) nn = 0 for x in s: nn+=f(x[0],x[1]) pi = 4*nn/n N.append(n) P.append(pi) n = n*2" }, { "code": null, "e": 8474, "s": 8181, "text": "def f(x): return x*xdef p_pdf(x): return 0.5*np.exp(-abs(x))def imp_pdf(x): return norm.pdf(x)n = 10N = []P = []while n <= 100000: s = np.random.normal(0,1,n) nn = 0 for x in s: nn+=f(x)*p_pdf(x)/imp_pdf(x) p = nn/n N.append(n) P.append(p) n = n*2" }, { "code": null, "e": 9671, "s": 8474, "text": "def sgn(x): if x>0: return 1 elif x==0: return 0 else: return -1 def p_laplace(x): return 0.5*np.exp(-abs(x))#def P_laplace_cum(x): #return 0.5*((1+sgn(x))(1-np.exp(-abs(x))))def P_laplace_inv(u): k = 1-2*abs(u-0.5) return -1*sgn(u-0.5)*np.log(k)# random number generatordef reverse_generator(X): res = [] for u in X: res.append(P_laplace_inv(u)) return resn_sample = 50s = np.random.uniform(0,1,n_sample)theta = reverse_generator(s) print(\"n_sample = \",n_sample)gen_xx =random.sample(theta,n_sample)plt.scatter(gen_xx,[0]*n_sample,marker='x')xx=np.linspace(-15,15,1000)plt.plot(xx,[p_laplace(i) for i in xx],c='red')plt.legend(['Laplace Distribution','generated number'])plt.title(\"Random Numbers directly generated from p(x)\")plt.show()# Laplace distribution variance calculationN = []P = []n= 10while n <= 100000: s = np.random.uniform(0,1,n) theta = reverse_generator(s) p = 0 for x in theta: p += x*x N.append(n) P.append(p/n) n = n*2 P_r = [2]*len(N)plt.plot(N,P)plt.plot(N,P_r,c='red')plt.legend([\"Inverse Transform Sampling value\",\"true value(2)\"])plt.xlabel(\"number of samples (n) \")plt.show()" }, { "code": null, "e": 10761, "s": 9671, "text": "def p_laplace(x): return 0.5*np.exp(-abs(x))def p_proxy(x): return norm.pdf(x)# random number generatordef rejection_generator(n): xx = np.linspace(0,1,100) K = max(p_laplace(xx)/p_proxy(xx))+1 random_samples = [] while len(random_samples) < n: proposal = np.random.randn() v = np.random.uniform(0,K) if v <= (p_laplace(proposal)/p_proxy(proposal)): random_samples.append(proposal) return random_samplesprint(\"generating...\")random_samples = rejection_generator(n=50)print(\"n_sample = \",len(random_samples))plt.scatter(random_samples,[0]*len(random_samples),marker='x')xx=np.linspace(-15,15,1000)plt.plot(xx,[p_laplace(i) for i in xx],c='red')plt.legend(['true','gen'])plt.show()# Laplace distribution variance calculationN = []P = []n= 10while n <= 100000: theta = rejection_generator(n) p = 0 for x in theta: p += x*x N.append(n) P.append(p/n) n = n*2 P_r = [2]*len(N)plt.plot(N,P)plt.plot(N,P_r,c='red')plt.legend([\"Rejection Sampling value\",\"true value(2)\"])plt.xlabel(\"number of samples (n) \")plt.show()" }, { "code": null, "e": 11817, "s": 10761, "text": "def p_laplace(x): return 0.5*np.exp(-abs(x))def p_proxy(x,theta,sigma): return norm.pdf(x,theta,sigma)def MCMC_generator(n): random_samples = [] theta_i = 0 while len(random_samples) < n: proposal = np.random.normal(loc=theta_i,scale=1) v = np.random.uniform(0,1) a = p_laplace(proposal)*p_proxy(theta_i,proposal,1) b = p_laplace(theta_i)*p_proxy(proposal,theta_i,1) if v <= (a/b): random_samples.append(proposal) theta_i = proposal return random_samplesn = 50random_samples = MCMC_generator(n)print(\"n_sample = \",n)plt.scatter(random_samples,[0]*n,marker='x')xx=np.linspace(-15,15,1000)plt.plot(xx,[p_laplace(i) for i in xx],c='red')plt.legend(['true','gen'])plt.show()N = []P = []n= 10while n <= 10000: theta = MCMC_generator(n=n) p = 0 for x in theta: p += x*x N.append(n) P.append(p/n) n = n*2 P_r = [2]*len(N)plt.plot(N,P)plt.plot(N,P_r,c='red')plt.legend([\"Rejection Sampling value\",\"true value(2)\"])plt.xlabel(\"number of samples (n) \")plt.show()" }, { "code": null, "e": 11923, "s": 11817, "text": "M.Yamasugi. Statistical Machine Learning-generative model-based pattern recognition-. Ohmsha, Japan, 2019" } ]
What is tri state checkBox, How to create a tri state checkBox in JavaFX?
A checkbox is a type of selection control, which is square in shape with a tick mark int it. Generally, a checkbox has two states checked and unchecked. Depending on the GUI (technology) we can also have a third state named undefined/undetermined, which indicates the state of the current checkbox is neither checked nor unchecked. JavaFX supports tristate checkboxes, the javafx.scene.control.CheckBox class represents a checkbox and it contains three boolean properties − allowIndeterminate − This property specifies whether a checkbox should have all the three states. You can set the value to this property using the setAllowIndeterminate() method. allowIndeterminate − This property specifies whether a checkbox should have all the three states. You can set the value to this property using the setAllowIndeterminate() method. indeterminate − This property specifies whether a checkbox is in undefined states. You can set the value to this property using the setIndeterminate() method. indeterminate − This property specifies whether a checkbox is in undefined states. You can set the value to this property using the setIndeterminate() method. selected − This property specifies whether the current checkbox is selected. You can set the value to this property using the setSelected() method. selected − This property specifies whether the current checkbox is selected. You can set the value to this property using the setSelected() method. To toggle through all the three states − Instantiate the CheckBox class. Instantiate the CheckBox class. Invoke the setAllowIndeterminate() method by passing the boolean value true as an argument. Invoke the setAllowIndeterminate() method by passing the boolean value true as an argument. Invoke the setIndeterminate() method by passing the boolean value true as an argument. Invoke the setIndeterminate() method by passing the boolean value true as an argument. Add the created checkbox to the parent node. Add the created checkbox to the parent node. import javafx.application.Application; import javafx.geometry.Insets; import javafx.scene.Scene; import javafx.scene.control.CheckBox; import javafx.scene.control.Label; import javafx.scene.layout.VBox; import javafx.scene.paint.Color; import javafx.scene.text.Font; import javafx.scene.text.FontPosture; import javafx.scene.text.FontWeight; import javafx.stage.Stage; public class CheckBox_Undefined_State extends Application { public void start(Stage stage) { //Creating the check boxes CheckBox checkBox1 = new CheckBox("Salary"); CheckBox checkBox2 = new CheckBox("Over Time Allowence"); CheckBox checkBox3 = new CheckBox("Bonus"); CheckBox checkBox4 = new CheckBox("Night Shift Allowence"); Label label = new Label("Select Recieved Allowences:"); Font font = Font.font("verdana", FontWeight.BOLD, FontPosture.REGULAR, 12); label.setFont(font); //Setting the indeterminate state true checkBox2.setAllowIndeterminate(true); checkBox2.setIndeterminate(true); checkBox4.setAllowIndeterminate(true); checkBox4.setIndeterminate(true); //Adding the toggle button to the pane VBox vBox = new VBox(5); vBox.setPadding(new Insets(5, 5, 5, 50)); vBox.getChildren().addAll(label, checkBox1, checkBox2, checkBox3, checkBox4); //Setting the stage Scene scene = new Scene(vBox, 595, 150, Color.BEIGE); stage.setTitle("Check Box Example"); stage.setScene(scene); stage.show(); } public static void main(String args[]){ launch(args); } }
[ { "code": null, "e": 1215, "s": 1062, "text": "A checkbox is a type of selection control, which is square in shape with a tick mark int it. Generally, a checkbox has two states checked and unchecked." }, { "code": null, "e": 1394, "s": 1215, "text": "Depending on the GUI (technology) we can also have a third state named undefined/undetermined, which indicates the state of the current checkbox is neither checked nor unchecked." }, { "code": null, "e": 1536, "s": 1394, "text": "JavaFX supports tristate checkboxes, the javafx.scene.control.CheckBox class represents a checkbox and it contains three boolean properties −" }, { "code": null, "e": 1715, "s": 1536, "text": "allowIndeterminate − This property specifies whether a checkbox should have all the three states. You can set the value to this property using the setAllowIndeterminate() method." }, { "code": null, "e": 1894, "s": 1715, "text": "allowIndeterminate − This property specifies whether a checkbox should have all the three states. You can set the value to this property using the setAllowIndeterminate() method." }, { "code": null, "e": 2053, "s": 1894, "text": "indeterminate − This property specifies whether a checkbox is in undefined states. You can set the value to this property using the setIndeterminate() method." }, { "code": null, "e": 2212, "s": 2053, "text": "indeterminate − This property specifies whether a checkbox is in undefined states. You can set the value to this property using the setIndeterminate() method." }, { "code": null, "e": 2360, "s": 2212, "text": "selected − This property specifies whether the current checkbox is selected. You can set the value to this property using the setSelected() method." }, { "code": null, "e": 2508, "s": 2360, "text": "selected − This property specifies whether the current checkbox is selected. You can set the value to this property using the setSelected() method." }, { "code": null, "e": 2549, "s": 2508, "text": "To toggle through all the three states −" }, { "code": null, "e": 2581, "s": 2549, "text": "Instantiate the CheckBox class." }, { "code": null, "e": 2613, "s": 2581, "text": "Instantiate the CheckBox class." }, { "code": null, "e": 2705, "s": 2613, "text": "Invoke the setAllowIndeterminate() method by passing the boolean value true as an argument." }, { "code": null, "e": 2797, "s": 2705, "text": "Invoke the setAllowIndeterminate() method by passing the boolean value true as an argument." }, { "code": null, "e": 2884, "s": 2797, "text": "Invoke the setIndeterminate() method by passing the boolean value true as an argument." }, { "code": null, "e": 2971, "s": 2884, "text": "Invoke the setIndeterminate() method by passing the boolean value true as an argument." }, { "code": null, "e": 3016, "s": 2971, "text": "Add the created checkbox to the parent node." }, { "code": null, "e": 3061, "s": 3016, "text": "Add the created checkbox to the parent node." }, { "code": null, "e": 4637, "s": 3061, "text": "import javafx.application.Application;\nimport javafx.geometry.Insets;\nimport javafx.scene.Scene;\nimport javafx.scene.control.CheckBox;\nimport javafx.scene.control.Label;\nimport javafx.scene.layout.VBox;\nimport javafx.scene.paint.Color;\nimport javafx.scene.text.Font;\nimport javafx.scene.text.FontPosture;\nimport javafx.scene.text.FontWeight;\nimport javafx.stage.Stage;\npublic class CheckBox_Undefined_State extends Application {\n public void start(Stage stage) {\n //Creating the check boxes\n CheckBox checkBox1 = new CheckBox(\"Salary\");\n CheckBox checkBox2 = new CheckBox(\"Over Time Allowence\");\n CheckBox checkBox3 = new CheckBox(\"Bonus\");\n CheckBox checkBox4 = new CheckBox(\"Night Shift Allowence\");\n Label label = new Label(\"Select Recieved Allowences:\");\n Font font = Font.font(\"verdana\", FontWeight.BOLD, FontPosture.REGULAR, 12);\n label.setFont(font);\n //Setting the indeterminate state true\n checkBox2.setAllowIndeterminate(true);\n checkBox2.setIndeterminate(true);\n checkBox4.setAllowIndeterminate(true);\n checkBox4.setIndeterminate(true);\n //Adding the toggle button to the pane\n VBox vBox = new VBox(5);\n vBox.setPadding(new Insets(5, 5, 5, 50));\n vBox.getChildren().addAll(label, checkBox1, checkBox2, checkBox3, checkBox4);\n //Setting the stage\n Scene scene = new Scene(vBox, 595, 150, Color.BEIGE);\n stage.setTitle(\"Check Box Example\");\n stage.setScene(scene);\n stage.show();\n }\n public static void main(String args[]){\n launch(args);\n }\n}" } ]
How to check an array is associative or sequential in PHP? - GeeksforGeeks
24 Sep, 2018 In PHP there is no need to write the variable type before the variable because it is loosely-typed. It takes datatype from user defined values that are stored in it. Arrays in PHP is a type of data structure that allows to store multiple elements of similar data type under a single variable thereby saving the effort of creating a different variable for every data.There are basically three types of arrays in PHP: Sequential (Indexed) arrays Associative arrays Multidimensional arrays Sequential Arrays: Those arrays which have numerical indexes in an ordered sequential manner (starting from 0 and ending with n-1) are called Sequential or Indexed arrays. In PHP, by default array Indexed array. <?php// Example of sequential array $arr = array("January", "February", "March"); // 1st elementecho $arr[0] . "\n"; // 2nd elementecho $arr[1] . "\n"; // 3rd element echo $arr[2] . "\n";?> January February March Associative arrays: The arrays which are having string type keys instead of indexes or which exist in (‘key’, ‘value’)pairs are called associative arrays. <?php// Example of associative array $arr1= array("Month1" => "January", "Month2" => "February", "Month3" => "March" ); echo $arr1["Month1"] . "\n";echo $arr1["Month2"] . "\n";echo $arr1["Month3"] . "\n";?> January February March How to check if PHP array is associative or sequential?There is no inbuilt method in PHP to know the type of array. If the sequential array contains n elements then their index lies between 0 to (n-1). So find the array key value and check if it exist in 0 to (n-1) then it is sequential otherwise associative array. <?php// Example to check Sequential array // Associative array$arr1= array("Month1" => "January", "Month2" => "February", "Month3" => "March" ); // Checking for sequential keys of array arrif(array_keys($arr1) !== range(0, count($arr1) - 1)) echo "Array is associative"; else echo "Array is sequential \n";?> Array is associative Note: === It returns True if $x and $y are equal and same type. !== It returns True if $x and $y are not equal or not same type. == It returns True if $x and $y are equal. != It returns True if $x not equal to $y. Picked PHP PHP Programs Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to fetch data from localserver database and display on HTML table using PHP ? PHP str_replace() Function How to create admin login page using PHP? Different ways for passing data to view in Laravel Create a drop-down list that options fetched from a MySQL database in PHP How to call PHP function on the click of a Button ? How to fetch data from localserver database and display on HTML table using PHP ? How to create admin login page using PHP? How to pass form variables from one page to other page in PHP ? PHP | Ternary Operator
[ { "code": null, "e": 26217, "s": 26189, "text": "\n24 Sep, 2018" }, { "code": null, "e": 26633, "s": 26217, "text": "In PHP there is no need to write the variable type before the variable because it is loosely-typed. It takes datatype from user defined values that are stored in it. Arrays in PHP is a type of data structure that allows to store multiple elements of similar data type under a single variable thereby saving the effort of creating a different variable for every data.There are basically three types of arrays in PHP:" }, { "code": null, "e": 26661, "s": 26633, "text": "Sequential (Indexed) arrays" }, { "code": null, "e": 26680, "s": 26661, "text": "Associative arrays" }, { "code": null, "e": 26704, "s": 26680, "text": "Multidimensional arrays" }, { "code": null, "e": 26916, "s": 26704, "text": "Sequential Arrays: Those arrays which have numerical indexes in an ordered sequential manner (starting from 0 and ending with n-1) are called Sequential or Indexed arrays. In PHP, by default array Indexed array." }, { "code": "<?php// Example of sequential array $arr = array(\"January\", \"February\", \"March\"); // 1st elementecho $arr[0] . \"\\n\"; // 2nd elementecho $arr[1] . \"\\n\"; // 3rd element echo $arr[2] . \"\\n\";?>", "e": 27114, "s": 26916, "text": null }, { "code": null, "e": 27138, "s": 27114, "text": "January\nFebruary\nMarch\n" }, { "code": null, "e": 27293, "s": 27138, "text": "Associative arrays: The arrays which are having string type keys instead of indexes or which exist in (‘key’, ‘value’)pairs are called associative arrays." }, { "code": "<?php// Example of associative array $arr1= array(\"Month1\" => \"January\", \"Month2\" => \"February\", \"Month3\" => \"March\" ); echo $arr1[\"Month1\"] . \"\\n\";echo $arr1[\"Month2\"] . \"\\n\";echo $arr1[\"Month3\"] . \"\\n\";?>", "e": 27534, "s": 27293, "text": null }, { "code": null, "e": 27558, "s": 27534, "text": "January\nFebruary\nMarch\n" }, { "code": null, "e": 27875, "s": 27558, "text": "How to check if PHP array is associative or sequential?There is no inbuilt method in PHP to know the type of array. If the sequential array contains n elements then their index lies between 0 to (n-1). So find the array key value and check if it exist in 0 to (n-1) then it is sequential otherwise associative array." }, { "code": "<?php// Example to check Sequential array // Associative array$arr1= array(\"Month1\" => \"January\", \"Month2\" => \"February\", \"Month3\" => \"March\" ); // Checking for sequential keys of array arrif(array_keys($arr1) !== range(0, count($arr1) - 1)) echo \"Array is associative\"; else echo \"Array is sequential \\n\";?>", "e": 28229, "s": 27875, "text": null }, { "code": null, "e": 28251, "s": 28229, "text": "Array is associative\n" }, { "code": null, "e": 28257, "s": 28251, "text": "Note:" }, { "code": null, "e": 28315, "s": 28257, "text": "=== It returns True if $x and $y are equal and same type." }, { "code": null, "e": 28380, "s": 28315, "text": "!== It returns True if $x and $y are not equal or not same type." }, { "code": null, "e": 28423, "s": 28380, "text": "== It returns True if $x and $y are equal." }, { "code": null, "e": 28465, "s": 28423, "text": "!= It returns True if $x not equal to $y." }, { "code": null, "e": 28472, "s": 28465, "text": "Picked" }, { "code": null, "e": 28476, "s": 28472, "text": "PHP" }, { "code": null, "e": 28489, "s": 28476, "text": "PHP Programs" }, { "code": null, "e": 28506, "s": 28489, "text": "Web Technologies" }, { "code": null, "e": 28510, "s": 28506, "text": "PHP" }, { "code": null, "e": 28608, "s": 28510, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28690, "s": 28608, "text": "How to fetch data from localserver database and display on HTML table using PHP ?" }, { "code": null, "e": 28717, "s": 28690, "text": "PHP str_replace() Function" }, { "code": null, "e": 28759, "s": 28717, "text": "How to create admin login page using PHP?" }, { "code": null, "e": 28810, "s": 28759, "text": "Different ways for passing data to view in Laravel" }, { "code": null, "e": 28884, "s": 28810, "text": "Create a drop-down list that options fetched from a MySQL database in PHP" }, { "code": null, "e": 28936, "s": 28884, "text": "How to call PHP function on the click of a Button ?" }, { "code": null, "e": 29018, "s": 28936, "text": "How to fetch data from localserver database and display on HTML table using PHP ?" }, { "code": null, "e": 29060, "s": 29018, "text": "How to create admin login page using PHP?" }, { "code": null, "e": 29124, "s": 29060, "text": "How to pass form variables from one page to other page in PHP ?" } ]
Access the elements of a Series in Pandas - GeeksforGeeks
06 Dec, 2018 Pandas Series is a one-dimensional labeled array capable of holding data of any type (integer, string, float, python objects, etc.). Labels need not be unique but must be a hashable type. Let’s discuss different ways to access the elements of given Pandas Series. First create a Pandas Series. # importing pandas module import pandas as pd # making data frame df = pd.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/nba.csv") ser = pd.Series(df['Name'])ser.head(10)# or simply df['Name'].head(10) Output: Example #1: Get the first element of series # importing pandas module import pandas as pd # making data frame df = pd.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/nba.csv") df['Name'].head(10) # get the first elementser[0] Output: Example #2: Access multiple elements by providing position of item # importing pandas module import pandas as pd # making data frame df = pd.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/nba.csv") df['Name'].head(10) # get multiple elements at given indexser[[0, 3, 6, 9]] Output: Example #3: Access first 5 elements in Series # importing pandas module import pandas as pd # making data frame df = pd.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/nba.csv") df['Name'].head(10) # get first five namesser[:5] Output: Example #4: Get last 10 elements in Series # importing pandas module import pandas as pd # making data frame df = pd.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/nba.csv") df['Name'].head(10) # get last 10 namesser[-10:] Output: Example #5: Access multiple elements by providing label of index # importing pandas module import pandas as pd import numpy as np ser = pd.Series(np.arange(3, 15), index = list("abcdefghijkl")) ser[['a', 'd', 'g', 'l']] Output: pandas-series-program Python pandas-series Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() Reading and Writing to text files in Python *args and **kwargs in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 26311, "s": 26283, "text": "\n06 Dec, 2018" }, { "code": null, "e": 26499, "s": 26311, "text": "Pandas Series is a one-dimensional labeled array capable of holding data of any type (integer, string, float, python objects, etc.). Labels need not be unique but must be a hashable type." }, { "code": null, "e": 26575, "s": 26499, "text": "Let’s discuss different ways to access the elements of given Pandas Series." }, { "code": null, "e": 26605, "s": 26575, "text": "First create a Pandas Series." }, { "code": "# importing pandas module import pandas as pd # making data frame df = pd.read_csv(\"https://media.geeksforgeeks.org/wp-content/uploads/nba.csv\") ser = pd.Series(df['Name'])ser.head(10)# or simply df['Name'].head(10)", "e": 26827, "s": 26605, "text": null }, { "code": null, "e": 26879, "s": 26827, "text": "Output: Example #1: Get the first element of series" }, { "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['Name'].head(10) # get the first elementser[0]", "e": 27081, "s": 26879, "text": null }, { "code": null, "e": 27089, "s": 27081, "text": "Output:" }, { "code": null, "e": 27157, "s": 27089, "text": " Example #2: Access multiple elements by providing position of item" }, { "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['Name'].head(10) # get multiple elements at given indexser[[0, 3, 6, 9]]", "e": 27385, "s": 27157, "text": null }, { "code": null, "e": 27439, "s": 27385, "text": "Output: Example #3: Access first 5 elements in Series" }, { "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['Name'].head(10) # get first five namesser[:5]", "e": 27641, "s": 27439, "text": null }, { "code": null, "e": 27692, "s": 27641, "text": "Output: Example #4: Get last 10 elements in Series" }, { "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['Name'].head(10) # get last 10 namesser[-10:]", "e": 27893, "s": 27692, "text": null }, { "code": null, "e": 27966, "s": 27893, "text": "Output: Example #5: Access multiple elements by providing label of index" }, { "code": "# importing pandas module import pandas as pd import numpy as np ser = pd.Series(np.arange(3, 15), index = list(\"abcdefghijkl\")) ser[['a', 'd', 'g', 'l']]", "e": 28123, "s": 27966, "text": null }, { "code": null, "e": 28131, "s": 28123, "text": "Output:" }, { "code": null, "e": 28153, "s": 28131, "text": "pandas-series-program" }, { "code": null, "e": 28174, "s": 28153, "text": "Python pandas-series" }, { "code": null, "e": 28188, "s": 28174, "text": "Python-pandas" }, { "code": null, "e": 28195, "s": 28188, "text": "Python" }, { "code": null, "e": 28293, "s": 28195, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28311, "s": 28293, "text": "Python Dictionary" }, { "code": null, "e": 28346, "s": 28311, "text": "Read a file line by line in Python" }, { "code": null, "e": 28378, "s": 28346, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28400, "s": 28378, "text": "Enumerate() in Python" }, { "code": null, "e": 28442, "s": 28400, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28472, "s": 28442, "text": "Iterate over a list in Python" }, { "code": null, "e": 28498, "s": 28472, "text": "Python String | replace()" }, { "code": null, "e": 28542, "s": 28498, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 28571, "s": 28542, "text": "*args and **kwargs in Python" } ]
Largest subarray with 0 sum | Practice | GeeksforGeeks
Given an array having both positive and negative integers. The task is to compute the length of the largest subarray with sum 0. Example 1: Input: N = 8 A[] = {15,-2,2,-8,1,7,10,23} Output: 5 Explanation: The largest subarray with sum 0 will be -2 2 -8 1 7. Your Task: You just have to complete the function maxLen() which takes two arguments an array A and n, where n is the size of the array A and returns the length of the largest subarray with 0 sum. Expected Time Complexity: O(N). Expected Auxiliary Space: O(N). Constraints: 1 <= N <= 105 -1000 <= A[i] <= 1000, for each valid i 0 lunesco2 hours ago Python Total time taken: 0.38/1.46 def maxLen(self, n, arr): d = dict() suma = 0 maxi = 0 for i in range(n): suma += arr[i] if suma == 0: maxi = i + 1 continue if suma not in d: d[suma] = i else: if i - d[suma] > maxi: maxi = i - d[suma] return maxi 0 19065931 day ago //JAVA CODE Time taken is 1.69/2.32 class GfG{ int maxLen(int arr[], int n) { HashMap<Integer, Integer> mp = new HashMap<>();//first index will store prefix sum and the second wioll store the index till which the prefix sum is int sum =0;//variable sum is zero int maxi =0;//maxmum lenght sub array which will give the sum as 0 for(int i=0 ; i<n ; i++)//linearly iterating the array { sum = sum + arr[i];//keep adding the array to the sum if(sum == 0)//if it is zero then we can say that the4 sub array from the staring till the current index is giving the sum zero maxi = i+1;//if you currently standing at index i then it will be i+1 update it else { if(mp.get(sum)!=null)//if sum is not zero then check that sum does exist in the hash map or not maxi = Math.max(maxi , i - mp.get(sum));//if it does then get the index though this---> i - mp.get(sum) then compare with previous index if it exceed then update the maxi or els else mp.put(sum , i); //doest not then put it into the hashmap with index where the sum appears } } return maxi;//retun that }} 0 mayurxxivk1 day ago CorrectAnswer.⚡ Total Time Taken:1.62/2.32 int maxLen(int arr[], int n) { HashMap<Integer, Integer> mp = new HashMap<>(); int sum =0; int maxi =0; for(int i=0 ; i<n ; i++) { sum = sum + arr[i]; if(sum == 0) maxi = i+1; else { if(mp.get(sum)!=null) maxi = Math.max(maxi , i - mp.get(sum)); else mp.put(sum , i); } } return maxi; } 0 riteshthakare11912 days ago c++ code: int maxLen(vector<int>&arr, int n) { int maxlen=0; unordered_map<int,int> m;// prefix-sum,index m[0]=-1; int presum=0; for (int i=0;i<n;i++){ presum+=arr[i]; if (m.find(presum)!=m.end()){ int len=i-m[presum]; if (len>maxlen){ maxlen=len; } } else{ m[presum]=i; } } return maxlen; 0 shivaroy0855 days ago first we can have a intuition that we will keep the sum of the whole array one by one... s = 0 for i in range(n): s = s+ arr[i] eg: 0 1 2 3 #index 1 , -1 , 1, -1 #numbers now at index 1 the sum is zero and at index 3 the sum will be zero therefore at index 1 the sub array length will be (i+1) i.e 1+1 = 2 and at index 3 the sub array length will be (i+1) i.e 3+1 = 4 max(of them is) 4 so the ans will be 4.... m = 0 #define before loop statrs .....loop.... if s == 0: m = i+1 but if the array is arranged in such a manner that there is no subsequent element sum which will give 0. then we need to create a hash table to keep the subsequent sum into it with their index, if we find a repeating sum ones again that means that from the position of that sum number till now the sub array sum is zero, 0 eg: 0 1 2 3 4 1 -1 3 2 -2 from 0th index to 1 index we find sum == 0 then we know that 2 is the max sub array length till now, now on 2nd index we find 3 adding all till 2nd index never gives 0, we check hash map, 3 not in hash map we insert 3 with the index 2, we continue, we then find +2 after adding we get 5 , similarly 5 was not in hash map so we add it with index 3, n3xt we add -2 and we again get now, as 3 is already in hash map that means from 2nd index till 4th whatever we added will lead to 0...... BAM!!!! therefore we find the difference (distance ) and check the max of them till now, else: / THIS if s in dic: / P m = max(m,i-dic[s]) / A else: / R dic[s] = i / T SOLUTION: class Solution: def maxLen(self, n, arr): #Code here dic = {} s = 0 m= 0 for i in range(n): s = s+ arr[i] if s == 0: m = i+1 else: if s in dic: m = max(m,i-dic[s]) else: dic[s] = i return m 0 abhishekmaurya56671 week ago class Solution{ public: int maxLen(vector<int>&nums, int n) { unordered_map<int,int> map; int sum=0; int len=0; map[0]=-1; for(int i=0;i<n;i++){ sum+=nums[i]; if(map.find(sum)!=map.end()){ len=max(len,i-(int)map[sum]); } else{ map[sum]=i; } } return len; } }; 0 abhishekmaurya5667 This comment was deleted. 0 19bcs13141 week ago class GfG { int maxLen(int arr[], int n) { // Your code here Map<Integer,Integer> map=new HashMap<>(); int sum=0; int len=0; map.put(0,-1); for(int i=0;i<n;i++){ sum+=arr[i]; if(map.containsKey(sum)==false){ map.put(sum,i); }else{ int index=map.get(sum); len=Math.max(len,i-index); } } return len; } } 0 saisaran21 week ago using unordered map in c++ class Solution{ public: int maxLen(vector<int>&A, int n) { int s=0; for(int i=0;i<n;i++) { s=s+A[i]; A[i]=s; } unordered_map<int,int>u; for(int i=0;i<n;i++) { u[A[i]]=i; } int mx=0; for(int i=0;i<n;i++) { if(u.find(A[i])!=u.end()) { mx=max(mx,u[A[i]]-i); } if(A[i]==0) { mx=max(mx,i+1); } } return mx; }}; 0 2016yashpratap1 week ago // Easiest java solution class GfG{ int maxLen(int arr[], int n) //store sum as key and index as value in the hashmap { HashMap<Integer,Integer> hm = new HashMap<>(); int sum =0; int mlen = 0; int i =-1; //initialize hashmap with key =0 and value as -1 hm.put(sum,i); while(i<arr.length-1) { i++; sum = sum +arr[i]; //if sum is not present in the list then put in the map if(hm.containsKey(sum)==false) hm.put(sum,i); else { int len = i - hm.get(sum); if(len>mlen) mlen = len; } } return mlen; }} 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": 367, "s": 238, "text": "Given an array having both positive and negative integers. The task is to compute the length of the largest subarray with sum 0." }, { "code": null, "e": 378, "s": 367, "text": "Example 1:" }, { "code": null, "e": 496, "s": 378, "text": "Input:\nN = 8\nA[] = {15,-2,2,-8,1,7,10,23}\nOutput: 5\nExplanation: The largest subarray with\nsum 0 will be -2 2 -8 1 7." }, { "code": null, "e": 693, "s": 496, "text": "Your Task:\nYou just have to complete the function maxLen() which takes two arguments an array A and n, where n is the size of the array A and returns the length of the largest subarray with 0 sum." }, { "code": null, "e": 757, "s": 693, "text": "Expected Time Complexity: O(N).\nExpected Auxiliary Space: O(N)." }, { "code": null, "e": 824, "s": 757, "text": "Constraints:\n1 <= N <= 105\n-1000 <= A[i] <= 1000, for each valid i" }, { "code": null, "e": 826, "s": 824, "text": "0" }, { "code": null, "e": 845, "s": 826, "text": "lunesco2 hours ago" }, { "code": null, "e": 852, "s": 845, "text": "Python" }, { "code": null, "e": 880, "s": 852, "text": "Total time taken: 0.38/1.46" }, { "code": null, "e": 1311, "s": 880, "text": "def maxLen(self, n, arr):\n d = dict()\n suma = 0\n maxi = 0\n \n for i in range(n):\n suma += arr[i]\n \n if suma == 0:\n maxi = i + 1\n continue\n \n if suma not in d:\n d[suma] = i\n else:\n if i - d[suma] > maxi:\n maxi = i - d[suma]\n \n return maxi" }, { "code": null, "e": 1313, "s": 1311, "text": "0" }, { "code": null, "e": 1330, "s": 1313, "text": "19065931 day ago" }, { "code": null, "e": 1342, "s": 1330, "text": "//JAVA CODE" }, { "code": null, "e": 1366, "s": 1342, "text": "Time taken is 1.69/2.32" }, { "code": null, "e": 2605, "s": 1366, "text": "class GfG{ int maxLen(int arr[], int n) { HashMap<Integer, Integer> mp = new HashMap<>();//first index will store prefix sum and the second wioll store the index till which the prefix sum is int sum =0;//variable sum is zero int maxi =0;//maxmum lenght sub array which will give the sum as 0 for(int i=0 ; i<n ; i++)//linearly iterating the array { sum = sum + arr[i];//keep adding the array to the sum if(sum == 0)//if it is zero then we can say that the4 sub array from the staring till the current index is giving the sum zero maxi = i+1;//if you currently standing at index i then it will be i+1 update it else { if(mp.get(sum)!=null)//if sum is not zero then check that sum does exist in the hash map or not maxi = Math.max(maxi , i - mp.get(sum));//if it does then get the index though this---> i - mp.get(sum) then compare with previous index if it exceed then update the maxi or els else mp.put(sum , i); //doest not then put it into the hashmap with index where the sum appears } } return maxi;//retun that }}" }, { "code": null, "e": 2607, "s": 2605, "text": "0" }, { "code": null, "e": 2627, "s": 2607, "text": "mayurxxivk1 day ago" }, { "code": null, "e": 2643, "s": 2627, "text": "CorrectAnswer.⚡" }, { "code": null, "e": 2670, "s": 2643, "text": "Total Time Taken:1.62/2.32" }, { "code": null, "e": 3228, "s": 2672, "text": " int maxLen(int arr[], int n)\n {\n \n HashMap<Integer, Integer> mp = new HashMap<>();\n \n int sum =0;\n int maxi =0;\n \n for(int i=0 ; i<n ; i++)\n {\n sum = sum + arr[i];\n \n if(sum == 0)\n maxi = i+1;\n \n else\n {\n if(mp.get(sum)!=null)\n maxi = Math.max(maxi , i - mp.get(sum));\n \n else\n mp.put(sum , i); \n }\n }\n return maxi;\n }" }, { "code": null, "e": 3230, "s": 3228, "text": "0" }, { "code": null, "e": 3258, "s": 3230, "text": "riteshthakare11912 days ago" }, { "code": null, "e": 3268, "s": 3258, "text": "c++ code:" }, { "code": null, "e": 3740, "s": 3268, "text": "int maxLen(vector<int>&arr, int n) { int maxlen=0; unordered_map<int,int> m;// prefix-sum,index m[0]=-1; int presum=0; for (int i=0;i<n;i++){ presum+=arr[i]; if (m.find(presum)!=m.end()){ int len=i-m[presum]; if (len>maxlen){ maxlen=len; } } else{ m[presum]=i; } } return maxlen;" }, { "code": null, "e": 3742, "s": 3740, "text": "0" }, { "code": null, "e": 3764, "s": 3742, "text": "shivaroy0855 days ago" }, { "code": null, "e": 3853, "s": 3764, "text": "first we can have a intuition that we will keep the sum of the whole array one by one..." }, { "code": null, "e": 3861, "s": 3855, "text": "s = 0" }, { "code": null, "e": 3904, "s": 3861, "text": "for i in range(n): s = s+ arr[i]" }, { "code": null, "e": 3939, "s": 3906, "text": "eg: 0 1 2 3 #index" }, { "code": null, "e": 3976, "s": 3939, "text": " 1 , -1 , 1, -1 #numbers" }, { "code": null, "e": 4175, "s": 3976, "text": "now at index 1 the sum is zero and at index 3 the sum will be zero therefore at index 1 the sub array length will be (i+1) i.e 1+1 = 2 and at index 3 the sub array length will be (i+1) i.e 3+1 = 4 " }, { "code": null, "e": 4220, "s": 4177, "text": "max(of them is) 4 so the ans will be 4...." }, { "code": null, "e": 4263, "s": 4220, "text": " m = 0 #define before loop statrs" }, { "code": null, "e": 4279, "s": 4263, "text": " .....loop...." }, { "code": null, "e": 4316, "s": 4281, "text": " if s == 0: m = i+1" }, { "code": null, "e": 4514, "s": 4318, "text": "but if the array is arranged in such a manner that there is no subsequent element sum which will give 0. then we need to create a hash table to keep the subsequent sum into it with their index, " }, { "code": null, "e": 4651, "s": 4518, "text": " if we find a repeating sum ones again that means that from the position of that sum number till now the sub array sum is zero, 0" }, { "code": null, "e": 4677, "s": 4651, "text": "eg: 0 1 2 3 4 " }, { "code": null, "e": 4705, "s": 4677, "text": " 1 -1 3 2 -2" }, { "code": null, "e": 4875, "s": 4705, "text": " from 0th index to 1 index we find sum == 0 then we know that 2 is the max sub array length till now, now on 2nd index we find 3 adding all till 2nd index never gives 0," }, { "code": null, "e": 5202, "s": 4875, "text": "we check hash map, 3 not in hash map we insert 3 with the index 2, we continue, we then find +2 after adding we get 5 , similarly 5 was not in hash map so we add it with index 3, n3xt we add -2 and we again get now, as 3 is already in hash map that means from 2nd index till 4th whatever we added will lead to 0...... BAM!!!!" }, { "code": null, "e": 5286, "s": 5204, "text": "therefore we find the difference (distance ) and check the max of them till now," }, { "code": null, "e": 5633, "s": 5286, "text": " else: / THIS if s in dic: / P m = max(m,i-dic[s]) / A else: / R dic[s] = i / T" }, { "code": null, "e": 5645, "s": 5635, "text": "SOLUTION:" }, { "code": null, "e": 5989, "s": 5649, "text": "class Solution: def maxLen(self, n, arr): #Code here dic = {} s = 0 m= 0 for i in range(n): s = s+ arr[i] if s == 0: m = i+1 else: if s in dic: m = max(m,i-dic[s]) else: dic[s] = i return m" }, { "code": null, "e": 5991, "s": 5989, "text": "0" }, { "code": null, "e": 6020, "s": 5991, "text": "abhishekmaurya56671 week ago" }, { "code": null, "e": 6472, "s": 6020, "text": "class Solution{\n public:\n int maxLen(vector<int>&nums, int n)\n { \n unordered_map<int,int> map;\n int sum=0;\n int len=0;\n map[0]=-1;\n for(int i=0;i<n;i++){\n sum+=nums[i];\n \n if(map.find(sum)!=map.end()){\n len=max(len,i-(int)map[sum]);\n }\n else{\n map[sum]=i;\n }\n }\n return len;\n \n }\n};" }, { "code": null, "e": 6474, "s": 6472, "text": "0" }, { "code": null, "e": 6493, "s": 6474, "text": "abhishekmaurya5667" }, { "code": null, "e": 6519, "s": 6493, "text": "This comment was deleted." }, { "code": null, "e": 6521, "s": 6519, "text": "0" }, { "code": null, "e": 6541, "s": 6521, "text": "19bcs13141 week ago" }, { "code": null, "e": 7015, "s": 6541, "text": "class GfG\n{\n int maxLen(int arr[], int n)\n {\n // Your code here\n Map<Integer,Integer> map=new HashMap<>();\n int sum=0;\n int len=0;\n map.put(0,-1);\n for(int i=0;i<n;i++){\n sum+=arr[i];\n if(map.containsKey(sum)==false){\n map.put(sum,i);\n }else{\n int index=map.get(sum);\n len=Math.max(len,i-index);\n }\n }\n return len;\n }\n}" }, { "code": null, "e": 7017, "s": 7015, "text": "0" }, { "code": null, "e": 7037, "s": 7017, "text": "saisaran21 week ago" }, { "code": null, "e": 7064, "s": 7037, "text": "using unordered map in c++" }, { "code": null, "e": 7554, "s": 7064, "text": "class Solution{ public: int maxLen(vector<int>&A, int n) { int s=0; for(int i=0;i<n;i++) { s=s+A[i]; A[i]=s; } unordered_map<int,int>u; for(int i=0;i<n;i++) { u[A[i]]=i; } int mx=0; for(int i=0;i<n;i++) { if(u.find(A[i])!=u.end()) { mx=max(mx,u[A[i]]-i); } if(A[i]==0) { mx=max(mx,i+1); } }" }, { "code": null, "e": 7585, "s": 7554, "text": " return mx; }};" }, { "code": null, "e": 7587, "s": 7585, "text": "0" }, { "code": null, "e": 7612, "s": 7587, "text": "2016yashpratap1 week ago" }, { "code": null, "e": 8308, "s": 7612, "text": "// Easiest java solution class GfG{ int maxLen(int arr[], int n) //store sum as key and index as value in the hashmap { HashMap<Integer,Integer> hm = new HashMap<>(); int sum =0; int mlen = 0; int i =-1; //initialize hashmap with key =0 and value as -1 hm.put(sum,i); while(i<arr.length-1) { i++; sum = sum +arr[i]; //if sum is not present in the list then put in the map if(hm.containsKey(sum)==false) hm.put(sum,i); else { int len = i - hm.get(sum); if(len>mlen) mlen = len; } } return mlen; }}" }, { "code": null, "e": 8454, "s": 8308, "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": 8490, "s": 8454, "text": " Login to access your submissions. " }, { "code": null, "e": 8500, "s": 8490, "text": "\nProblem\n" }, { "code": null, "e": 8510, "s": 8500, "text": "\nContest\n" }, { "code": null, "e": 8573, "s": 8510, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 8721, "s": 8573, "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": 8929, "s": 8721, "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": 9035, "s": 8929, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Node.js cipher.update() Method - GeeksforGeeks
16 Sep, 2021 The cipher.update() method is an inbuilt application programming interface of class Cipher within crypto module which is used to update the cipher with data according to the given encoding format. Syntax: const cipher.update(data[, inputEncoding][, outputEncoding]) Parameters: This method takes the following parameter: data: It is used to update the cipher by new content. inputEncoding: Input encoding format. outputEncoding: Output encoding format. Return Value: This method returns the object of buffer containing the cipher value. Example 1: Filename: index.js Javascript // Node.js program to demonstrate the// cipher.update() method // Importing crypto moduleconst crypto = require('crypto'); // Creating and initializing algorithm and passwordconst algorithm = 'aes-192-cbc';const password = 'Password used to generate key'; // Getting key for the cipher objectconst key = crypto.scryptSync(password, 'salt', 24); // Creating and initializing the static ivconst iv = Buffer.alloc(16, 0); // Creating and initializing the cipher objectconst cipher = crypto.createCipheriv(algorithm, key, iv); // Updating the cipher with the data// by using update() methodlet encrypted = cipher.update( 'some clear text data', 'utf8', 'hex'); // Getting the buffer data of cipherencrypted += cipher.final('hex'); // Display the resultconsole.log(encrypted); Output: e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa Example 2: Filename: index.js Javascript // Node.js program to demonstrate the// cipher.update() method // Importing crypto moduleconst crypto = require('crypto'); // Creating and initializing algorithm and passwordconst algorithm = 'aes-192-cbc';const password = 'Password used to generate key'; // Getting key for cipher objectcrypto.scrypt(password, 'salt', 24, { N: 512 }, (err, key) => { if (err) throw err; // Creating and initializing the static iv const iv = Buffer.alloc(16, 0); // Creating and initializing the cipher object const cipher = crypto .createCipheriv(algorithm, key, iv); // Updating the cipher with the data // by using update() method let encrypted = cipher.update( 'some clear text data', 'utf8', 'hex'); // Getting the buffer data of cipher encrypted += cipher.final('hex'); // Display the result console.log(encrypted); }); Output: 5850288b1848440f0c410400403f7b456293229b5231c17d2b83b602f252714b Run the index.js file using the following command: node index.js Reference: https://nodejs.org/dist/latest-v12.x/docs/api/crypto.html#crypto_cipher_update_data_inputencoding_outputencoding gulshankumarar231 sweetyty Node.js-crypto-module Node.js-Methods Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to update Node.js and NPM to next version ? Node.js fs.readFileSync() Method Node.js fs.writeFile() Method How to update NPM ? Difference between promise and async await in Node.js Remove elements from a JavaScript Array Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 38611, "s": 38583, "text": "\n16 Sep, 2021" }, { "code": null, "e": 38808, "s": 38611, "text": "The cipher.update() method is an inbuilt application programming interface of class Cipher within crypto module which is used to update the cipher with data according to the given encoding format." }, { "code": null, "e": 38816, "s": 38808, "text": "Syntax:" }, { "code": null, "e": 38877, "s": 38816, "text": "const cipher.update(data[, inputEncoding][, outputEncoding])" }, { "code": null, "e": 38932, "s": 38877, "text": "Parameters: This method takes the following parameter:" }, { "code": null, "e": 38986, "s": 38932, "text": "data: It is used to update the cipher by new content." }, { "code": null, "e": 39024, "s": 38986, "text": "inputEncoding: Input encoding format." }, { "code": null, "e": 39064, "s": 39024, "text": "outputEncoding: Output encoding format." }, { "code": null, "e": 39148, "s": 39064, "text": "Return Value: This method returns the object of buffer containing the cipher value." }, { "code": null, "e": 39178, "s": 39148, "text": "Example 1: Filename: index.js" }, { "code": null, "e": 39189, "s": 39178, "text": "Javascript" }, { "code": "// Node.js program to demonstrate the// cipher.update() method // Importing crypto moduleconst crypto = require('crypto'); // Creating and initializing algorithm and passwordconst algorithm = 'aes-192-cbc';const password = 'Password used to generate key'; // Getting key for the cipher objectconst key = crypto.scryptSync(password, 'salt', 24); // Creating and initializing the static ivconst iv = Buffer.alloc(16, 0); // Creating and initializing the cipher objectconst cipher = crypto.createCipheriv(algorithm, key, iv); // Updating the cipher with the data// by using update() methodlet encrypted = cipher.update( 'some clear text data', 'utf8', 'hex'); // Getting the buffer data of cipherencrypted += cipher.final('hex'); // Display the resultconsole.log(encrypted);", "e": 39964, "s": 39189, "text": null }, { "code": null, "e": 39972, "s": 39964, "text": "Output:" }, { "code": null, "e": 40037, "s": 39972, "text": "e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa" }, { "code": null, "e": 40067, "s": 40037, "text": "Example 2: Filename: index.js" }, { "code": null, "e": 40078, "s": 40067, "text": "Javascript" }, { "code": "// Node.js program to demonstrate the// cipher.update() method // Importing crypto moduleconst crypto = require('crypto'); // Creating and initializing algorithm and passwordconst algorithm = 'aes-192-cbc';const password = 'Password used to generate key'; // Getting key for cipher objectcrypto.scrypt(password, 'salt', 24, { N: 512 }, (err, key) => { if (err) throw err; // Creating and initializing the static iv const iv = Buffer.alloc(16, 0); // Creating and initializing the cipher object const cipher = crypto .createCipheriv(algorithm, key, iv); // Updating the cipher with the data // by using update() method let encrypted = cipher.update( 'some clear text data', 'utf8', 'hex'); // Getting the buffer data of cipher encrypted += cipher.final('hex'); // Display the result console.log(encrypted); });", "e": 41006, "s": 40078, "text": null }, { "code": null, "e": 41014, "s": 41006, "text": "Output:" }, { "code": null, "e": 41079, "s": 41014, "text": "5850288b1848440f0c410400403f7b456293229b5231c17d2b83b602f252714b" }, { "code": null, "e": 41130, "s": 41079, "text": "Run the index.js file using the following command:" }, { "code": null, "e": 41144, "s": 41130, "text": "node index.js" }, { "code": null, "e": 41268, "s": 41144, "text": "Reference: https://nodejs.org/dist/latest-v12.x/docs/api/crypto.html#crypto_cipher_update_data_inputencoding_outputencoding" }, { "code": null, "e": 41286, "s": 41268, "text": "gulshankumarar231" }, { "code": null, "e": 41295, "s": 41286, "text": "sweetyty" }, { "code": null, "e": 41317, "s": 41295, "text": "Node.js-crypto-module" }, { "code": null, "e": 41333, "s": 41317, "text": "Node.js-Methods" }, { "code": null, "e": 41341, "s": 41333, "text": "Node.js" }, { "code": null, "e": 41358, "s": 41341, "text": "Web Technologies" }, { "code": null, "e": 41456, "s": 41358, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 41504, "s": 41456, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 41537, "s": 41504, "text": "Node.js fs.readFileSync() Method" }, { "code": null, "e": 41567, "s": 41537, "text": "Node.js fs.writeFile() Method" }, { "code": null, "e": 41587, "s": 41567, "text": "How to update NPM ?" }, { "code": null, "e": 41641, "s": 41587, "text": "Difference between promise and async await in Node.js" }, { "code": null, "e": 41681, "s": 41641, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 41726, "s": 41681, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 41769, "s": 41726, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 41819, "s": 41769, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Sorting Algorithms - GeeksQuiz
06 Sep, 2021 Selection sort makes O(n) swaps which is minimum among all sorting algorithms mentioned above. 2 5 1 7 9 12 11 10 Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Program for Breadth First Search or BFS for a Graph Best Time to Buy and Sell Stock Must Do Coding Questions for Product Based Companies How to calculate MOVING AVERAGE in a Pandas DataFrame? How to insert a pandas DataFrame to an existing PostgreSQL table? What is "network ID" and "host ID" in IP Addresses? What is Transmission Control Protocol (TCP)? How to Find Length of String in Bash Script? Bash Scripting - How to read a file line by line Converting nested JSON structures to Pandas DataFrames
[ { "code": null, "e": 35847, "s": 35819, "text": "\n06 Sep, 2021" }, { "code": null, "e": 35942, "s": 35847, "text": "Selection sort makes O(n) swaps which is minimum among all sorting algorithms mentioned above." }, { "code": null, "e": 35969, "s": 35942, "text": "2 5 1 7 9 12 11 10 " }, { "code": null, "e": 36067, "s": 35969, "text": "Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here." }, { "code": null, "e": 36126, "s": 36067, "text": "Python Program for Breadth First Search or BFS for a Graph" }, { "code": null, "e": 36158, "s": 36126, "text": "Best Time to Buy and Sell Stock" }, { "code": null, "e": 36211, "s": 36158, "text": "Must Do Coding Questions for Product Based Companies" }, { "code": null, "e": 36266, "s": 36211, "text": "How to calculate MOVING AVERAGE in a Pandas DataFrame?" }, { "code": null, "e": 36332, "s": 36266, "text": "How to insert a pandas DataFrame to an existing PostgreSQL table?" }, { "code": null, "e": 36384, "s": 36332, "text": "What is \"network ID\" and \"host ID\" in IP Addresses?" }, { "code": null, "e": 36429, "s": 36384, "text": "What is Transmission Control Protocol (TCP)?" }, { "code": null, "e": 36474, "s": 36429, "text": "How to Find Length of String in Bash Script?" }, { "code": null, "e": 36523, "s": 36474, "text": "Bash Scripting - How to read a file line by line" } ]
Check the Version of the Python Interpreter - GeeksforGeeks
24 Jan, 2021 Under this article, we will get to know the current version of python interpreter in the system. Getting the version of the interpreter is really important as the python interpreter is widely used throughout the industries for computer programming and source coding. It takes an interactive command and executes it. As the interpreter is the one which takes the code and helps in execution. Sometimes due to the old version of the interpreter making command doesn’t work properly and as we know the language python comes with frequent update vision with some added new features, so the user must update the interpreter with the latest release version. To get the Version of the python Interpreter; They are listed as follows: Using sys.version method Using python_version() function Using python -V command 1. Using sys.version method: For this method, the user needs to import the sys library and from sys.version command which will return the user’s current python version in the use. For this method, the user must open the Python shell and write the following command as given below, with this command the user will get the current working version of the python interpreter in the form of a string. Here are some step that user must follow to get its current running version of the python interpreter:- Open cmd/terminal/windows powershellWrite ‘python’ and press enter key to move into python interpreterWrite the same command given in the input box below, and in the result, the user will get the current interpreter version. Open cmd/terminal/windows powershell Write ‘python’ and press enter key to move into python interpreter Write the same command given in the input box below, and in the result, the user will get the current interpreter version. Python3 import sys print("User Current Version:-", sys.version) Output: 2. Using python_version() function: This function is accessible by importing the platform library and will always return a string of the running user’s python version. For better understanding one can go with the following steps:- Open cmd/terminal/windows powershellWrite ‘python’ and press enter key to move into python interpreterNow, write the same command as mention below in the code box given, and press enter , with this it will return the current python interpreter version in the form of string. Open cmd/terminal/windows powershell Write ‘python’ and press enter key to move into python interpreter Now, write the same command as mention below in the code box given, and press enter , with this it will return the current python interpreter version in the form of string. Python3 from platform import python_version print("Current Python Version-", python_version()) Output: 3.Using python -V command:- This method is one of the simplest methods among all other methods as in this method user get the current python version with the one of the inbuilt command present in python. Here are some step that user must follow to get its current running version of the python interpreter:- Open cmd/terminal/windows powershellNow, write the same command as mention below in the code box given, and press enter , with this it will return the current python interpreter version in the form of string. Open cmd/terminal/windows powershell Now, write the same command as mention below in the code box given, and press enter , with this it will return the current python interpreter version in the form of string. python -V Output: Picked Python-sys python-utility 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 ? Selecting rows in pandas DataFrame based on conditions How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Get unique values from a list Defaultdict in Python Python OOPs Concepts Python | os.path.join() method Python | Pandas dataframe.groupby()
[ { "code": null, "e": 24292, "s": 24264, "text": "\n24 Jan, 2021" }, { "code": null, "e": 24609, "s": 24292, "text": "Under this article, we will get to know the current version of python interpreter in the system. Getting the version of the interpreter is really important as the python interpreter is widely used throughout the industries for computer programming and source coding. It takes an interactive command and executes it. " }, { "code": null, "e": 24945, "s": 24609, "text": "As the interpreter is the one which takes the code and helps in execution. Sometimes due to the old version of the interpreter making command doesn’t work properly and as we know the language python comes with frequent update vision with some added new features, so the user must update the interpreter with the latest release version." }, { "code": null, "e": 25019, "s": 24945, "text": "To get the Version of the python Interpreter; They are listed as follows:" }, { "code": null, "e": 25044, "s": 25019, "text": "Using sys.version method" }, { "code": null, "e": 25076, "s": 25044, "text": "Using python_version() function" }, { "code": null, "e": 25100, "s": 25076, "text": "Using python -V command" }, { "code": null, "e": 25129, "s": 25100, "text": "1. Using sys.version method:" }, { "code": null, "e": 25496, "s": 25129, "text": "For this method, the user needs to import the sys library and from sys.version command which will return the user’s current python version in the use. For this method, the user must open the Python shell and write the following command as given below, with this command the user will get the current working version of the python interpreter in the form of a string." }, { "code": null, "e": 25600, "s": 25496, "text": "Here are some step that user must follow to get its current running version of the python interpreter:-" }, { "code": null, "e": 25825, "s": 25600, "text": "Open cmd/terminal/windows powershellWrite ‘python’ and press enter key to move into python interpreterWrite the same command given in the input box below, and in the result, the user will get the current interpreter version." }, { "code": null, "e": 25862, "s": 25825, "text": "Open cmd/terminal/windows powershell" }, { "code": null, "e": 25929, "s": 25862, "text": "Write ‘python’ and press enter key to move into python interpreter" }, { "code": null, "e": 26052, "s": 25929, "text": "Write the same command given in the input box below, and in the result, the user will get the current interpreter version." }, { "code": null, "e": 26060, "s": 26052, "text": "Python3" }, { "code": "import sys print(\"User Current Version:-\", sys.version)", "e": 26119, "s": 26060, "text": null }, { "code": null, "e": 26127, "s": 26119, "text": "Output:" }, { "code": null, "e": 26163, "s": 26127, "text": "2. Using python_version() function:" }, { "code": null, "e": 26358, "s": 26163, "text": "This function is accessible by importing the platform library and will always return a string of the running user’s python version. For better understanding one can go with the following steps:-" }, { "code": null, "e": 26633, "s": 26358, "text": "Open cmd/terminal/windows powershellWrite ‘python’ and press enter key to move into python interpreterNow, write the same command as mention below in the code box given, and press enter , with this it will return the current python interpreter version in the form of string." }, { "code": null, "e": 26670, "s": 26633, "text": "Open cmd/terminal/windows powershell" }, { "code": null, "e": 26737, "s": 26670, "text": "Write ‘python’ and press enter key to move into python interpreter" }, { "code": null, "e": 26910, "s": 26737, "text": "Now, write the same command as mention below in the code box given, and press enter , with this it will return the current python interpreter version in the form of string." }, { "code": null, "e": 26918, "s": 26910, "text": "Python3" }, { "code": "from platform import python_version print(\"Current Python Version-\", python_version())", "e": 27008, "s": 26918, "text": null }, { "code": null, "e": 27016, "s": 27008, "text": "Output:" }, { "code": null, "e": 27045, "s": 27016, "text": "3.Using python -V command:-" }, { "code": null, "e": 27221, "s": 27045, "text": "This method is one of the simplest methods among all other methods as in this method user get the current python version with the one of the inbuilt command present in python." }, { "code": null, "e": 27325, "s": 27221, "text": "Here are some step that user must follow to get its current running version of the python interpreter:-" }, { "code": null, "e": 27534, "s": 27325, "text": "Open cmd/terminal/windows powershellNow, write the same command as mention below in the code box given, and press enter , with this it will return the current python interpreter version in the form of string." }, { "code": null, "e": 27571, "s": 27534, "text": "Open cmd/terminal/windows powershell" }, { "code": null, "e": 27744, "s": 27571, "text": "Now, write the same command as mention below in the code box given, and press enter , with this it will return the current python interpreter version in the form of string." }, { "code": null, "e": 27755, "s": 27744, "text": " python -V" }, { "code": null, "e": 27763, "s": 27755, "text": "Output:" }, { "code": null, "e": 27770, "s": 27763, "text": "Picked" }, { "code": null, "e": 27781, "s": 27770, "text": "Python-sys" }, { "code": null, "e": 27796, "s": 27781, "text": "python-utility" }, { "code": null, "e": 27803, "s": 27796, "text": "Python" }, { "code": null, "e": 27901, "s": 27803, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27910, "s": 27901, "text": "Comments" }, { "code": null, "e": 27923, "s": 27910, "text": "Old Comments" }, { "code": null, "e": 27955, "s": 27923, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28010, "s": 27955, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 28066, "s": 28010, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28108, "s": 28066, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28150, "s": 28108, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28189, "s": 28150, "text": "Python | Get unique values from a list" }, { "code": null, "e": 28211, "s": 28189, "text": "Defaultdict in Python" }, { "code": null, "e": 28232, "s": 28211, "text": "Python OOPs Concepts" }, { "code": null, "e": 28263, "s": 28232, "text": "Python | os.path.join() method" } ]
Get row numbers of NumPy array having element larger than X
11 Oct, 2020 Let’s see how to getting the row numbers of a numpy array that have at least one item is larger than a specified value X. So, for doing this task we will use numpy.where() and numpy.any() functions together. Syntax: numpy.where(condition[, x, y]) Return: [ndarray or tuple of ndarrays] If both x and y are specified, the output array contains elements of x where condition is True, and elements from y elsewhere. Syntax: numpy.any(a, axis = None, out = None, keepdims = class numpy._globals._NoValue at 0x40ba726c) Return: [ndarray, optional]Output array with same dimensions as Input array, Placed with result Example : Arr = [[1,2,3,4,5], [10,-3,30,4,5], [3,2,5,-4,5], [9,7,3,6,5]] and X = 6 then output is [ 0, 2 ]. Here, [[1,2,3,4,5], no element is greater than 6 so output is [0]. [10,-3,30,4,5], 10 is greater than 6 so output is [0]. [3,2,5,-4,5], no element is greater than 6 so output is [0, 2]. [4,7,3,6,5]] 7 is greater than 6 so output is [0, 2]. Below is the implementation: Python3 # importing libraryimport numpy # create numpy arrayarr = numpy.array([[1, 2, 3, 4, 5], [10, -3, 30, 4, 5], [3, 2, 5, -4, 5], [9, 7, 3, 6, 5] ]) # declare specified valueX = 6 # view arrayprint("Given Array:\n", arr) # finding out the row numbersoutput = numpy.where(numpy.any(arr > X, axis = 1)) # view outputprint("Result:\n", output) Output: Given Array: [[ 1 2 3 4 5] [10 -3 30 4 5] [ 3 2 5 -4 5] [ 9 7 3 6 5]] Result: (array([1, 3], dtype=int64),) Python numpy-Indexing Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | datetime.timedelta() function Python | Get unique values from a list
[ { "code": null, "e": 28, "s": 0, "text": "\n11 Oct, 2020" }, { "code": null, "e": 236, "s": 28, "text": "Let’s see how to getting the row numbers of a numpy array that have at least one item is larger than a specified value X. So, for doing this task we will use numpy.where() and numpy.any() functions together." }, { "code": null, "e": 275, "s": 236, "text": "Syntax: numpy.where(condition[, x, y])" }, { "code": null, "e": 441, "s": 275, "text": "Return: [ndarray or tuple of ndarrays] If both x and y are specified, the output array contains elements of x where condition is True, and elements from y elsewhere." }, { "code": null, "e": 543, "s": 441, "text": "Syntax: numpy.any(a, axis = None, out = None, keepdims = class numpy._globals._NoValue at 0x40ba726c)" }, { "code": null, "e": 639, "s": 543, "text": "Return: [ndarray, optional]Output array with same dimensions as Input array, Placed with result" }, { "code": null, "e": 649, "s": 639, "text": "Example :" }, { "code": null, "e": 1015, "s": 649, "text": "Arr = [[1,2,3,4,5], \n [10,-3,30,4,5], \n [3,2,5,-4,5], \n [9,7,3,6,5]] \nand X = 6 then output is [ 0, 2 ].\n\nHere, \n[[1,2,3,4,5],\nno element is greater than 6 so output is [0].\n\n[10,-3,30,4,5],\n10 is greater than 6 so output is [0].\n\n[3,2,5,-4,5],\nno element is greater than 6 so output is [0, 2].\n\n[4,7,3,6,5]]\n7 is greater than 6 so output is [0, 2].\n" }, { "code": null, "e": 1044, "s": 1015, "text": "Below is the implementation:" }, { "code": null, "e": 1052, "s": 1044, "text": "Python3" }, { "code": "# importing libraryimport numpy # create numpy arrayarr = numpy.array([[1, 2, 3, 4, 5], [10, -3, 30, 4, 5], [3, 2, 5, -4, 5], [9, 7, 3, 6, 5] ]) # declare specified valueX = 6 # view arrayprint(\"Given Array:\\n\", arr) # finding out the row numbersoutput = numpy.where(numpy.any(arr > X, axis = 1)) # view outputprint(\"Result:\\n\", output)", "e": 1494, "s": 1052, "text": null }, { "code": null, "e": 1502, "s": 1494, "text": "Output:" }, { "code": null, "e": 1624, "s": 1502, "text": "Given Array:\n[[ 1 2 3 4 5]\n[10 -3 30 4 5]\n[ 3 2 5 -4 5]\n[ 9 7 3 6 5]]\nResult:\n(array([1, 3], dtype=int64),)\n" }, { "code": null, "e": 1646, "s": 1624, "text": "Python numpy-Indexing" }, { "code": null, "e": 1659, "s": 1646, "text": "Python-numpy" }, { "code": null, "e": 1666, "s": 1659, "text": "Python" }, { "code": null, "e": 1764, "s": 1666, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1796, "s": 1764, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1823, "s": 1796, "text": "Python Classes and Objects" }, { "code": null, "e": 1844, "s": 1823, "text": "Python OOPs Concepts" }, { "code": null, "e": 1867, "s": 1844, "text": "Introduction To PYTHON" }, { "code": null, "e": 1923, "s": 1867, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 1954, "s": 1923, "text": "Python | os.path.join() method" }, { "code": null, "e": 1996, "s": 1954, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2038, "s": 1996, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2077, "s": 2038, "text": "Python | datetime.timedelta() function" } ]
Rock, Paper, Scissor game – Python Project
08 Aug, 2021 In this article, we will see how we can create a rock paper and scissor game using Tkinter. Rock paper scissor is a hand game usually played between two people, in which each player simultaneously forms one of the three shapes with an outstretched hand. These shapes are “rock”, “paper”, and “scissors”. Let there be a Player who is playing with a computer as an opponent. Now, If the player selects Paper and Computer Selects Scissor – Computer wins If the player selects Rock and Computer Selects Scissor – Player 1 wins If the player selects Paper and Computer Selects Rock – Player 1 wins And If the player selects Paper and Computer Selects Paper – Draw If the player selects Rock and Computer Selects Rock – Draw If the player selects Scissor and Computer Selects Scissor – Draw Tkinter: It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with tkinter is the fastest and easiest way to create the GUI applications. Random: Python defines a set of functions that are used to generate or manipulate random numbers through the random module. PIL: Python Imaging Library (expansion of PIL) is the de facto image processing package for Python language. It incorporates lightweight image processing tools that aids in editing, creating and saving images. 1) Import Python Module Tkinter to execute GUI applications. 2) From PIL Import ImageTk, Image for image processing. 3) Import random which will help the computer to select options rock, paper, or scissor randomly. 4) Now an object is created root which is the main window object. Title of this window -> Rock Paper Scissor Dimensions of this window -> “800×680” 5) Create canvas of width=800, height=680 6) Now we Create labels on GUI window l1 =Player-> font=’Algerian’, size=25 l2 =Computer-> font=’Algerian’, size=25 l3 =Vs font=’Algerian’, size=40 7) Now labels are placed on window l1 at x=80, y=20 l2 at x=560, y=20 l3 at x=370, y=230 For Default Image: 1) An variable named img_p is used to open the default hand image and resize it to (300,300). This will be shown at default condition in the game at the place of the player. 2) An variable named img_c is used to store flipped default image from left to right using transpose function and it is saved in the variable. This will be shown at default condition in the game at the place of the computer’s side. 3) Images img_p and img_c are loaded on the canvas now using Tk.PhotoImage For Rock Image: 1) An variable named rock_p is used to open the rock hand image and resize it to (300,300). This will be shown at the player’s side when the player selects rock in the game. 2) An variable named rock_c is used to store flipped rock hand image from left to right using transpose function and will be shown at computer’s side when the computer randomly selects rock in the game. 3) Images rock_p and rock_c are loaded on the canvas now using Tk.PhotoImage. For Paper Image 1) An variable named paper_p is used to open the paper hand image and resize it to (300,300). This will be shown at the player’s side when the player selects paper in the game. 2) An variable named paper_c is used to store flipped paper hand images from left to right using the transpose function and will be shown at the computer’s side when the computer randomly selects paper in the game. 3) Images paper_p and paper_c is loaded on the canvas now using Tk.PhotoImage. For Scissors Image 1) An variable named scissor_p is used to open the scissor hand image and resize it to (300,300). This will be shown at player’s side when player selects scissor in the game. 2) An variable named scissor_c is used to store flipped scissor hand image from left to right using transpose function and will be shown at computer’s side when computer randomly selects scissor in the game. 3) Images scissor_p and scissor_c are loaded on the canvas now using Tk.PhotoImage. For Selection Image: 1) An variable named img_s is used to open the selection of hand images i.e. Combined image of Rock, Paper & Scissor, and resize it to (300,130). 2) Image img_s is loaded on the canvas now using Tk.PhotoImage. 1) A game function is defined in which we have a list named select having values 1, 2, 3 representing rock, paper, and scissors respectively. 2) Here random.choice randomly selects options 1-3 for computer 3) Set image for Player on canvas If Player selects 1 (Rock) Show rock image on canvas using create_image. If Player selects 2 (Paper) Show paper image on canvas using create_image. If Player selects 3 (Scissor) Show scissor image on canvas using create_image. 4) Set image for Computer on canvas If Computer selects 1 (Rock) Show rock image on canvas using create_image. If Computer selects 2 (Paper) Show paper image on canvas using create_image. If Computer selects 3 (Scissor) Show scissor image on canvas using create_image. 5) Obtaining the result If Player chooses Rock and computer chooses Rock OR If the player chooses Paper and the computer chooses Paper OR If the player chooses Scissor and the computer chooses Scissor. Result Shown-> Draw If the Player chooses Rock and computer choose Scissor OR If the player chooses Paper and computer choose Rock OR If the player chooses Scissor and computer choose Paper. Result Shown -> Player won Else Result Shown-> Computer won Note: This result is shown on canvas in form of text having dimensions (390,600), font=’Algerian’, tag=’result’. 6) Buttons Clear Button -> Deletes the present result and switches the figures at both sides to its default conditions. Rock Button -> Selects choice 1 in function game and Shows an Image of Hand showing Rock On Player side. Paper Button -> Selects choice 2 in function game and Shows Image of Hand showing Paper On Player side Scissor Button -> Selects choice 3 in function game and Shows an Image of Hand showing the Scissor On the Player side. Images Used: default.jpg paper.jpg rock.jpg scissor.jpg Selection.jpg main.py Python3 from tkinter import *from PIL import ImageTk, Imageimport random # main window objectroot = Tk() # Title of GUI windowroot.title('Rock Paper Scissor') # Size of windowroot.geometry('800x680') # Creating canvascanvas = Canvas(root, width=800, height=680)canvas.grid(row=0, column=0) # Creating labels on GUI windowl1 = Label(root, text='Player', font=('Algerian', 25))l2 = Label(root, text='Computer', font=('Algerian', 25))l3 = Label(root, text='Vs', font=('Algerian', 40)) # Placing all the labels on windowl1.place(x=80, y=20)l2.place(x=560, y=20)l3.place(x=370, y=230) # Default imageimg_p = Image.open("default.jpeg")img_p = img_p.resize((300, 300)) # Flipping image from left to rightimg_c = img_p.transpose(Image.FLIP_LEFT_RIGHT) # Loading images to put on canvasimg_p = ImageTk.PhotoImage(img_p)img_c = ImageTk.PhotoImage(img_c) # Rock imagerock_p = Image.open('rock.jpeg')rock_p = rock_p.resize((300, 300)) # Flipping image from left to rightrock_c = rock_p.transpose(Image.FLIP_LEFT_RIGHT) # Loading images to put on canvasrock_p = ImageTk.PhotoImage(rock_p)rock_c = ImageTk.PhotoImage(rock_c) # Paper imagepaper_p = Image.open('paper.jpeg')paper_p = paper_p.resize((300, 300)) # Flipping image from left to rightpaper_c = paper_p.transpose(Image.FLIP_LEFT_RIGHT) # Loading images to put on canvaspaper_p = ImageTk.PhotoImage(paper_p)paper_c = ImageTk.PhotoImage(paper_c) # Scissor imagescissor_p = Image.open('scissor.jpeg')scissor_p = scissor_p.resize((300, 300)) # Flipping image from left to rightscissor_c = scissor_p.transpose(Image.FLIP_LEFT_RIGHT) # Loading images to put on canvasscissor_p = ImageTk.PhotoImage(scissor_p)scissor_c = ImageTk.PhotoImage(scissor_c) # Selection imageimg_s = Image.open("Selection.jpeg")img_s = img_s.resize((300, 130))img_s = ImageTk.PhotoImage(img_s) # Putting image on canvas on specific coordinatescanvas.create_image(0, 100, anchor=NW, image=img_p)canvas.create_image(500, 100, anchor=NW, image=img_c)canvas.create_image(0, 400, anchor=NW, image=img_s)canvas.create_image(500, 400, anchor=NW, image=img_s) # game functiondef game(player): select = [1, 2, 3] # Randomly selects option for computer computer = random.choice(select) # Setting image for player on canvas if player == 1: # Puts rock image on canvas canvas.create_image(0, 100, anchor=NW, image=rock_p) elif player == 2: # Puts paper image on canvas canvas.create_image(0, 100, anchor=NW, image=paper_p) else: # Puts scissor image on canvas canvas.create_image(0, 100, anchor=NW, image=scissor_p) # Setting image for computer on canvas if computer == 1: # Puts rock image on canvas canvas.create_image(500, 100, anchor=NW, image=rock_c) elif computer == 2: # Puts paper image on canvas canvas.create_image(500, 100, anchor=NW, image=paper_c) else: # Puts scissor image on canvas canvas.create_image(500, 100, anchor=NW, image=scissor_c) # Obtaining result by comparison if player == computer: # Case of DRAW res = 'Draw' # Case of player's win elif (player == 1 and computer == 3) or (player == 2 and computer == 1) or (player == 3 and computer == 2): res = 'You won' # Case of computer's win else: res = 'Computer won' # Putting result on canvas canvas.create_text(390, 600, text='Result:- ' + res, fill="black", font=('Algerian', 25), tag='result') # Function for clear buttondef clear(): # Removes result from canvas canvas.delete('result') # Puts default image on canvas canvas.create_image(0, 100, anchor=NW, image=img_p) canvas.create_image(500, 100, anchor=NW, image=img_c) # Button for selecting rockrock_b = Button(root, text='Rock', command=lambda: game(1))rock_b.place(x=35, y=487) # Button for selecting paperpaper_b = Button(root, text='Paper', command=lambda: game(2))paper_b.place(x=128, y=487) # Button for selecting scissorscissor_b = Button(root, text='Scissor', command=lambda: game(3))scissor_b.place(x=220, y=487) # Button for clearclear_b = Button(root, text='CLEAR', font=('Times', 10, 'bold'), width=10, command=clear).place(x=370, y=28) root.mainloop() Output Utkarsh ShawChirag Bhatia Utkarsh Shaw Chirag Bhatia chi251201 ProGeek 2021 Python Tkinter-projects Python-projects Python-tkinter ProGeek Project Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Project Idea - A website acting as transaction between oxygen sellers and buyers Online Schooling System - Python Project Project Idea | Anonymous Message Prank Game in PHP Project Idea – Healthcare App Project Idea - Fintech SDE SHEET - A Complete Guide for SDE Preparation Implementing Web Scraping in Python with BeautifulSoup Working with zip files in Python XML parsing in Python Python | Simple GUI calculator using Tkinter
[ { "code": null, "e": 52, "s": 24, "text": "\n08 Aug, 2021" }, { "code": null, "e": 356, "s": 52, "text": "In this article, we will see how we can create a rock paper and scissor game using Tkinter. Rock paper scissor is a hand game usually played between two people, in which each player simultaneously forms one of the three shapes with an outstretched hand. These shapes are “rock”, “paper”, and “scissors”." }, { "code": null, "e": 431, "s": 356, "text": "Let there be a Player who is playing with a computer as an opponent. Now," }, { "code": null, "e": 504, "s": 431, "text": "If the player selects Paper and Computer Selects Scissor – Computer wins" }, { "code": null, "e": 576, "s": 504, "text": "If the player selects Rock and Computer Selects Scissor – Player 1 wins" }, { "code": null, "e": 646, "s": 576, "text": "If the player selects Paper and Computer Selects Rock – Player 1 wins" }, { "code": null, "e": 712, "s": 646, "text": "And If the player selects Paper and Computer Selects Paper – Draw" }, { "code": null, "e": 772, "s": 712, "text": "If the player selects Rock and Computer Selects Rock – Draw" }, { "code": null, "e": 838, "s": 772, "text": "If the player selects Scissor and Computer Selects Scissor – Draw" }, { "code": null, "e": 1007, "s": 838, "text": "Tkinter: It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with tkinter is the fastest and easiest way to create the GUI applications." }, { "code": null, "e": 1131, "s": 1007, "text": "Random: Python defines a set of functions that are used to generate or manipulate random numbers through the random module." }, { "code": null, "e": 1341, "s": 1131, "text": "PIL: Python Imaging Library (expansion of PIL) is the de facto image processing package for Python language. It incorporates lightweight image processing tools that aids in editing, creating and saving images." }, { "code": null, "e": 1402, "s": 1341, "text": "1) Import Python Module Tkinter to execute GUI applications." }, { "code": null, "e": 1458, "s": 1402, "text": "2) From PIL Import ImageTk, Image for image processing." }, { "code": null, "e": 1556, "s": 1458, "text": "3) Import random which will help the computer to select options rock, paper, or scissor randomly." }, { "code": null, "e": 1622, "s": 1556, "text": "4) Now an object is created root which is the main window object." }, { "code": null, "e": 1665, "s": 1622, "text": "Title of this window -> Rock Paper Scissor" }, { "code": null, "e": 1704, "s": 1665, "text": "Dimensions of this window -> “800×680”" }, { "code": null, "e": 1746, "s": 1704, "text": "5) Create canvas of width=800, height=680" }, { "code": null, "e": 1784, "s": 1746, "text": "6) Now we Create labels on GUI window" }, { "code": null, "e": 1822, "s": 1784, "text": "l1 =Player-> font=’Algerian’, size=25" }, { "code": null, "e": 1862, "s": 1822, "text": "l2 =Computer-> font=’Algerian’, size=25" }, { "code": null, "e": 1894, "s": 1862, "text": "l3 =Vs font=’Algerian’, size=40" }, { "code": null, "e": 1929, "s": 1894, "text": "7) Now labels are placed on window" }, { "code": null, "e": 1946, "s": 1929, "text": "l1 at x=80, y=20" }, { "code": null, "e": 1964, "s": 1946, "text": "l2 at x=560, y=20" }, { "code": null, "e": 1983, "s": 1964, "text": "l3 at x=370, y=230" }, { "code": null, "e": 2002, "s": 1983, "text": "For Default Image:" }, { "code": null, "e": 2176, "s": 2002, "text": "1) An variable named img_p is used to open the default hand image and resize it to (300,300). This will be shown at default condition in the game at the place of the player." }, { "code": null, "e": 2408, "s": 2176, "text": "2) An variable named img_c is used to store flipped default image from left to right using transpose function and it is saved in the variable. This will be shown at default condition in the game at the place of the computer’s side." }, { "code": null, "e": 2483, "s": 2408, "text": "3) Images img_p and img_c are loaded on the canvas now using Tk.PhotoImage" }, { "code": null, "e": 2499, "s": 2483, "text": "For Rock Image:" }, { "code": null, "e": 2673, "s": 2499, "text": "1) An variable named rock_p is used to open the rock hand image and resize it to (300,300). This will be shown at the player’s side when the player selects rock in the game." }, { "code": null, "e": 2876, "s": 2673, "text": "2) An variable named rock_c is used to store flipped rock hand image from left to right using transpose function and will be shown at computer’s side when the computer randomly selects rock in the game." }, { "code": null, "e": 2955, "s": 2876, "text": "3) Images rock_p and rock_c are loaded on the canvas now using Tk.PhotoImage." }, { "code": null, "e": 2971, "s": 2955, "text": "For Paper Image" }, { "code": null, "e": 3148, "s": 2971, "text": "1) An variable named paper_p is used to open the paper hand image and resize it to (300,300). This will be shown at the player’s side when the player selects paper in the game." }, { "code": null, "e": 3363, "s": 3148, "text": "2) An variable named paper_c is used to store flipped paper hand images from left to right using the transpose function and will be shown at the computer’s side when the computer randomly selects paper in the game." }, { "code": null, "e": 3443, "s": 3363, "text": "3) Images paper_p and paper_c is loaded on the canvas now using Tk.PhotoImage." }, { "code": null, "e": 3462, "s": 3443, "text": "For Scissors Image" }, { "code": null, "e": 3637, "s": 3462, "text": "1) An variable named scissor_p is used to open the scissor hand image and resize it to (300,300). This will be shown at player’s side when player selects scissor in the game." }, { "code": null, "e": 3845, "s": 3637, "text": "2) An variable named scissor_c is used to store flipped scissor hand image from left to right using transpose function and will be shown at computer’s side when computer randomly selects scissor in the game." }, { "code": null, "e": 3930, "s": 3845, "text": "3) Images scissor_p and scissor_c are loaded on the canvas now using Tk.PhotoImage." }, { "code": null, "e": 3951, "s": 3930, "text": "For Selection Image:" }, { "code": null, "e": 4099, "s": 3951, "text": "1) An variable named img_s is used to open the selection of hand images i.e. Combined image of Rock, Paper & Scissor, and resize it to (300,130). " }, { "code": null, "e": 4163, "s": 4099, "text": "2) Image img_s is loaded on the canvas now using Tk.PhotoImage." }, { "code": null, "e": 4305, "s": 4163, "text": "1) A game function is defined in which we have a list named select having values 1, 2, 3 representing rock, paper, and scissors respectively." }, { "code": null, "e": 4369, "s": 4305, "text": "2) Here random.choice randomly selects options 1-3 for computer" }, { "code": null, "e": 4403, "s": 4369, "text": "3) Set image for Player on canvas" }, { "code": null, "e": 4477, "s": 4403, "text": "If Player selects 1 (Rock) Show rock image on canvas using create_image." }, { "code": null, "e": 4552, "s": 4477, "text": "If Player selects 2 (Paper) Show paper image on canvas using create_image." }, { "code": null, "e": 4631, "s": 4552, "text": "If Player selects 3 (Scissor) Show scissor image on canvas using create_image." }, { "code": null, "e": 4667, "s": 4631, "text": "4) Set image for Computer on canvas" }, { "code": null, "e": 4743, "s": 4667, "text": "If Computer selects 1 (Rock) Show rock image on canvas using create_image." }, { "code": null, "e": 4820, "s": 4743, "text": "If Computer selects 2 (Paper) Show paper image on canvas using create_image." }, { "code": null, "e": 4901, "s": 4820, "text": "If Computer selects 3 (Scissor) Show scissor image on canvas using create_image." }, { "code": null, "e": 4925, "s": 4901, "text": "5) Obtaining the result" }, { "code": null, "e": 5123, "s": 4925, "text": "If Player chooses Rock and computer chooses Rock OR If the player chooses Paper and the computer chooses Paper OR If the player chooses Scissor and the computer chooses Scissor. Result Shown-> Draw" }, { "code": null, "e": 5322, "s": 5123, "text": "If the Player chooses Rock and computer choose Scissor OR If the player chooses Paper and computer choose Rock OR If the player chooses Scissor and computer choose Paper. Result Shown -> Player won" }, { "code": null, "e": 5355, "s": 5322, "text": "Else Result Shown-> Computer won" }, { "code": null, "e": 5468, "s": 5355, "text": "Note: This result is shown on canvas in form of text having dimensions (390,600), font=’Algerian’, tag=’result’." }, { "code": null, "e": 5479, "s": 5468, "text": "6) Buttons" }, { "code": null, "e": 5588, "s": 5479, "text": "Clear Button -> Deletes the present result and switches the figures at both sides to its default conditions." }, { "code": null, "e": 5694, "s": 5588, "text": "Rock Button -> Selects choice 1 in function game and Shows an Image of Hand showing Rock On Player side." }, { "code": null, "e": 5797, "s": 5694, "text": "Paper Button -> Selects choice 2 in function game and Shows Image of Hand showing Paper On Player side" }, { "code": null, "e": 5916, "s": 5797, "text": "Scissor Button -> Selects choice 3 in function game and Shows an Image of Hand showing the Scissor On the Player side." }, { "code": null, "e": 5929, "s": 5916, "text": "Images Used:" }, { "code": null, "e": 5941, "s": 5929, "text": "default.jpg" }, { "code": null, "e": 5951, "s": 5941, "text": "paper.jpg" }, { "code": null, "e": 5960, "s": 5951, "text": "rock.jpg" }, { "code": null, "e": 5972, "s": 5960, "text": "scissor.jpg" }, { "code": null, "e": 5986, "s": 5972, "text": "Selection.jpg" }, { "code": null, "e": 5994, "s": 5986, "text": "main.py" }, { "code": null, "e": 6002, "s": 5994, "text": "Python3" }, { "code": "from tkinter import *from PIL import ImageTk, Imageimport random # main window objectroot = Tk() # Title of GUI windowroot.title('Rock Paper Scissor') # Size of windowroot.geometry('800x680') # Creating canvascanvas = Canvas(root, width=800, height=680)canvas.grid(row=0, column=0) # Creating labels on GUI windowl1 = Label(root, text='Player', font=('Algerian', 25))l2 = Label(root, text='Computer', font=('Algerian', 25))l3 = Label(root, text='Vs', font=('Algerian', 40)) # Placing all the labels on windowl1.place(x=80, y=20)l2.place(x=560, y=20)l3.place(x=370, y=230) # Default imageimg_p = Image.open(\"default.jpeg\")img_p = img_p.resize((300, 300)) # Flipping image from left to rightimg_c = img_p.transpose(Image.FLIP_LEFT_RIGHT) # Loading images to put on canvasimg_p = ImageTk.PhotoImage(img_p)img_c = ImageTk.PhotoImage(img_c) # Rock imagerock_p = Image.open('rock.jpeg')rock_p = rock_p.resize((300, 300)) # Flipping image from left to rightrock_c = rock_p.transpose(Image.FLIP_LEFT_RIGHT) # Loading images to put on canvasrock_p = ImageTk.PhotoImage(rock_p)rock_c = ImageTk.PhotoImage(rock_c) # Paper imagepaper_p = Image.open('paper.jpeg')paper_p = paper_p.resize((300, 300)) # Flipping image from left to rightpaper_c = paper_p.transpose(Image.FLIP_LEFT_RIGHT) # Loading images to put on canvaspaper_p = ImageTk.PhotoImage(paper_p)paper_c = ImageTk.PhotoImage(paper_c) # Scissor imagescissor_p = Image.open('scissor.jpeg')scissor_p = scissor_p.resize((300, 300)) # Flipping image from left to rightscissor_c = scissor_p.transpose(Image.FLIP_LEFT_RIGHT) # Loading images to put on canvasscissor_p = ImageTk.PhotoImage(scissor_p)scissor_c = ImageTk.PhotoImage(scissor_c) # Selection imageimg_s = Image.open(\"Selection.jpeg\")img_s = img_s.resize((300, 130))img_s = ImageTk.PhotoImage(img_s) # Putting image on canvas on specific coordinatescanvas.create_image(0, 100, anchor=NW, image=img_p)canvas.create_image(500, 100, anchor=NW, image=img_c)canvas.create_image(0, 400, anchor=NW, image=img_s)canvas.create_image(500, 400, anchor=NW, image=img_s) # game functiondef game(player): select = [1, 2, 3] # Randomly selects option for computer computer = random.choice(select) # Setting image for player on canvas if player == 1: # Puts rock image on canvas canvas.create_image(0, 100, anchor=NW, image=rock_p) elif player == 2: # Puts paper image on canvas canvas.create_image(0, 100, anchor=NW, image=paper_p) else: # Puts scissor image on canvas canvas.create_image(0, 100, anchor=NW, image=scissor_p) # Setting image for computer on canvas if computer == 1: # Puts rock image on canvas canvas.create_image(500, 100, anchor=NW, image=rock_c) elif computer == 2: # Puts paper image on canvas canvas.create_image(500, 100, anchor=NW, image=paper_c) else: # Puts scissor image on canvas canvas.create_image(500, 100, anchor=NW, image=scissor_c) # Obtaining result by comparison if player == computer: # Case of DRAW res = 'Draw' # Case of player's win elif (player == 1 and computer == 3) or (player == 2 and computer == 1) or (player == 3 and computer == 2): res = 'You won' # Case of computer's win else: res = 'Computer won' # Putting result on canvas canvas.create_text(390, 600, text='Result:- ' + res, fill=\"black\", font=('Algerian', 25), tag='result') # Function for clear buttondef clear(): # Removes result from canvas canvas.delete('result') # Puts default image on canvas canvas.create_image(0, 100, anchor=NW, image=img_p) canvas.create_image(500, 100, anchor=NW, image=img_c) # Button for selecting rockrock_b = Button(root, text='Rock', command=lambda: game(1))rock_b.place(x=35, y=487) # Button for selecting paperpaper_b = Button(root, text='Paper', command=lambda: game(2))paper_b.place(x=128, y=487) # Button for selecting scissorscissor_b = Button(root, text='Scissor', command=lambda: game(3))scissor_b.place(x=220, y=487) # Button for clearclear_b = Button(root, text='CLEAR', font=('Times', 10, 'bold'), width=10, command=clear).place(x=370, y=28) root.mainloop()", "e": 10294, "s": 6002, "text": null }, { "code": null, "e": 10301, "s": 10294, "text": "Output" }, { "code": null, "e": 10327, "s": 10301, "text": "Utkarsh ShawChirag Bhatia" }, { "code": null, "e": 10340, "s": 10327, "text": "Utkarsh Shaw" }, { "code": null, "e": 10354, "s": 10340, "text": "Chirag Bhatia" }, { "code": null, "e": 10364, "s": 10354, "text": "chi251201" }, { "code": null, "e": 10377, "s": 10364, "text": "ProGeek 2021" }, { "code": null, "e": 10401, "s": 10377, "text": "Python Tkinter-projects" }, { "code": null, "e": 10417, "s": 10401, "text": "Python-projects" }, { "code": null, "e": 10432, "s": 10417, "text": "Python-tkinter" }, { "code": null, "e": 10440, "s": 10432, "text": "ProGeek" }, { "code": null, "e": 10448, "s": 10440, "text": "Project" }, { "code": null, "e": 10455, "s": 10448, "text": "Python" }, { "code": null, "e": 10553, "s": 10455, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 10634, "s": 10553, "text": "Project Idea - A website acting as transaction between oxygen sellers and buyers" }, { "code": null, "e": 10675, "s": 10634, "text": "Online Schooling System - Python Project" }, { "code": null, "e": 10726, "s": 10675, "text": "Project Idea | Anonymous Message Prank Game in PHP" }, { "code": null, "e": 10756, "s": 10726, "text": "Project Idea – Healthcare App" }, { "code": null, "e": 10779, "s": 10756, "text": "Project Idea - Fintech" }, { "code": null, "e": 10828, "s": 10779, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 10883, "s": 10828, "text": "Implementing Web Scraping in Python with BeautifulSoup" }, { "code": null, "e": 10916, "s": 10883, "text": "Working with zip files in Python" }, { "code": null, "e": 10938, "s": 10916, "text": "XML parsing in Python" } ]
Generating Strong Password using Python
27 Jan, 2022 Having a weak password is not good for a system that demands high confidentiality and security of user credentials. It turns out that people find it difficult to make up a strong password that is strong enough to prevent unauthorized users from memorizing it. This article uses a mixture of numbers, alphabets, and other symbols found on the computer keyboard to form a 12-character password which is unpredictable and cannot easily be memorized. The components of the password are represented in the form of arrays. Use the random method to select at least one character from each array of characters. Since the 12-character password is required, so fill the rest of the length of the password left with randomly selected characters from an array formed from the combination of all the characters needed in the final password. Anytime the password is generated, shuffle the password using random.shuffle() to ensure that the final password does not follow a particular pattern. Creating Random Password Generator Using Python | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersCreating Random Password Generator Using Python | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou'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.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 9:13•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=U_ZCiZ1TgOo" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> Python3 import randomimport array # maximum length of password needed# this can be changed to suit your password lengthMAX_LEN = 12 # declare arrays of the character that we need in out password# Represented as chars to enable easy string concatenationDIGITS = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] LOCASE_CHARACTERS = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] UPCASE_CHARACTERS = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'] SYMBOLS = ['@', '#', '$', '%', '=', ':', '?', '.', '/', '|', '~', '>', '*', '(', ')', '<'] # combines all the character arrays above to form one arrayCOMBINED_LIST = DIGITS + UPCASE_CHARACTERS + LOCASE_CHARACTERS + SYMBOLS # randomly select at least one character from each character set aboverand_digit = random.choice(DIGITS)rand_upper = random.choice(UPCASE_CHARACTERS)rand_lower = random.choice(LOCASE_CHARACTERS)rand_symbol = random.choice(SYMBOLS) # combine the character randomly selected above# at this stage, the password contains only 4 characters but# we want a 12-character passwordtemp_pass = rand_digit + rand_upper + rand_lower + rand_symbol # now that we are sure we have at least one character from each# set of characters, we fill the rest of# the password length by selecting randomly from the combined# list of character above.for x in range(MAX_LEN - 4): temp_pass = temp_pass + random.choice(COMBINED_LIST) # convert temporary password into array and shuffle to # prevent it from having a consistent pattern # where the beginning of the password is predictable temp_pass_list = array.array('u', temp_pass) random.shuffle(temp_pass_list) # traverse the temporary password array and append the chars# to form the passwordpassword = ""for x in temp_pass_list: password = password + x # print out passwordprint(password) Output : yf2byU$@zTg5 nikhilaggarwal3 vallabhwebdeveloper Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Introduction To PYTHON
[ { "code": null, "e": 52, "s": 24, "text": "\n27 Jan, 2022" }, { "code": null, "e": 314, "s": 52, "text": "Having a weak password is not good for a system that demands high confidentiality and security of user credentials. It turns out that people find it difficult to make up a strong password that is strong enough to prevent unauthorized users from memorizing it. " }, { "code": null, "e": 503, "s": 314, "text": "This article uses a mixture of numbers, alphabets, and other symbols found on the computer keyboard to form a 12-character password which is unpredictable and cannot easily be memorized. " }, { "code": null, "e": 573, "s": 503, "text": "The components of the password are represented in the form of arrays." }, { "code": null, "e": 659, "s": 573, "text": "Use the random method to select at least one character from each array of characters." }, { "code": null, "e": 1035, "s": 659, "text": "Since the 12-character password is required, so fill the rest of the length of the password left with randomly selected characters from an array formed from the combination of all the characters needed in the final password. Anytime the password is generated, shuffle the password using random.shuffle() to ensure that the final password does not follow a particular pattern." }, { "code": null, "e": 1947, "s": 1035, "text": "Creating Random Password Generator Using Python | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersCreating Random Password Generator Using Python | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou'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.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 9:13•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=U_ZCiZ1TgOo\" 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": 1955, "s": 1947, "text": "Python3" }, { "code": "import randomimport array # maximum length of password needed# this can be changed to suit your password lengthMAX_LEN = 12 # declare arrays of the character that we need in out password# Represented as chars to enable easy string concatenationDIGITS = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] LOCASE_CHARACTERS = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] UPCASE_CHARACTERS = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'] SYMBOLS = ['@', '#', '$', '%', '=', ':', '?', '.', '/', '|', '~', '>', '*', '(', ')', '<'] # combines all the character arrays above to form one arrayCOMBINED_LIST = DIGITS + UPCASE_CHARACTERS + LOCASE_CHARACTERS + SYMBOLS # randomly select at least one character from each character set aboverand_digit = random.choice(DIGITS)rand_upper = random.choice(UPCASE_CHARACTERS)rand_lower = random.choice(LOCASE_CHARACTERS)rand_symbol = random.choice(SYMBOLS) # combine the character randomly selected above# at this stage, the password contains only 4 characters but# we want a 12-character passwordtemp_pass = rand_digit + rand_upper + rand_lower + rand_symbol # now that we are sure we have at least one character from each# set of characters, we fill the rest of# the password length by selecting randomly from the combined# list of character above.for x in range(MAX_LEN - 4): temp_pass = temp_pass + random.choice(COMBINED_LIST) # convert temporary password into array and shuffle to # prevent it from having a consistent pattern # where the beginning of the password is predictable temp_pass_list = array.array('u', temp_pass) random.shuffle(temp_pass_list) # traverse the temporary password array and append the chars# to form the passwordpassword = \"\"for x in temp_pass_list: password = password + x # print out passwordprint(password)", "e": 4055, "s": 1955, "text": null }, { "code": null, "e": 4066, "s": 4055, "text": "Output : " }, { "code": null, "e": 4079, "s": 4066, "text": "yf2byU$@zTg5" }, { "code": null, "e": 4097, "s": 4081, "text": "nikhilaggarwal3" }, { "code": null, "e": 4117, "s": 4097, "text": "vallabhwebdeveloper" }, { "code": null, "e": 4124, "s": 4117, "text": "Python" }, { "code": null, "e": 4222, "s": 4124, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4240, "s": 4222, "text": "Python Dictionary" }, { "code": null, "e": 4282, "s": 4240, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 4304, "s": 4282, "text": "Enumerate() in Python" }, { "code": null, "e": 4339, "s": 4304, "text": "Read a file line by line in Python" }, { "code": null, "e": 4365, "s": 4339, "text": "Python String | replace()" }, { "code": null, "e": 4397, "s": 4365, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 4426, "s": 4397, "text": "*args and **kwargs in Python" }, { "code": null, "e": 4453, "s": 4426, "text": "Python Classes and Objects" }, { "code": null, "e": 4483, "s": 4453, "text": "Iterate over a list in Python" } ]
JavaScript | ‘===’ vs ‘==’Comparison Operator
25 May, 2022 In Javascript(ES6), there are four ways to test equality which are listed below: Using ‘==’ operator Using ‘===’ operator SameValueZero: used mainly in sets, maps and arrays. SameValue: used elsewhere Now, our main concern is getting to know the difference between the ‘==’ and ‘===’ operators that the javascript provides, though they look similar, yet they are very different. ‘==’ operator: In Javascript, the ‘==’ operator is also known as loose equality operator which is mainly used to compare two value on both the sides and then return true or false. This operator checks equality only after converting both the values to a common type i.e type coercion. Note: Type coercion means that the two values are compared only after attempting to convert them into the same type. Let’s look at all the value in which the ‘==’ operator will return true. Example: javascript // '==' operatorconsole.log(21 == 21);console.log(21 == '21');console.log('food is love'=='food is love');console.log(true == 1);console.log(false == 0);console.log(null == undefined); Output: In the above code, when we compare 21 with ’21’ the javascript will convert the ’21’ into the number value of 21 and hence we get true, similar thing happens when we try to check if ‘true == 1’, in that case, the javascript basically converts 1 into a truthy value and then compares and return the boolean true. The case of (null == undefined) is special as when we compare these values we get true, but it’s not crystal clear why?. In javascript there are two types of values: true or false True ‘0’ ‘false’ // false wrapped in string. [] {} function(){} False ” or “” // empty string false 0 null undefined NaN // not-a-number So both null and undefined are false values and they represent an ’empty’ value or undefined in js, hence the comparison with ‘==’ operator returns true. Now, let’s look at all the value in which the ‘==’ operator will return false. Example: javascript // '==' operatorconsole.log(21 == 32);console.log(21 == '32');console.log(true == 0);console.log(null == false); Output: In the above code when we compare null with false we get false, as null being a primitive data type it can never be equal to a boolean value, even though they belong to the same false group. ‘===’ operator: Also known as strict equality operator, it compares both the value and the type that is why the name “strict equality”. Let’s see some code where ‘===’ operator will return true. Example: javascript // '===' operatorconsole.log('hello world' === 'hello world');console.log(true === true);console.log(5 === 5); Output: Simply checking the types and values at both the sides and then just printing out the boolean true or false. Some example where it will return false. javascript // '===' operatorconsole.log(true === 1);console.log(true === 'true');console.log(5 === '5'); Output: immukul surinderdawra388 javascript-basics javascript-operators 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 Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array Roadmap to Learn JavaScript For Beginners Difference Between PUT and PATCH Request How to Open URL in New Tab using JavaScript ? How to get character array from string in JavaScript? Node.js | fs.writeFileSync() Method How do you run JavaScript script through the Terminal? JavaScript | Promises
[ { "code": null, "e": 54, "s": 26, "text": "\n25 May, 2022" }, { "code": null, "e": 135, "s": 54, "text": "In Javascript(ES6), there are four ways to test equality which are listed below:" }, { "code": null, "e": 155, "s": 135, "text": "Using ‘==’ operator" }, { "code": null, "e": 176, "s": 155, "text": "Using ‘===’ operator" }, { "code": null, "e": 229, "s": 176, "text": "SameValueZero: used mainly in sets, maps and arrays." }, { "code": null, "e": 255, "s": 229, "text": "SameValue: used elsewhere" }, { "code": null, "e": 917, "s": 255, "text": "Now, our main concern is getting to know the difference between the ‘==’ and ‘===’ operators that the javascript provides, though they look similar, yet they are very different. ‘==’ operator: In Javascript, the ‘==’ operator is also known as loose equality operator which is mainly used to compare two value on both the sides and then return true or false. This operator checks equality only after converting both the values to a common type i.e type coercion. Note: Type coercion means that the two values are compared only after attempting to convert them into the same type. Let’s look at all the value in which the ‘==’ operator will return true. Example: " }, { "code": null, "e": 928, "s": 917, "text": "javascript" }, { "code": "// '==' operatorconsole.log(21 == 21);console.log(21 == '21');console.log('food is love'=='food is love');console.log(true == 1);console.log(false == 0);console.log(null == undefined);", "e": 1113, "s": 928, "text": null }, { "code": null, "e": 1619, "s": 1113, "text": "Output: In the above code, when we compare 21 with ’21’ the javascript will convert the ’21’ into the number value of 21 and hence we get true, similar thing happens when we try to check if ‘true == 1’, in that case, the javascript basically converts 1 into a truthy value and then compares and return the boolean true. The case of (null == undefined) is special as when we compare these values we get true, but it’s not crystal clear why?. In javascript there are two types of values: true or false True" }, { "code": null, "e": 1623, "s": 1619, "text": "‘0’" }, { "code": null, "e": 1659, "s": 1623, "text": "‘false’ // false wrapped in string." }, { "code": null, "e": 1662, "s": 1659, "text": "[]" }, { "code": null, "e": 1665, "s": 1662, "text": "{}" }, { "code": null, "e": 1678, "s": 1665, "text": "function(){}" }, { "code": null, "e": 1684, "s": 1678, "text": "False" }, { "code": null, "e": 1708, "s": 1684, "text": "” or “” // empty string" }, { "code": null, "e": 1714, "s": 1708, "text": "false" }, { "code": null, "e": 1716, "s": 1714, "text": "0" }, { "code": null, "e": 1721, "s": 1716, "text": "null" }, { "code": null, "e": 1731, "s": 1721, "text": "undefined" }, { "code": null, "e": 1751, "s": 1731, "text": "NaN // not-a-number" }, { "code": null, "e": 1994, "s": 1751, "text": "So both null and undefined are false values and they represent an ’empty’ value or undefined in js, hence the comparison with ‘==’ operator returns true. Now, let’s look at all the value in which the ‘==’ operator will return false. Example: " }, { "code": null, "e": 2005, "s": 1994, "text": "javascript" }, { "code": "// '==' operatorconsole.log(21 == 32);console.log(21 == '32');console.log(true == 0);console.log(null == false);", "e": 2118, "s": 2005, "text": null }, { "code": null, "e": 2523, "s": 2118, "text": "Output: In the above code when we compare null with false we get false, as null being a primitive data type it can never be equal to a boolean value, even though they belong to the same false group. ‘===’ operator: Also known as strict equality operator, it compares both the value and the type that is why the name “strict equality”. Let’s see some code where ‘===’ operator will return true. Example: " }, { "code": null, "e": 2534, "s": 2523, "text": "javascript" }, { "code": "// '===' operatorconsole.log('hello world' === 'hello world');console.log(true === true);console.log(5 === 5);", "e": 2645, "s": 2534, "text": null }, { "code": null, "e": 2805, "s": 2645, "text": "Output: Simply checking the types and values at both the sides and then just printing out the boolean true or false. Some example where it will return false. " }, { "code": null, "e": 2816, "s": 2805, "text": "javascript" }, { "code": "// '===' operatorconsole.log(true === 1);console.log(true === 'true');console.log(5 === '5');", "e": 2910, "s": 2816, "text": null }, { "code": null, "e": 2919, "s": 2910, "text": "Output: " }, { "code": null, "e": 2927, "s": 2919, "text": "immukul" }, { "code": null, "e": 2944, "s": 2927, "text": "surinderdawra388" }, { "code": null, "e": 2962, "s": 2944, "text": "javascript-basics" }, { "code": null, "e": 2983, "s": 2962, "text": "javascript-operators" }, { "code": null, "e": 2994, "s": 2983, "text": "JavaScript" }, { "code": null, "e": 3092, "s": 2994, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3153, "s": 3092, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3225, "s": 3153, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 3265, "s": 3225, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 3307, "s": 3265, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 3348, "s": 3307, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 3394, "s": 3348, "text": "How to Open URL in New Tab using JavaScript ?" }, { "code": null, "e": 3448, "s": 3394, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 3484, "s": 3448, "text": "Node.js | fs.writeFileSync() Method" }, { "code": null, "e": 3539, "s": 3484, "text": "How do you run JavaScript script through the Terminal?" } ]
How to setup cron jobs in Ubuntu
27 Feb, 2020 The Cron software utility is a time-based job scheduler in Unix-like operating systems. Cron allows Linux and Unix users to run commands or scripts at a given time and date. Once can schedule scripts to be executed periodically. It is usually used for system admin jobs such as backups or cleaning/tmp/ directories and more. The following steps to be followed to set up a cron job in Ubuntu: Connect to server and update the system:Before begin with setting up crontab connect the server and update the system software to the latest version available. We can do this by using below command:#apt-get update && #apt-get upgrade #apt-get update && #apt-get upgrade Check if cron package is installed:To check if cron is installed, run the following command –#dpkg -l cron #dpkg -l cron If cron is not installed, install the cron package on Ubuntu:One can Install the cron package with package Manager using the following command-#apt-get install cron #apt-get install cron Verify if cron service is running:To check whether the cron service is running on the system, we can use the following command-#systemctl status cron #systemctl status cron Configure cron job on ubuntu:In order to set up cron jobs, one needs to modify the /etc/crontab file which can be done by only root user. You can edit the crontab file with following text editor.Example:#nano /etc/crontab Example: #nano /etc/crontab Before we take example of cron tab execution let’s understand the common syntax of cron tab: Syntax: * * * * * /path/to/command arg1 arg2 OR * * * * * /root/backup.sh In the syntax first * stand for representing minutes [0-59]. Second * stands for representing hour[0-23]. Third * stand for representing day [0-31]. Fourth star stands for representing month[0-12]. Fifth * stand for representing day of the week[0-7]. After all step for installation of cron tab and understanding common syntax, let’s execute a cron tab with suitable example. Example #1: If we want to schedule a backup on first day of each month at 9 PM, the following command performs this operation. #crontab -e //install your cron job by running this command. // Append the following entry. 0 9 1 * * /path/to/script/backup-script.sh Example #2: Set up and run php script as cron job to run script every day at 10 AM. #crontab -e //add cron job // Append the following entry. 0 10 * * * /path/to/myphpscript.php Following options are available in crontab:crontab -l : List the all your cron jobs.crontab -r : Delete the current cron jobs. For more information about cron, one can check the manual pages using: man cron man crontab Samdare B linux-command Picked Linux-Unix TechTips Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n27 Feb, 2020" }, { "code": null, "e": 353, "s": 28, "text": "The Cron software utility is a time-based job scheduler in Unix-like operating systems. Cron allows Linux and Unix users to run commands or scripts at a given time and date. Once can schedule scripts to be executed periodically. It is usually used for system admin jobs such as backups or cleaning/tmp/ directories and more." }, { "code": null, "e": 420, "s": 353, "text": "The following steps to be followed to set up a cron job in Ubuntu:" }, { "code": null, "e": 654, "s": 420, "text": "Connect to server and update the system:Before begin with setting up crontab connect the server and update the system software to the latest version available. We can do this by using below command:#apt-get update && #apt-get upgrade" }, { "code": null, "e": 690, "s": 654, "text": "#apt-get update && #apt-get upgrade" }, { "code": null, "e": 798, "s": 690, "text": "Check if cron package is installed:To check if cron is installed, run the following command –#dpkg -l cron " }, { "code": null, "e": 813, "s": 798, "text": "#dpkg -l cron " }, { "code": null, "e": 978, "s": 813, "text": "If cron is not installed, install the cron package on Ubuntu:One can Install the cron package with package Manager using the following command-#apt-get install cron" }, { "code": null, "e": 1000, "s": 978, "text": "#apt-get install cron" }, { "code": null, "e": 1150, "s": 1000, "text": "Verify if cron service is running:To check whether the cron service is running on the system, we can use the following command-#systemctl status cron" }, { "code": null, "e": 1173, "s": 1150, "text": "#systemctl status cron" }, { "code": null, "e": 1395, "s": 1173, "text": "Configure cron job on ubuntu:In order to set up cron jobs, one needs to modify the /etc/crontab file which can be done by only root user. You can edit the crontab file with following text editor.Example:#nano /etc/crontab" }, { "code": null, "e": 1404, "s": 1395, "text": "Example:" }, { "code": null, "e": 1423, "s": 1404, "text": "#nano /etc/crontab" }, { "code": null, "e": 1516, "s": 1423, "text": "Before we take example of cron tab execution let’s understand the common syntax of cron tab:" }, { "code": null, "e": 1524, "s": 1516, "text": "Syntax:" }, { "code": null, "e": 1590, "s": 1524, "text": "* * * * * /path/to/command arg1 arg2\nOR\n* * * * * /root/backup.sh" }, { "code": null, "e": 1841, "s": 1590, "text": "In the syntax first * stand for representing minutes [0-59]. Second * stands for representing hour[0-23]. Third * stand for representing day [0-31]. Fourth star stands for representing month[0-12]. Fifth * stand for representing day of the week[0-7]." }, { "code": null, "e": 1967, "s": 1841, "text": " After all step for installation of cron tab and understanding common syntax, let’s execute a cron tab with suitable example." }, { "code": null, "e": 2094, "s": 1967, "text": "Example #1: If we want to schedule a backup on first day of each month at 9 PM, the following command performs this operation." }, { "code": null, "e": 2230, "s": 2094, "text": "#crontab -e //install your cron job by running this command.\n// Append the following entry.\n\n0 9 1 * * /path/to/script/backup-script.sh" }, { "code": null, "e": 2315, "s": 2230, "text": " Example #2: Set up and run php script as cron job to run script every day at 10 AM." }, { "code": null, "e": 2410, "s": 2315, "text": "#crontab -e //add cron job\n\n// Append the following entry.\n0 10 * * * /path/to/myphpscript.php" }, { "code": null, "e": 2537, "s": 2410, "text": "Following options are available in crontab:crontab -l : List the all your cron jobs.crontab -r : Delete the current cron jobs." }, { "code": null, "e": 2608, "s": 2537, "text": "For more information about cron, one can check the manual pages using:" }, { "code": null, "e": 2630, "s": 2608, "text": "man cron\nman crontab " }, { "code": null, "e": 2640, "s": 2630, "text": "Samdare B" }, { "code": null, "e": 2654, "s": 2640, "text": "linux-command" }, { "code": null, "e": 2661, "s": 2654, "text": "Picked" }, { "code": null, "e": 2672, "s": 2661, "text": "Linux-Unix" }, { "code": null, "e": 2681, "s": 2672, "text": "TechTips" } ]
SQL Server – PATINDEX() Function
23 Sep, 2021 The PATINDEX() function in the SQL server is used to return the starting index of the first occurrence of a pattern in a string or a specified expression. It returns zero if the pattern is not found. It returns NULL if either pattern or expression is NULL. Starting index is 1. PATINDEX ( '%pattern%' , expression ) There are two parameters and both are required. Pattern – This is the sequence to be found in the string that must be surrounded by %. Other wildcard characters can be used in patterns. The pattern has a limit of 8000 characters. Other wildcard characters are ‘%’ , ‘-‘ , ‘[]’ , ‘[^]’. Expression – A string that is searched for the specified pattern. The function PATINDEX() is applicable to the following databases. SQL Server (all supported versions) Azure SQL Database Azure SQL Data Warehouse Azure SQL Managed Instance Azure Synapse Analytics Analytics Platform System (PDW) Parallel Data Warehouse Suppose if we want to find the first occurrence of ‘ek’ in the string ‘GeeksforGeeks’.then query will be like: Query: SELECT PATINDEX('%ek%', 'GeeksforGeeks'); Output: 3 Now if we finding the first occurrence of the letter ‘z’ in the string ‘GeeksforGeeks’. Query: SELECT PATINDEX('%[z]%', 'GeeksforGeeks'); Output: It returns 0 because the given string does not contain the letter ‘z. 0 Take another example for finding the first occurrence of the symbol in the string ‘How are you?’. Query: SELECT position = PATINDEX('%[^ 0-9A-z]%', 'How are you?'); Output: 12 SQL-Server SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Update Multiple Columns in Single Update Statement in SQL? Window functions in SQL What is Temporary Table in SQL? SQL | Sub queries in From Clause SQL using Python RANK() Function in SQL Server SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter SQL Query to Convert VARCHAR to INT SQL Query to Compare Two Dates How to Write a SQL Query For a Specific Date Range and Date Time?
[ { "code": null, "e": 52, "s": 24, "text": "\n23 Sep, 2021" }, { "code": null, "e": 208, "s": 52, "text": "The PATINDEX() function in the SQL server is used to return the starting index of the first occurrence of a pattern in a string or a specified expression. " }, { "code": null, "e": 253, "s": 208, "text": "It returns zero if the pattern is not found." }, { "code": null, "e": 310, "s": 253, "text": "It returns NULL if either pattern or expression is NULL." }, { "code": null, "e": 331, "s": 310, "text": "Starting index is 1." }, { "code": null, "e": 369, "s": 331, "text": "PATINDEX ( '%pattern%' , expression )" }, { "code": null, "e": 417, "s": 369, "text": "There are two parameters and both are required." }, { "code": null, "e": 655, "s": 417, "text": "Pattern – This is the sequence to be found in the string that must be surrounded by %. Other wildcard characters can be used in patterns. The pattern has a limit of 8000 characters. Other wildcard characters are ‘%’ , ‘-‘ , ‘[]’ , ‘[^]’." }, { "code": null, "e": 721, "s": 655, "text": "Expression – A string that is searched for the specified pattern." }, { "code": null, "e": 787, "s": 721, "text": "The function PATINDEX() is applicable to the following databases." }, { "code": null, "e": 823, "s": 787, "text": "SQL Server (all supported versions)" }, { "code": null, "e": 842, "s": 823, "text": "Azure SQL Database" }, { "code": null, "e": 867, "s": 842, "text": "Azure SQL Data Warehouse" }, { "code": null, "e": 894, "s": 867, "text": "Azure SQL Managed Instance" }, { "code": null, "e": 950, "s": 894, "text": "Azure Synapse Analytics Analytics Platform System (PDW)" }, { "code": null, "e": 974, "s": 950, "text": "Parallel Data Warehouse" }, { "code": null, "e": 1085, "s": 974, "text": "Suppose if we want to find the first occurrence of ‘ek’ in the string ‘GeeksforGeeks’.then query will be like:" }, { "code": null, "e": 1092, "s": 1085, "text": "Query:" }, { "code": null, "e": 1134, "s": 1092, "text": "SELECT PATINDEX('%ek%', 'GeeksforGeeks');" }, { "code": null, "e": 1142, "s": 1134, "text": "Output:" }, { "code": null, "e": 1144, "s": 1142, "text": "3" }, { "code": null, "e": 1232, "s": 1144, "text": "Now if we finding the first occurrence of the letter ‘z’ in the string ‘GeeksforGeeks’." }, { "code": null, "e": 1239, "s": 1232, "text": "Query:" }, { "code": null, "e": 1282, "s": 1239, "text": "SELECT PATINDEX('%[z]%', 'GeeksforGeeks');" }, { "code": null, "e": 1290, "s": 1282, "text": "Output:" }, { "code": null, "e": 1360, "s": 1290, "text": "It returns 0 because the given string does not contain the letter ‘z." }, { "code": null, "e": 1362, "s": 1360, "text": "0" }, { "code": null, "e": 1460, "s": 1362, "text": "Take another example for finding the first occurrence of the symbol in the string ‘How are you?’." }, { "code": null, "e": 1467, "s": 1460, "text": "Query:" }, { "code": null, "e": 1527, "s": 1467, "text": "SELECT position = PATINDEX('%[^ 0-9A-z]%', 'How are you?');" }, { "code": null, "e": 1535, "s": 1527, "text": "Output:" }, { "code": null, "e": 1538, "s": 1535, "text": "12" }, { "code": null, "e": 1549, "s": 1538, "text": "SQL-Server" }, { "code": null, "e": 1553, "s": 1549, "text": "SQL" }, { "code": null, "e": 1557, "s": 1553, "text": "SQL" }, { "code": null, "e": 1655, "s": 1557, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1721, "s": 1655, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 1745, "s": 1721, "text": "Window functions in SQL" }, { "code": null, "e": 1777, "s": 1745, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 1810, "s": 1777, "text": "SQL | Sub queries in From Clause" }, { "code": null, "e": 1827, "s": 1810, "text": "SQL using Python" }, { "code": null, "e": 1857, "s": 1827, "text": "RANK() Function in SQL Server" }, { "code": null, "e": 1935, "s": 1857, "text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter" }, { "code": null, "e": 1971, "s": 1935, "text": "SQL Query to Convert VARCHAR to INT" }, { "code": null, "e": 2002, "s": 1971, "text": "SQL Query to Compare Two Dates" } ]
PHP strpos() and stripos() Functions
09 May, 2022 In this article, we will see how to find the position of the first occurrence of a string in another string using strpos() and stripos() Functions in PHP, & will see their implementation through the examples. Both the strpos() and stripos() Functions in PHP are binary-safe which means the function will handle its input as a raw byte stream and disregard every textual content it may contain. Here, the function will work correctly while passing arbitrary binary data ie., a string having non-ASCII bytes &/or null-bytes. strpos() Function: This function helps us to find the position of the first occurrence of a string in another string. This returns an integer value of the position of the first occurrence of the string. This function is case-sensitive, which means that it treats upper-case and lower-case characters differently. Syntax: strpos(original_str, search_str, start_pos); Parameter value: Out of the three parameters specified in the syntax, two are mandatory and one is optional. The three parameters are described below: original_str: This is a mandatory parameter that refers to the original string in which we need to search the occurrence of the required string. search_str: This is a mandatory parameter that refers to the string that we need to search. start_pos: This is an optional parameter that refers to the position of the string from where the search must begin. Return Type: This function returns an integer value that represents the index of original_str where the string search_str first occurs. Example: This example illustrates the strpos() function that specifies the position of the occurrence of a string in another string. PHP <?php // PHP code to search for a specific string's position // first occurrence using strpos() case-sensitive function function Search($search, $string) { $position = strpos($string, $search, 5); if (is_numeric($position)) { return "Found at position: " . $position; } else { return "Not Found"; } } // Driver Code $string = "Welcome to GeeksforGeeks"; $search = "Geeks"; echo Search($search, $string);?> Output: Found at position 11 stripos() Function: This function also helps us to find the position of the first occurrence of a string in another string. This returns an integer value of the position of the first occurrence of the string. This function is case-insensitive, which means it treats both upper-case and lower-case characters equally. This function works similarly as strpos(), the difference is that it is case in-sensitive whereas strpos() is case sensitive. Syntax: stripos(original_str, search_str, start_pos); Parameter value: Out of the three parameters specified in the syntax, two are mandatory and one is optional. original_str: This is a mandatory parameter that refers to the original string in which we need to search the occurrence of the required string. search_str: This is a mandatory parameter that refers to the string that we need to find. start_pos: This is an optional parameter that refers to the position of the string from where the search must begin. Return Type: This function returns an integer value that represents the index of original_str where the string search_str first occurs. Example: This example illustrates the stripos() function that specifies the position of the occurrence of a string in another string. PHP <?php // PHP code to search for a specific string // first occurrence using stripos() case-insensitive function function Search($search, $string) { $position = stripos($string, $search, 5); if ($position == true) { return "Found at position " . $position; } else { return "Not Found"; } } // Driver Code $string = "Welcome to GeeksforGeeks"; $search = "geeks"; echo Search($search, $string);?> Output: Found at position 11 Let us understand these functions in a tabular form -: Its syntax is -: strpos(string,find,start) Its syntax is -: stripos(string,find,start) harrykunz0 surindertarika1234 bhaskargeeksforgeeks mayank007rawa PHP-function PHP-string PHP Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Insert Form Data into Database using PHP ? How to convert array to string in PHP ? How to Upload Image into Database and Display it using PHP ? How to check whether an array is empty using PHP? PHP | Converting string to Date and DateTime Top 10 Projects For Beginners To Practice HTML and CSS Skills Installation of Node.js on Linux Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n09 May, 2022" }, { "code": null, "e": 237, "s": 28, "text": "In this article, we will see how to find the position of the first occurrence of a string in another string using strpos() and stripos() Functions in PHP, & will see their implementation through the examples." }, { "code": null, "e": 551, "s": 237, "text": "Both the strpos() and stripos() Functions in PHP are binary-safe which means the function will handle its input as a raw byte stream and disregard every textual content it may contain. Here, the function will work correctly while passing arbitrary binary data ie., a string having non-ASCII bytes &/or null-bytes." }, { "code": null, "e": 864, "s": 551, "text": "strpos() Function: This function helps us to find the position of the first occurrence of a string in another string. This returns an integer value of the position of the first occurrence of the string. This function is case-sensitive, which means that it treats upper-case and lower-case characters differently." }, { "code": null, "e": 873, "s": 864, "text": "Syntax: " }, { "code": null, "e": 918, "s": 873, "text": "strpos(original_str, search_str, start_pos);" }, { "code": null, "e": 1069, "s": 918, "text": "Parameter value: Out of the three parameters specified in the syntax, two are mandatory and one is optional. The three parameters are described below:" }, { "code": null, "e": 1214, "s": 1069, "text": "original_str: This is a mandatory parameter that refers to the original string in which we need to search the occurrence of the required string." }, { "code": null, "e": 1306, "s": 1214, "text": "search_str: This is a mandatory parameter that refers to the string that we need to search." }, { "code": null, "e": 1423, "s": 1306, "text": "start_pos: This is an optional parameter that refers to the position of the string from where the search must begin." }, { "code": null, "e": 1559, "s": 1423, "text": "Return Type: This function returns an integer value that represents the index of original_str where the string search_str first occurs." }, { "code": null, "e": 1692, "s": 1559, "text": "Example: This example illustrates the strpos() function that specifies the position of the occurrence of a string in another string." }, { "code": null, "e": 1696, "s": 1692, "text": "PHP" }, { "code": "<?php // PHP code to search for a specific string's position // first occurrence using strpos() case-sensitive function function Search($search, $string) { $position = strpos($string, $search, 5); if (is_numeric($position)) { return \"Found at position: \" . $position; } else { return \"Not Found\"; } } // Driver Code $string = \"Welcome to GeeksforGeeks\"; $search = \"Geeks\"; echo Search($search, $string);?>", "e": 2206, "s": 1696, "text": null }, { "code": null, "e": 2214, "s": 2206, "text": "Output:" }, { "code": null, "e": 2235, "s": 2214, "text": "Found at position 11" }, { "code": null, "e": 2678, "s": 2235, "text": "stripos() Function: This function also helps us to find the position of the first occurrence of a string in another string. This returns an integer value of the position of the first occurrence of the string. This function is case-insensitive, which means it treats both upper-case and lower-case characters equally. This function works similarly as strpos(), the difference is that it is case in-sensitive whereas strpos() is case sensitive." }, { "code": null, "e": 2688, "s": 2678, "text": "Syntax: " }, { "code": null, "e": 2734, "s": 2688, "text": "stripos(original_str, search_str, start_pos);" }, { "code": null, "e": 2843, "s": 2734, "text": "Parameter value: Out of the three parameters specified in the syntax, two are mandatory and one is optional." }, { "code": null, "e": 2988, "s": 2843, "text": "original_str: This is a mandatory parameter that refers to the original string in which we need to search the occurrence of the required string." }, { "code": null, "e": 3078, "s": 2988, "text": "search_str: This is a mandatory parameter that refers to the string that we need to find." }, { "code": null, "e": 3195, "s": 3078, "text": "start_pos: This is an optional parameter that refers to the position of the string from where the search must begin." }, { "code": null, "e": 3331, "s": 3195, "text": "Return Type: This function returns an integer value that represents the index of original_str where the string search_str first occurs." }, { "code": null, "e": 3465, "s": 3331, "text": "Example: This example illustrates the stripos() function that specifies the position of the occurrence of a string in another string." }, { "code": null, "e": 3469, "s": 3465, "text": "PHP" }, { "code": "<?php // PHP code to search for a specific string // first occurrence using stripos() case-insensitive function function Search($search, $string) { $position = stripos($string, $search, 5); if ($position == true) { return \"Found at position \" . $position; } else { return \"Not Found\"; } } // Driver Code $string = \"Welcome to GeeksforGeeks\"; $search = \"geeks\"; echo Search($search, $string);?>", "e": 3967, "s": 3469, "text": null }, { "code": null, "e": 3976, "s": 3967, "text": "Output: " }, { "code": null, "e": 3997, "s": 3976, "text": "Found at position 11" }, { "code": null, "e": 4052, "s": 3997, "text": "Let us understand these functions in a tabular form -:" }, { "code": null, "e": 4069, "s": 4052, "text": "Its syntax is -:" }, { "code": null, "e": 4095, "s": 4069, "text": "strpos(string,find,start)" }, { "code": null, "e": 4112, "s": 4095, "text": "Its syntax is -:" }, { "code": null, "e": 4139, "s": 4112, "text": "stripos(string,find,start)" }, { "code": null, "e": 4150, "s": 4139, "text": "harrykunz0" }, { "code": null, "e": 4169, "s": 4150, "text": "surindertarika1234" }, { "code": null, "e": 4190, "s": 4169, "text": "bhaskargeeksforgeeks" }, { "code": null, "e": 4204, "s": 4190, "text": "mayank007rawa" }, { "code": null, "e": 4217, "s": 4204, "text": "PHP-function" }, { "code": null, "e": 4228, "s": 4217, "text": "PHP-string" }, { "code": null, "e": 4232, "s": 4228, "text": "PHP" }, { "code": null, "e": 4249, "s": 4232, "text": "Web Technologies" }, { "code": null, "e": 4253, "s": 4249, "text": "PHP" }, { "code": null, "e": 4351, "s": 4253, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4401, "s": 4351, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 4441, "s": 4401, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 4502, "s": 4441, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 4552, "s": 4502, "text": "How to check whether an array is empty using PHP?" }, { "code": null, "e": 4597, "s": 4552, "text": "PHP | Converting string to Date and DateTime" }, { "code": null, "e": 4659, "s": 4597, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 4692, "s": 4659, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 4753, "s": 4692, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 4803, "s": 4753, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Maximum Product Subarray
06 Jul, 2022 Given an array that contains both positive and negative integers, find the product of the maximum product subarray. Expected Time complexity is O(n) and only O(1) extra space can be used. Examples: Input: arr[] = {6, -3, -10, 0, 2} Output: 180 // The subarray is {6, -3, -10} Input: arr[] = {-1, -3, -10, 0, 60} Output: 60 // The subarray is {60} Input: arr[] = {-2, -40, 0, -2, -3} Output: 80 // The subarray is {-2, -40} Naive Solution: The idea is to traverse over every contiguous subarrays, find the product of each of these subarrays and return the maximum product from these results. Below is the implementation of the above approach. C++ C Java Python3 C# Javascript // C++ program to find Maximum Product Subarray#include <bits/stdc++.h>using namespace std; /* Returns the product of max product subarray.*/int maxSubarrayProduct(int arr[], int n){ // Initializing result int result = arr[0]; for (int i = 0; i < n; i++) { int mul = arr[i]; // traversing in current subarray for (int j = i + 1; j < n; j++) { // updating result every time // to keep an eye over the maximum product result = max(result, mul); mul *= arr[j]; } // updating the result for (n-1)th index. result = max(result, mul); } return result;} // Driver codeint main(){ int arr[] = { 1, -2, -3, 0, 7, -8, -2 }; int n = sizeof(arr) / sizeof(arr[0]); cout << "Maximum Sub array product is " << maxSubarrayProduct(arr, n); return 0;} // This code is contributed by Aditya Kumar (adityakumar129) // C program to find Maximum Product Subarray#include <stdio.h> // Find maximum between two numbers.int max(int num1, int num2){ return (num1 > num2) ? num1 : num2;} /* Returns the product of max product subarray.*/int maxSubarrayProduct(int arr[], int n){ // Initializing result int result = arr[0]; for (int i = 0; i < n; i++) { int mul = arr[i]; // traversing in current subarray for (int j = i + 1; j < n; j++) { // updating result every time // to keep an eye over the maximum product result = max(result, mul); mul *= arr[j]; } // updating the result for (n-1)th index. result = max(result, mul); } return result;} // Driver codeint main(){ int arr[] = { 1, -2, -3, 0, 7, -8, -2 }; int n = sizeof(arr) / sizeof(arr[0]); printf("Maximum Sub array product is %d ", maxSubarrayProduct(arr, n)); return 0;} // This code is contributed by Aditya Kumar (adityakumar129) // Java program to find maximum product subarrayimport java.io.*; class GFG { /* Returns the product of max product subarray.*/ static int maxSubarrayProduct(int arr[]) { // Initializing result int result = arr[0]; int n = arr.length; for (int i = 0; i < n; i++) { int mul = arr[i]; // traversing in current subarray for (int j = i + 1; j < n; j++) { // updating result every time to keep an eye // over the maximum product result = Math.max(result, mul); mul *= arr[j]; } // updating the result for (n-1)th index. result = Math.max(result, mul); } return result; } // Driver Code public static void main(String[] args) { int arr[] = { 1, -2, -3, 0, 7, -8, -2 }; System.out.println("Maximum Sub array product is " + maxSubarrayProduct(arr)); }} // This code is contributed by Aditya Kumar (adityakumar129) # Python3 program to find Maximum Product Subarray # Returns the product of max product subarray.def maxSubarrayProduct(arr, n): # Initializing result result = arr[0] for i in range(n): mul = arr[i] # traversing in current subarray for j in range(i + 1, n): # updating result every time # to keep an eye over the maximum product result = max(result, mul) mul *= arr[j] # updating the result for (n-1)th index. result = max(result, mul) return result # Driver codearr = [ 1, -2, -3, 0, 7, -8, -2 ]n = len(arr)print("Maximum Sub array product is" , maxSubarrayProduct(arr, n)) # This code is contributed by divyeshrabadiya07 // C# program to find maximum product subarrayusing System; class GFG{ // Returns the product of max product subarraystatic int maxSubarrayProduct(int []arr){ // Initializing result int result = arr[0]; int n = arr.Length; for(int i = 0; i < n; i++) { int mul = arr[i]; // Traversing in current subarray for(int j = i + 1; j < n; j++) { // Updating result every time // to keep an eye over the // maximum product result = Math.Max(result, mul); mul *= arr[j]; } // Updating the result for (n-1)th index result = Math.Max(result, mul); } return result;} // Driver Codepublic static void Main(String[] args){ int []arr = { 1, -2, -3, 0, 7, -8, -2 }; Console.Write("Maximum Sub array product is " + maxSubarrayProduct(arr));}} // This code is contributed by shivanisinghss2110 <script> // Javascript program to find Maximum Product Subarray /* Returns the product of max product subarray.*/function maxSubarrayProduct(arr, n){ // Initializing result let result = arr[0]; for (let i = 0; i < n; i++) { let mul = arr[i]; // traversing in current subarray for (let j = i + 1; j < n; j++) { // updating result every time // to keep an eye over the maximum product result = Math.max(result, mul); mul *= arr[j]; } // updating the result for (n-1)th index. result = Math.max(result, mul); } return result;} // Driver code let arr = [ 1, -2, -3, 0, 7, -8, -2 ]; let n = arr.length; document.write("Maximum Sub array product is " + maxSubarrayProduct(arr, n)); // This code is contributed by Mayank Tyagi </script> Maximum Sub array product is 112 Time Complexity: O(N2)Auxiliary Space: O(1) Efficient Solution: The following solution assumes that the given input array always has a positive output. The solution works for all cases mentioned above. It doesn’t work for arrays like {0, 0, -20, 0}, {0, 0, 0}.. etc. The solution can be easily modified to handle this case. It is similar to Largest Sum Contiguous Subarray problem. The only thing to note here is, maximum product can also be obtained by minimum (negative) product ending with the previous element multiplied by this element. For example, in array {12, 2, -3, -5, -6, -2}, when we are at element -2, the maximum product is multiplication of, minimum product ending with -6 and -2. Note : if all elements of array are negative then the maximum product with the above algorithm is 1. so, if maximum product is 1, then we have to return the maximum element of an array. C++ C Java Python3 C# PHP Javascript // C++ program to find Maximum Product Subarray#include <bits/stdc++.h>using namespace std; /* Returns the product of max product subarray. */int maxSubarrayProduct(int arr[], int n){ // max positive product // ending at the current position int max_ending_here = 1; // min negative product ending // at the current position int min_ending_here = 1; // Initialize overall max product int max_so_far = 0; int flag = 0; /* Traverse through the array. Following values are maintained after the i'th iteration: max_ending_here is always 1 or some positive product ending with arr[i] min_ending_here is always 1 or some negative product ending with arr[i] */ for (int i = 0; i < n; i++) { /* If this element is positive, update max_ending_here. Update min_ending_here only if min_ending_here is negative */ if (arr[i] > 0) { max_ending_here = max_ending_here * arr[i]; min_ending_here = min(min_ending_here * arr[i], 1); flag = 1; } /* If this element is 0, then the maximum product cannot end here, make both max_ending_here and min_ending_here 0 Assumption: Output is alway greater than or equal to 1. */ else if (arr[i] == 0) { max_ending_here = 1; min_ending_here = 1; } /* If element is negative. This is tricky max_ending_here can either be 1 or positive. min_ending_here can either be 1 or negative. next max_ending_here will always be prev. min_ending_here * arr[i] ,next min_ending_here will be 1 if prev max_ending_here is 1, otherwise next min_ending_here will be prev max_ending_here * arr[i] */ else { int temp = max_ending_here; max_ending_here = max(min_ending_here * arr[i], 1); min_ending_here = temp * arr[i]; } // update max_so_far, if needed if (max_so_far < max_ending_here) max_so_far = max_ending_here; } if (flag == 0 && max_so_far == 0) return 0; /* if all the array elements are negative */ if (max_so_far == 1) { max_so_far = arr[0]; for(int i = 1; i < n; i++) max_so_far = max(max_so_far, arr[i]); } return max_so_far;} // Driver codeint main(){ int arr[] = { 1, -2, -3, 0, 7, -8, -2 }; int n = sizeof(arr) / sizeof(arr[0]); cout << "Maximum Sub array product is " << maxSubarrayProduct(arr, n); return 0;} // This is code is contributed by rathbhupendra // C program to find Maximum Product Subarray#include <stdio.h> // Utility functions to get minimum of two integersint min(int x, int y) { return x < y ? x : y; } // Utility functions to get maximum of two integersint max(int x, int y) { return x > y ? x : y; } /* Returns the product of max product subarray.Assumes that the given array always has a subarraywith product more than 1 */int maxSubarrayProduct(int arr[], int n){ // max positive product // ending at the current position int max_ending_here = 1; // min negative product ending // at the current position int min_ending_here = 1; // Initialize overall max product int max_so_far = 0; int flag = 0; /* Traverse through the array. Following values are maintained after the i'th iteration: max_ending_here is always 1 or some positive product ending with arr[i] min_ending_here is always 1 or some negative product ending with arr[i] */ for (int i = 0; i < n; i++) { /* If this element is positive, update max_ending_here. Update min_ending_here only if min_ending_here is negative */ if (arr[i] > 0) { max_ending_here = max_ending_here * arr[i]; min_ending_here = min(min_ending_here * arr[i], 1); flag = 1; } /* If this element is 0, then the maximum product cannot end here, make both max_ending_here and min_ending_here 0 Assumption: Output is alway greater than or equal to 1. */ else if (arr[i] == 0) { max_ending_here = 1; min_ending_here = 1; } /* If element is negative. This is tricky max_ending_here can either be 1 or positive. min_ending_here can either be 1 or negative. next min_ending_here will always be prev. max_ending_here * arr[i] next max_ending_here will be 1 if prev min_ending_here is 1, otherwise next max_ending_here will be prev min_ending_here * arr[i] */ else { int temp = max_ending_here; max_ending_here = max(min_ending_here * arr[i], 1); min_ending_here = temp * arr[i]; } // update max_so_far, if needed if (max_so_far < max_ending_here) max_so_far = max_ending_here; } if (flag == 0 && max_so_far == 0) return 0; return max_so_far; return max_so_far;} // Driver codeint main(){ int arr[] = { 1, -2, -3, 0, 7, -8, -2 }; int n = sizeof(arr) / sizeof(arr[0]); printf("Maximum Sub array product is %d", maxSubarrayProduct(arr, n)); return 0;} // Java program to find maximum product subarrayimport java.io.*; class ProductSubarray { // Utility functions to get // minimum of two integers static int min(int x, int y) { return x < y ? x : y; } // Utility functions to get // maximum of two integers static int max(int x, int y) { return x > y ? x : y; } /* Returns the product of max product subarray. Assumes that the given array always has a subarray with product more than 1 */ static int maxSubarrayProduct(int arr[]) { int n = arr.length; // max positive product // ending at the current // position int max_ending_here = 1; // min negative product // ending at the current // position int min_ending_here = 1; // Initialize overall max product int max_so_far = 0; int flag = 0; /* Traverse through the array. Following values are maintained after the ith iteration: max_ending_here is always 1 or some positive product ending with arr[i] min_ending_here is always 1 or some negative product ending with arr[i] */ for (int i = 0; i < n; i++) { /* If this element is positive, update max_ending_here. Update min_ending_here only if min_ending_here is negative */ if (arr[i] > 0) { max_ending_here = max_ending_here * arr[i]; min_ending_here = min(min_ending_here * arr[i], 1); flag = 1; } /* If this element is 0, then the maximum product cannot end here, make both max_ending_here and min_ending _here 0 Assumption: Output is alway greater than or equal to 1. */ else if (arr[i] == 0) { max_ending_here = 1; min_ending_here = 1; } /* If element is negative. This is tricky max_ending_here can either be 1 or positive. min_ending_here can either be 1 or negative. next min_ending_here will always be prev. max_ending_here * arr[i] next max_ending_here will be 1 if prev min_ending_here is 1, otherwise next max_ending_here will be prev min_ending_here * arr[i] */ else { int temp = max_ending_here; max_ending_here = max(min_ending_here * arr[i], 1); min_ending_here = temp * arr[i]; } // update max_so_far, if needed if (max_so_far < max_ending_here) max_so_far = max_ending_here; } if (flag == 0 && max_so_far == 0) return 0; return max_so_far; } // Driver Code public static void main(String[] args) { int arr[] = { 1, -2, -3, 0, 7, -8, -2 }; System.out.println("Maximum Sub array product is " + maxSubarrayProduct(arr)); }} /*This code is contributed by Devesh Agrawal*/ # Python program to find maximum product subarray # Returns the product of max product subarray.# Assumes that the given array always has a subarray# with product more than 1def maxsubarrayproduct(arr): n = len(arr) # max positive product ending at the current position max_ending_here = 1 # min positive product ending at the current position min_ending_here = 1 # Initialize maximum so far max_so_far = 0 flag = 0 # Traverse throughout the array. Following values # are maintained after the ith iteration: # max_ending_here is always 1 or some positive product # ending with arr[i] # min_ending_here is always 1 or some negative product # ending with arr[i] for i in range(0, n): # If this element is positive, update max_ending_here. # Update min_ending_here only if min_ending_here is # negative if arr[i] > 0: max_ending_here = max_ending_here * arr[i] min_ending_here = min (min_ending_here * arr[i], 1) flag = 1 # If this element is 0, then the maximum product cannot # end here, make both max_ending_here and min_ending_here 0 # Assumption: Output is alway greater than or equal to 1. elif arr[i] == 0: max_ending_here = 1 min_ending_here = 1 # If element is negative. This is tricky # max_ending_here can either be 1 or positive. # min_ending_here can either be 1 or negative. # next min_ending_here will always be prev. # max_ending_here * arr[i] # next max_ending_here will be 1 if prev # min_ending_here is 1, otherwise # next max_ending_here will be prev min_ending_here * arr[i] else: temp = max_ending_here max_ending_here = max (min_ending_here * arr[i], 1) min_ending_here = temp * arr[i] if (max_so_far < max_ending_here): max_so_far = max_ending_here if flag == 0 and max_so_far == 0: return 0 return max_so_far # Driver function to test above functionarr = [1, -2, -3, 0, 7, -8, -2]print ("Maximum product subarray is", maxsubarrayproduct(arr)) # This code is contributed by Devesh Agrawal // C# program to find maximum product subarrayusing System; class GFG { // Utility functions to get minimum of two integers static int min(int x, int y) { return x < y ? x : y; } // Utility functions to get maximum of two integers static int max(int x, int y) { return x > y ? x : y; } /* Returns the product of max product subarray. Assumes that the given array always has a subarray with product more than 1 */ static int maxSubarrayProduct(int[] arr) { int n = arr.Length; // max positive product ending at the current // position int max_ending_here = 1; // min negative product ending at the current // position int min_ending_here = 1; // Initialize overall max product int max_so_far = 0; int flag = 0; /* Traverse through the array. Following values are maintained after the ith iteration: max_ending_here is always 1 or some positive product ending with arr[i] min_ending_here is always 1 or some negative product ending with arr[i] */ for (int i = 0; i < n; i++) { /* If this element is positive, update max_ending_here. Update min_ending_here only if min_ending_here is negative */ if (arr[i] > 0) { max_ending_here = max_ending_here * arr[i]; min_ending_here = min(min_ending_here * arr[i], 1); flag = 1; } /* If this element is 0, then the maximum product cannot end here, make both max_ending_here and min_ending_here 0 Assumption: Output is alway greater than or equal to 1. */ else if (arr[i] == 0) { max_ending_here = 1; min_ending_here = 1; } /* If element is negative. This is tricky max_ending_here can either be 1 or positive. min_ending_here can either be 1 or negative. next min_ending_here will always be prev. max_ending_here * arr[i] next max_ending_here will be 1 if prev min_ending_here is 1, otherwise next max_ending_here will be prev min_ending_here * arr[i] */ else { int temp = max_ending_here; max_ending_here = max(min_ending_here * arr[i], 1); min_ending_here = temp * arr[i]; } // update max_so_far, if needed if (max_so_far < max_ending_here) max_so_far = max_ending_here; } if (flag == 0 && max_so_far == 0) return 0; return max_so_far; } // Driver Code public static void Main() { int[] arr = { 1, -2, -3, 0, 7, -8, -2 }; Console.WriteLine("Maximum Sub array product is " + maxSubarrayProduct(arr)); }} /*This code is contributed by vt_m*/ <?php// php program to find Maximum Product// Subarray // Utility functions to get minimum of// two integersfunction minn ($x, $y) { return $x < $y? $x : $y;} // Utility functions to get maximum of// two integersfunction maxx ($x, $y) { return $x > $y? $x : $y; } /* Returns the product of max productsubarray. Assumes that the given arrayalways has a subarray with productmore than 1 */function maxSubarrayProduct($arr, $n){ // max positive product ending at // the current position $max_ending_here = 1; // min negative product ending at // the current position $min_ending_here = 1; // Initialize overall max product $max_so_far = 0; $flag = 0; /* Traverse through the array. Following values are maintained after the i'th iteration: max_ending_here is always 1 or some positive product ending with arr[i] min_ending_here is always 1 or some negative product ending with arr[i] */ for ($i = 0; $i < $n; $i++) { /* If this element is positive, update max_ending_here. Update min_ending_here only if min_ending_here is negative */ if ($arr[$i] > 0) { $max_ending_here = $max_ending_here * $arr[$i]; $min_ending_here = min ($min_ending_here * $arr[$i], 1); $flag = 1; } /* If this element is 0, then the maximum product cannot end here, make both max_ending_here and min_ending_here 0 Assumption: Output is alway greater than or equal to 1. */ else if ($arr[$i] == 0) { $max_ending_here = 1; $min_ending_here = 1; } /* If element is negative. This is tricky max_ending_here can either be 1 or positive. min_ending_here can either be 1 or negative. next min_ending_here will always be prev. max_ending_here * arr[i] next max_ending_here will be 1 if prev min_ending_here is 1, otherwise next max_ending_here will be prev min_ending_here * arr[i] */ else { $temp = $max_ending_here; $max_ending_here = max ($min_ending_here * $arr[$i], 1); $min_ending_here = $temp * $arr[$i]; } // update max_so_far, if needed if ($max_so_far < $max_ending_here) $max_so_far = $max_ending_here; } if($flag==0 && $max_so_far==0) return 0; return $max_so_far;} // Driver Program to test above function $arr = array(1, -2, -3, 0, 7, -8, -2); $n = sizeof($arr) / sizeof($arr[0]); echo("Maximum Sub array product is "); echo (maxSubarrayProduct($arr, $n)); // This code is contributed by nitin mittal ?> <script> // JavaScript program to find // Maximum Product Subarray /* Returns the product of max product subarray.Assumes that the given array always has a subarraywith product more than 1 */function maxSubarrayProduct(arr, n){ // max positive product // ending at the current position let max_ending_here = 1; // min negative product ending // at the current position let min_ending_here = 1; // Initialize overall max product let max_so_far = 0; let flag = 0; /* Traverse through the array. Following values are maintained after the i'th iteration: max_ending_here is always 1 or some positive product ending with arr[i] min_ending_here is always 1 or some negative product ending with arr[i] */ for (let i = 0; i < n; i++) { /* If this element is positive, update max_ending_here. Update min_ending_here only if min_ending_here is negative */ if (arr[i] > 0) { max_ending_here = max_ending_here * arr[i]; min_ending_here = Math.min(min_ending_here * arr[i], 1); flag = 1; } /* If this element is 0, then the maximum product cannot end here, make both max_ending_here and min_ending_here 0 Assumption: Output is alway greater than or equal to 1. */ else if (arr[i] == 0) { max_ending_here = 1; min_ending_here = 1; } /* If element is negative. This is tricky max_ending_here can either be 1 or positive. min_ending_here can either be 1 or negative. next max_ending_here will always be prev. min_ending_here * arr[i] ,next min_ending_here will be 1 if prev max_ending_here is 1, otherwise next min_ending_here will be prev max_ending_here * arr[i] */ else { let temp = max_ending_here; max_ending_here = Math.max(min_ending_here * arr[i], 1); min_ending_here = temp * arr[i]; } // update max_so_far, if needed if (max_so_far < max_ending_here) max_so_far = max_ending_here; } if (flag == 0 && max_so_far == 0) return 0; return max_so_far;} // Driver program let arr = [ 1, -2, -3, 0, 7, -8, -2 ]; let n = arr.length; document.write("Maximum Sub array product is " + maxSubarrayProduct(arr,n)); </script> Maximum Sub array product is 112 Time Complexity: O(n) Auxiliary Space: O(1) Efficient Solution: The above solution assumes there is always a positive outcome for the given array which does not work for cases where the array contains only non-positive elements like {0, 0, -20, 0}, {0, 0, 0}.. etc. The modified solution is also similar to Largest Sum Contiguous Subarray problem which uses Kadane’s algorithm. For ease of understanding we are not using any flag like the previous solution. Here we use 3 variable called max_so_far, max_ending_here & min_ending_here. For every index the maximum number ending at that index will be the maximum(arr[i], max_ending_here * arr[i], min_ending_here[i]*arr[i]). Similarly the minimum number ending here will be the minimum of these 3. Thus we get the final value for maximum product subarray. C++ C Java Python3 Javascript C# // C++ program to find Maximum Product Subarray#include <bits/stdc++.h>using namespace std; /* Returns the productof max product subarray. */int maxSubarrayProduct(int arr[], int n){ // max positive product // ending at the current position int max_ending_here = arr[0]; // min negative product ending // at the current position int min_ending_here = arr[0]; // Initialize overall max product int max_so_far = arr[0]; /* Traverse through the array. the maximum product subarray ending at an index will be the maximum of the element itself, the product of element and max product ending previously and the min product ending previously. */ for (int i = 1; i < n; i++) { int temp = max({ arr[i], arr[i] * max_ending_here, arr[i] * min_ending_here }); min_ending_here = min({ arr[i], arr[i] * max_ending_here, arr[i] * min_ending_here }); max_ending_here = temp; max_so_far = max(max_so_far, max_ending_here); } return max_so_far;} // Driver codeint main(){ int arr[] = { 1, -2, -3, 0, 7, -8, -2 }; int n = sizeof(arr) / sizeof(arr[0]); cout << "Maximum Sub array product is " << maxSubarrayProduct(arr, n); return 0;} // This code is contributed by Aditya Kumar (adityakumar129) // C program to find Maximum Product Subarray#include <stdio.h> // Find maximum between two numbers.int max(int num1, int num2){ return (num1 > num2) ? num1 : num2;} // Find minimum between two numbers.int min(int num1, int num2){ return (num1 > num2) ? num2 : num1;} /* Returns the product of max product subarray. */int maxSubarrayProduct(int arr[], int n){ // max positive product // ending at the current position int max_ending_here = arr[0]; // min negative product ending // at the current position int min_ending_here = arr[0]; // Initialize overall max product int max_so_far = arr[0]; /* Traverse through the array. the maximum product subarray ending at an index will be the maximum of the element itself, the product of element and max product ending previously and the min product ending previously. */ for (int i = 1; i < n; i++) { int temp = max(max(arr[i], arr[i] * max_ending_here), arr[i] * min_ending_here); min_ending_here = min(min(arr[i], arr[i] * max_ending_here), arr[i] * min_ending_here); max_ending_here = temp; max_so_far = max(max_so_far, max_ending_here);}return max_so_far;} // Driver codeint main(){ int arr[] = { 1, -2, -3, 0, 7, -8, -2 }; int n = sizeof(arr) / sizeof(arr[0]); printf("Maximum Sub array product is %d", maxSubarrayProduct(arr, n)); return 0;} // This code is contributed by Aditya Kumar (adityakumar129) /*package whatever //do not write package name here */import java.io.*; class GFG { // Java program to find Maximum Product Subarray // Returns the product // of max product subarray. static int maxSubarrayProduct(int arr[],int n){ // max positive product // ending at the current position int max_ending_here = arr[0]; // min negative product ending // at the current position int min_ending_here = arr[0]; // Initialize overall max product int max_so_far = arr[0]; // /* Traverse through the array. // the maximum product subarray ending at an index // will be the maximum of the element itself, // the product of element and max product ending previously // and the min product ending previously. */ for(int i=1;i<n;i++){ int temp = Math.max(Math.max(arr[i], arr[i] * max_ending_here), arr[i] * min_ending_here); min_ending_here = Math.min(Math.min(arr[i], arr[i] * max_ending_here), arr[i] * min_ending_here); max_ending_here = temp; max_so_far = Math.max(max_so_far, max_ending_here); } return max_so_far; } // Driver code public static void main(String args[]) { int[] arr = { 1, -2, -3, 0, 7, -8, -2 }; int n = arr.length; System.out.printf("Maximum Sub array product is %d",maxSubarrayProduct(arr, n)); }} // This code is contributed by shinjanpatra # Python3 program to find Maximum Product Subarray # Returns the product# of max product subarray.def maxSubarrayProduct(arr, n): # max positive product # ending at the current position max_ending_here = arr[0] # min negative product ending # at the current position min_ending_here = arr[0] # Initialize overall max product max_so_far = arr[0] # /* Traverse through the array. # the maximum product subarray ending at an index # will be the maximum of the element itself, # the product of element and max product ending previously # and the min product ending previously. */ for i in range(1, n): temp = max(max(arr[i], arr[i] * max_ending_here), arr[i] * min_ending_here) min_ending_here = min(min(arr[i], arr[i] * max_ending_here), arr[i] * min_ending_here) max_ending_here = temp max_so_far = max(max_so_far, max_ending_here) return max_so_far # Driver codearr = [ 1, -2, -3, 0, 7, -8, -2 ]n = len(arr)print(f"Maximum Sub array product is {maxSubarrayProduct(arr, n)}") # This code is contributed by shinjanpatra <script> // JavaScript program to find Maximum Product Subarray /* Returns the productof max product subarray. */function maxSubarrayProduct(arr, n){ // max positive product // ending at the current position let max_ending_here = arr[0]; // min negative product ending // at the current position let min_ending_here = arr[0]; // Initialize overall max product let max_so_far = arr[0]; /* Traverse through the array. the maximum product subarray ending at an index will be the maximum of the element itself, the product of element and max product ending previously and the min product ending previously. */ for (let i = 1; i < n; i++) { let temp = Math.max(Math.max(arr[i], arr[i] * max_ending_here), arr[i] * min_ending_here); min_ending_here = Math.min(Math.min(arr[i], arr[i] * max_ending_here), arr[i] * min_ending_here); max_ending_here = temp; max_so_far = Math.max(max_so_far, max_ending_here); } return max_so_far;} // Driver codelet arr = [ 1, -2, -3, 0, 7, -8, -2 ]let n = arr.lengthdocument.write("Maximum Sub array product is "+maxSubarrayProduct(arr, n)); // This code is contributed by shinjanpatra </script> // C# program to find maximum product subarrayusing System; class GFG { /* Returns the product of max product subarray. Assumes that the given array always has a subarray with product more than 1 */ static int maxSubarrayProduct(int[] arr) { // max positive product // ending at the current position int max_ending_here = arr[0]; // min negative product ending // at the current position int min_ending_here = arr[0]; // Initialize overall max product int max_so_far = arr[0]; /* Traverse through the array. the maximum product subarray ending at an index will be the maximum of the element itself, the product of element and max product ending previously and the min product ending previously. */ for(int i=1;i<arr.Length;i++) { int temp = Math.Max(Math.Max(arr[i], arr[i] * max_ending_here), arr[i] * min_ending_here); min_ending_here = Math.Min(Math.Min(arr[i], arr[i] * max_ending_here), arr[i] * min_ending_here); max_ending_here = temp; max_so_far = Math.Max(max_so_far, max_ending_here); } return max_so_far; } // Driver Code public static void Main() { int[] arr = { 1, -2, -3, 0, 7, -8, -2 }; Console.WriteLine("Maximum Sub array product is " + maxSubarrayProduct(arr)); }} // This code is contributed by CodeWithMini Maximum Sub array product is 112 Time Complexity: O(N)Auxiliary Space: O(1) This article is compiled by Dheeraj Jain and reviewed by GeeksforGeeks team. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above nitin mittal mahendera rathbhupendra redlilacblue gp6 ManishKumarSavita yashbeersingh42 khritik shivanisinghss2110 divyeshrabadiya07 mayanktyagi1709 jana_sayantan kaustavbhattachaarya sarthakbhagwatin amartyaghoshgfg teko shinjanpatra adityakumar129 codewithmini Amazon Microsoft Morgan Stanley Myntra Myntra-Question Arrays Morgan Stanley Amazon Microsoft Myntra 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 Multidimensional Arrays in Java Stack Data Structure (Introduction and Program) Linear Search Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Introduction to Arrays K'th Smallest/Largest Element in Unsorted Array | Set 1 Subset Sum Problem | DP-25 Introduction to Data Structures
[ { "code": null, "e": 52, "s": 24, "text": "\n06 Jul, 2022" }, { "code": null, "e": 240, "s": 52, "text": "Given an array that contains both positive and negative integers, find the product of the maximum product subarray. Expected Time complexity is O(n) and only O(1) extra space can be used." }, { "code": null, "e": 250, "s": 240, "text": "Examples:" }, { "code": null, "e": 486, "s": 250, "text": "Input: arr[] = {6, -3, -10, 0, 2}\nOutput: 180 // The subarray is {6, -3, -10}\n\nInput: arr[] = {-1, -3, -10, 0, 60}\nOutput: 60 // The subarray is {60}\n\nInput: arr[] = {-2, -40, 0, -2, -3}\nOutput: 80 // The subarray is {-2, -40}" }, { "code": null, "e": 502, "s": 486, "text": "Naive Solution:" }, { "code": null, "e": 654, "s": 502, "text": "The idea is to traverse over every contiguous subarrays, find the product of each of these subarrays and return the maximum product from these results." }, { "code": null, "e": 705, "s": 654, "text": "Below is the implementation of the above approach." }, { "code": null, "e": 709, "s": 705, "text": "C++" }, { "code": null, "e": 711, "s": 709, "text": "C" }, { "code": null, "e": 716, "s": 711, "text": "Java" }, { "code": null, "e": 724, "s": 716, "text": "Python3" }, { "code": null, "e": 727, "s": 724, "text": "C#" }, { "code": null, "e": 738, "s": 727, "text": "Javascript" }, { "code": "// C++ program to find Maximum Product Subarray#include <bits/stdc++.h>using namespace std; /* Returns the product of max product subarray.*/int maxSubarrayProduct(int arr[], int n){ // Initializing result int result = arr[0]; for (int i = 0; i < n; i++) { int mul = arr[i]; // traversing in current subarray for (int j = i + 1; j < n; j++) { // updating result every time // to keep an eye over the maximum product result = max(result, mul); mul *= arr[j]; } // updating the result for (n-1)th index. result = max(result, mul); } return result;} // Driver codeint main(){ int arr[] = { 1, -2, -3, 0, 7, -8, -2 }; int n = sizeof(arr) / sizeof(arr[0]); cout << \"Maximum Sub array product is \" << maxSubarrayProduct(arr, n); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)", "e": 1671, "s": 738, "text": null }, { "code": "// C program to find Maximum Product Subarray#include <stdio.h> // Find maximum between two numbers.int max(int num1, int num2){ return (num1 > num2) ? num1 : num2;} /* Returns the product of max product subarray.*/int maxSubarrayProduct(int arr[], int n){ // Initializing result int result = arr[0]; for (int i = 0; i < n; i++) { int mul = arr[i]; // traversing in current subarray for (int j = i + 1; j < n; j++) { // updating result every time // to keep an eye over the maximum product result = max(result, mul); mul *= arr[j]; } // updating the result for (n-1)th index. result = max(result, mul); } return result;} // Driver codeint main(){ int arr[] = { 1, -2, -3, 0, 7, -8, -2 }; int n = sizeof(arr) / sizeof(arr[0]); printf(\"Maximum Sub array product is %d \", maxSubarrayProduct(arr, n)); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)", "e": 2663, "s": 1671, "text": null }, { "code": "// Java program to find maximum product subarrayimport java.io.*; class GFG { /* Returns the product of max product subarray.*/ static int maxSubarrayProduct(int arr[]) { // Initializing result int result = arr[0]; int n = arr.length; for (int i = 0; i < n; i++) { int mul = arr[i]; // traversing in current subarray for (int j = i + 1; j < n; j++) { // updating result every time to keep an eye // over the maximum product result = Math.max(result, mul); mul *= arr[j]; } // updating the result for (n-1)th index. result = Math.max(result, mul); } return result; } // Driver Code public static void main(String[] args) { int arr[] = { 1, -2, -3, 0, 7, -8, -2 }; System.out.println(\"Maximum Sub array product is \" + maxSubarrayProduct(arr)); }} // This code is contributed by Aditya Kumar (adityakumar129)", "e": 3707, "s": 2663, "text": null }, { "code": "# Python3 program to find Maximum Product Subarray # Returns the product of max product subarray.def maxSubarrayProduct(arr, n): # Initializing result result = arr[0] for i in range(n): mul = arr[i] # traversing in current subarray for j in range(i + 1, n): # updating result every time # to keep an eye over the maximum product result = max(result, mul) mul *= arr[j] # updating the result for (n-1)th index. result = max(result, mul) return result # Driver codearr = [ 1, -2, -3, 0, 7, -8, -2 ]n = len(arr)print(\"Maximum Sub array product is\" , maxSubarrayProduct(arr, n)) # This code is contributed by divyeshrabadiya07", "e": 4468, "s": 3707, "text": null }, { "code": "// C# program to find maximum product subarrayusing System; class GFG{ // Returns the product of max product subarraystatic int maxSubarrayProduct(int []arr){ // Initializing result int result = arr[0]; int n = arr.Length; for(int i = 0; i < n; i++) { int mul = arr[i]; // Traversing in current subarray for(int j = i + 1; j < n; j++) { // Updating result every time // to keep an eye over the // maximum product result = Math.Max(result, mul); mul *= arr[j]; } // Updating the result for (n-1)th index result = Math.Max(result, mul); } return result;} // Driver Codepublic static void Main(String[] args){ int []arr = { 1, -2, -3, 0, 7, -8, -2 }; Console.Write(\"Maximum Sub array product is \" + maxSubarrayProduct(arr));}} // This code is contributed by shivanisinghss2110", "e": 5446, "s": 4468, "text": null }, { "code": "<script> // Javascript program to find Maximum Product Subarray /* Returns the product of max product subarray.*/function maxSubarrayProduct(arr, n){ // Initializing result let result = arr[0]; for (let i = 0; i < n; i++) { let mul = arr[i]; // traversing in current subarray for (let j = i + 1; j < n; j++) { // updating result every time // to keep an eye over the maximum product result = Math.max(result, mul); mul *= arr[j]; } // updating the result for (n-1)th index. result = Math.max(result, mul); } return result;} // Driver code let arr = [ 1, -2, -3, 0, 7, -8, -2 ]; let n = arr.length; document.write(\"Maximum Sub array product is \" + maxSubarrayProduct(arr, n)); // This code is contributed by Mayank Tyagi </script>", "e": 6320, "s": 5446, "text": null }, { "code": null, "e": 6353, "s": 6320, "text": "Maximum Sub array product is 112" }, { "code": null, "e": 6397, "s": 6353, "text": "Time Complexity: O(N2)Auxiliary Space: O(1)" }, { "code": null, "e": 6417, "s": 6397, "text": "Efficient Solution:" }, { "code": null, "e": 7051, "s": 6417, "text": "The following solution assumes that the given input array always has a positive output. The solution works for all cases mentioned above. It doesn’t work for arrays like {0, 0, -20, 0}, {0, 0, 0}.. etc. The solution can be easily modified to handle this case. It is similar to Largest Sum Contiguous Subarray problem. The only thing to note here is, maximum product can also be obtained by minimum (negative) product ending with the previous element multiplied by this element. For example, in array {12, 2, -3, -5, -6, -2}, when we are at element -2, the maximum product is multiplication of, minimum product ending with -6 and -2. " }, { "code": null, "e": 7435, "s": 7051, "text": "Note : if all elements of array are negative then the maximum product with the above algorithm is 1. so, if maximum product is 1, then we have to return the maximum element of an array. " }, { "code": null, "e": 7439, "s": 7435, "text": "C++" }, { "code": null, "e": 7441, "s": 7439, "text": "C" }, { "code": null, "e": 7446, "s": 7441, "text": "Java" }, { "code": null, "e": 7454, "s": 7446, "text": "Python3" }, { "code": null, "e": 7457, "s": 7454, "text": "C#" }, { "code": null, "e": 7461, "s": 7457, "text": "PHP" }, { "code": null, "e": 7472, "s": 7461, "text": "Javascript" }, { "code": "// C++ program to find Maximum Product Subarray#include <bits/stdc++.h>using namespace std; /* Returns the product of max product subarray. */int maxSubarrayProduct(int arr[], int n){ // max positive product // ending at the current position int max_ending_here = 1; // min negative product ending // at the current position int min_ending_here = 1; // Initialize overall max product int max_so_far = 0; int flag = 0; /* Traverse through the array. Following values are maintained after the i'th iteration: max_ending_here is always 1 or some positive product ending with arr[i] min_ending_here is always 1 or some negative product ending with arr[i] */ for (int i = 0; i < n; i++) { /* If this element is positive, update max_ending_here. Update min_ending_here only if min_ending_here is negative */ if (arr[i] > 0) { max_ending_here = max_ending_here * arr[i]; min_ending_here = min(min_ending_here * arr[i], 1); flag = 1; } /* If this element is 0, then the maximum product cannot end here, make both max_ending_here and min_ending_here 0 Assumption: Output is alway greater than or equal to 1. */ else if (arr[i] == 0) { max_ending_here = 1; min_ending_here = 1; } /* If element is negative. This is tricky max_ending_here can either be 1 or positive. min_ending_here can either be 1 or negative. next max_ending_here will always be prev. min_ending_here * arr[i] ,next min_ending_here will be 1 if prev max_ending_here is 1, otherwise next min_ending_here will be prev max_ending_here * arr[i] */ else { int temp = max_ending_here; max_ending_here = max(min_ending_here * arr[i], 1); min_ending_here = temp * arr[i]; } // update max_so_far, if needed if (max_so_far < max_ending_here) max_so_far = max_ending_here; } if (flag == 0 && max_so_far == 0) return 0; /* if all the array elements are negative */ if (max_so_far == 1) { max_so_far = arr[0]; for(int i = 1; i < n; i++) max_so_far = max(max_so_far, arr[i]); } return max_so_far;} // Driver codeint main(){ int arr[] = { 1, -2, -3, 0, 7, -8, -2 }; int n = sizeof(arr) / sizeof(arr[0]); cout << \"Maximum Sub array product is \" << maxSubarrayProduct(arr, n); return 0;} // This is code is contributed by rathbhupendra", "e": 10119, "s": 7472, "text": null }, { "code": "// C program to find Maximum Product Subarray#include <stdio.h> // Utility functions to get minimum of two integersint min(int x, int y) { return x < y ? x : y; } // Utility functions to get maximum of two integersint max(int x, int y) { return x > y ? x : y; } /* Returns the product of max product subarray.Assumes that the given array always has a subarraywith product more than 1 */int maxSubarrayProduct(int arr[], int n){ // max positive product // ending at the current position int max_ending_here = 1; // min negative product ending // at the current position int min_ending_here = 1; // Initialize overall max product int max_so_far = 0; int flag = 0; /* Traverse through the array. Following values are maintained after the i'th iteration: max_ending_here is always 1 or some positive product ending with arr[i] min_ending_here is always 1 or some negative product ending with arr[i] */ for (int i = 0; i < n; i++) { /* If this element is positive, update max_ending_here. Update min_ending_here only if min_ending_here is negative */ if (arr[i] > 0) { max_ending_here = max_ending_here * arr[i]; min_ending_here = min(min_ending_here * arr[i], 1); flag = 1; } /* If this element is 0, then the maximum product cannot end here, make both max_ending_here and min_ending_here 0 Assumption: Output is alway greater than or equal to 1. */ else if (arr[i] == 0) { max_ending_here = 1; min_ending_here = 1; } /* If element is negative. This is tricky max_ending_here can either be 1 or positive. min_ending_here can either be 1 or negative. next min_ending_here will always be prev. max_ending_here * arr[i] next max_ending_here will be 1 if prev min_ending_here is 1, otherwise next max_ending_here will be prev min_ending_here * arr[i] */ else { int temp = max_ending_here; max_ending_here = max(min_ending_here * arr[i], 1); min_ending_here = temp * arr[i]; } // update max_so_far, if needed if (max_so_far < max_ending_here) max_so_far = max_ending_here; } if (flag == 0 && max_so_far == 0) return 0; return max_so_far; return max_so_far;} // Driver codeint main(){ int arr[] = { 1, -2, -3, 0, 7, -8, -2 }; int n = sizeof(arr) / sizeof(arr[0]); printf(\"Maximum Sub array product is %d\", maxSubarrayProduct(arr, n)); return 0;}", "e": 12805, "s": 10119, "text": null }, { "code": "// Java program to find maximum product subarrayimport java.io.*; class ProductSubarray { // Utility functions to get // minimum of two integers static int min(int x, int y) { return x < y ? x : y; } // Utility functions to get // maximum of two integers static int max(int x, int y) { return x > y ? x : y; } /* Returns the product of max product subarray. Assumes that the given array always has a subarray with product more than 1 */ static int maxSubarrayProduct(int arr[]) { int n = arr.length; // max positive product // ending at the current // position int max_ending_here = 1; // min negative product // ending at the current // position int min_ending_here = 1; // Initialize overall max product int max_so_far = 0; int flag = 0; /* Traverse through the array. Following values are maintained after the ith iteration: max_ending_here is always 1 or some positive product ending with arr[i] min_ending_here is always 1 or some negative product ending with arr[i] */ for (int i = 0; i < n; i++) { /* If this element is positive, update max_ending_here. Update min_ending_here only if min_ending_here is negative */ if (arr[i] > 0) { max_ending_here = max_ending_here * arr[i]; min_ending_here = min(min_ending_here * arr[i], 1); flag = 1; } /* If this element is 0, then the maximum product cannot end here, make both max_ending_here and min_ending _here 0 Assumption: Output is alway greater than or equal to 1. */ else if (arr[i] == 0) { max_ending_here = 1; min_ending_here = 1; } /* If element is negative. This is tricky max_ending_here can either be 1 or positive. min_ending_here can either be 1 or negative. next min_ending_here will always be prev. max_ending_here * arr[i] next max_ending_here will be 1 if prev min_ending_here is 1, otherwise next max_ending_here will be prev min_ending_here * arr[i] */ else { int temp = max_ending_here; max_ending_here = max(min_ending_here * arr[i], 1); min_ending_here = temp * arr[i]; } // update max_so_far, if needed if (max_so_far < max_ending_here) max_so_far = max_ending_here; } if (flag == 0 && max_so_far == 0) return 0; return max_so_far; } // Driver Code public static void main(String[] args) { int arr[] = { 1, -2, -3, 0, 7, -8, -2 }; System.out.println(\"Maximum Sub array product is \" + maxSubarrayProduct(arr)); }} /*This code is contributed by Devesh Agrawal*/", "e": 15979, "s": 12805, "text": null }, { "code": "# Python program to find maximum product subarray # Returns the product of max product subarray.# Assumes that the given array always has a subarray# with product more than 1def maxsubarrayproduct(arr): n = len(arr) # max positive product ending at the current position max_ending_here = 1 # min positive product ending at the current position min_ending_here = 1 # Initialize maximum so far max_so_far = 0 flag = 0 # Traverse throughout the array. Following values # are maintained after the ith iteration: # max_ending_here is always 1 or some positive product # ending with arr[i] # min_ending_here is always 1 or some negative product # ending with arr[i] for i in range(0, n): # If this element is positive, update max_ending_here. # Update min_ending_here only if min_ending_here is # negative if arr[i] > 0: max_ending_here = max_ending_here * arr[i] min_ending_here = min (min_ending_here * arr[i], 1) flag = 1 # If this element is 0, then the maximum product cannot # end here, make both max_ending_here and min_ending_here 0 # Assumption: Output is alway greater than or equal to 1. elif arr[i] == 0: max_ending_here = 1 min_ending_here = 1 # If element is negative. This is tricky # max_ending_here can either be 1 or positive. # min_ending_here can either be 1 or negative. # next min_ending_here will always be prev. # max_ending_here * arr[i] # next max_ending_here will be 1 if prev # min_ending_here is 1, otherwise # next max_ending_here will be prev min_ending_here * arr[i] else: temp = max_ending_here max_ending_here = max (min_ending_here * arr[i], 1) min_ending_here = temp * arr[i] if (max_so_far < max_ending_here): max_so_far = max_ending_here if flag == 0 and max_so_far == 0: return 0 return max_so_far # Driver function to test above functionarr = [1, -2, -3, 0, 7, -8, -2]print (\"Maximum product subarray is\", maxsubarrayproduct(arr)) # This code is contributed by Devesh Agrawal", "e": 18205, "s": 15979, "text": null }, { "code": "// C# program to find maximum product subarrayusing System; class GFG { // Utility functions to get minimum of two integers static int min(int x, int y) { return x < y ? x : y; } // Utility functions to get maximum of two integers static int max(int x, int y) { return x > y ? x : y; } /* Returns the product of max product subarray. Assumes that the given array always has a subarray with product more than 1 */ static int maxSubarrayProduct(int[] arr) { int n = arr.Length; // max positive product ending at the current // position int max_ending_here = 1; // min negative product ending at the current // position int min_ending_here = 1; // Initialize overall max product int max_so_far = 0; int flag = 0; /* Traverse through the array. Following values are maintained after the ith iteration: max_ending_here is always 1 or some positive product ending with arr[i] min_ending_here is always 1 or some negative product ending with arr[i] */ for (int i = 0; i < n; i++) { /* If this element is positive, update max_ending_here. Update min_ending_here only if min_ending_here is negative */ if (arr[i] > 0) { max_ending_here = max_ending_here * arr[i]; min_ending_here = min(min_ending_here * arr[i], 1); flag = 1; } /* If this element is 0, then the maximum product cannot end here, make both max_ending_here and min_ending_here 0 Assumption: Output is alway greater than or equal to 1. */ else if (arr[i] == 0) { max_ending_here = 1; min_ending_here = 1; } /* If element is negative. This is tricky max_ending_here can either be 1 or positive. min_ending_here can either be 1 or negative. next min_ending_here will always be prev. max_ending_here * arr[i] next max_ending_here will be 1 if prev min_ending_here is 1, otherwise next max_ending_here will be prev min_ending_here * arr[i] */ else { int temp = max_ending_here; max_ending_here = max(min_ending_here * arr[i], 1); min_ending_here = temp * arr[i]; } // update max_so_far, if needed if (max_so_far < max_ending_here) max_so_far = max_ending_here; } if (flag == 0 && max_so_far == 0) return 0; return max_so_far; } // Driver Code public static void Main() { int[] arr = { 1, -2, -3, 0, 7, -8, -2 }; Console.WriteLine(\"Maximum Sub array product is \" + maxSubarrayProduct(arr)); }} /*This code is contributed by vt_m*/", "e": 21378, "s": 18205, "text": null }, { "code": "<?php// php program to find Maximum Product// Subarray // Utility functions to get minimum of// two integersfunction minn ($x, $y) { return $x < $y? $x : $y;} // Utility functions to get maximum of// two integersfunction maxx ($x, $y) { return $x > $y? $x : $y; } /* Returns the product of max productsubarray. Assumes that the given arrayalways has a subarray with productmore than 1 */function maxSubarrayProduct($arr, $n){ // max positive product ending at // the current position $max_ending_here = 1; // min negative product ending at // the current position $min_ending_here = 1; // Initialize overall max product $max_so_far = 0; $flag = 0; /* Traverse through the array. Following values are maintained after the i'th iteration: max_ending_here is always 1 or some positive product ending with arr[i] min_ending_here is always 1 or some negative product ending with arr[i] */ for ($i = 0; $i < $n; $i++) { /* If this element is positive, update max_ending_here. Update min_ending_here only if min_ending_here is negative */ if ($arr[$i] > 0) { $max_ending_here = $max_ending_here * $arr[$i]; $min_ending_here = min ($min_ending_here * $arr[$i], 1); $flag = 1; } /* If this element is 0, then the maximum product cannot end here, make both max_ending_here and min_ending_here 0 Assumption: Output is alway greater than or equal to 1. */ else if ($arr[$i] == 0) { $max_ending_here = 1; $min_ending_here = 1; } /* If element is negative. This is tricky max_ending_here can either be 1 or positive. min_ending_here can either be 1 or negative. next min_ending_here will always be prev. max_ending_here * arr[i] next max_ending_here will be 1 if prev min_ending_here is 1, otherwise next max_ending_here will be prev min_ending_here * arr[i] */ else { $temp = $max_ending_here; $max_ending_here = max ($min_ending_here * $arr[$i], 1); $min_ending_here = $temp * $arr[$i]; } // update max_so_far, if needed if ($max_so_far < $max_ending_here) $max_so_far = $max_ending_here; } if($flag==0 && $max_so_far==0) return 0; return $max_so_far;} // Driver Program to test above function $arr = array(1, -2, -3, 0, 7, -8, -2); $n = sizeof($arr) / sizeof($arr[0]); echo(\"Maximum Sub array product is \"); echo (maxSubarrayProduct($arr, $n)); // This code is contributed by nitin mittal ?>", "e": 24259, "s": 21378, "text": null }, { "code": "<script> // JavaScript program to find // Maximum Product Subarray /* Returns the product of max product subarray.Assumes that the given array always has a subarraywith product more than 1 */function maxSubarrayProduct(arr, n){ // max positive product // ending at the current position let max_ending_here = 1; // min negative product ending // at the current position let min_ending_here = 1; // Initialize overall max product let max_so_far = 0; let flag = 0; /* Traverse through the array. Following values are maintained after the i'th iteration: max_ending_here is always 1 or some positive product ending with arr[i] min_ending_here is always 1 or some negative product ending with arr[i] */ for (let i = 0; i < n; i++) { /* If this element is positive, update max_ending_here. Update min_ending_here only if min_ending_here is negative */ if (arr[i] > 0) { max_ending_here = max_ending_here * arr[i]; min_ending_here = Math.min(min_ending_here * arr[i], 1); flag = 1; } /* If this element is 0, then the maximum product cannot end here, make both max_ending_here and min_ending_here 0 Assumption: Output is alway greater than or equal to 1. */ else if (arr[i] == 0) { max_ending_here = 1; min_ending_here = 1; } /* If element is negative. This is tricky max_ending_here can either be 1 or positive. min_ending_here can either be 1 or negative. next max_ending_here will always be prev. min_ending_here * arr[i] ,next min_ending_here will be 1 if prev max_ending_here is 1, otherwise next min_ending_here will be prev max_ending_here * arr[i] */ else { let temp = max_ending_here; max_ending_here = Math.max(min_ending_here * arr[i], 1); min_ending_here = temp * arr[i]; } // update max_so_far, if needed if (max_so_far < max_ending_here) max_so_far = max_ending_here; } if (flag == 0 && max_so_far == 0) return 0; return max_so_far;} // Driver program let arr = [ 1, -2, -3, 0, 7, -8, -2 ]; let n = arr.length; document.write(\"Maximum Sub array product is \" + maxSubarrayProduct(arr,n)); </script>", "e": 26728, "s": 24259, "text": null }, { "code": null, "e": 26761, "s": 26728, "text": "Maximum Sub array product is 112" }, { "code": null, "e": 26805, "s": 26761, "text": "Time Complexity: O(n) Auxiliary Space: O(1)" }, { "code": null, "e": 26826, "s": 26805, "text": " Efficient Solution:" }, { "code": null, "e": 27566, "s": 26826, "text": "The above solution assumes there is always a positive outcome for the given array which does not work for cases where the array contains only non-positive elements like {0, 0, -20, 0}, {0, 0, 0}.. etc. The modified solution is also similar to Largest Sum Contiguous Subarray problem which uses Kadane’s algorithm. For ease of understanding we are not using any flag like the previous solution. Here we use 3 variable called max_so_far, max_ending_here & min_ending_here. For every index the maximum number ending at that index will be the maximum(arr[i], max_ending_here * arr[i], min_ending_here[i]*arr[i]). Similarly the minimum number ending here will be the minimum of these 3. Thus we get the final value for maximum product subarray." }, { "code": null, "e": 27570, "s": 27566, "text": "C++" }, { "code": null, "e": 27572, "s": 27570, "text": "C" }, { "code": null, "e": 27577, "s": 27572, "text": "Java" }, { "code": null, "e": 27585, "s": 27577, "text": "Python3" }, { "code": null, "e": 27596, "s": 27585, "text": "Javascript" }, { "code": null, "e": 27599, "s": 27596, "text": "C#" }, { "code": "// C++ program to find Maximum Product Subarray#include <bits/stdc++.h>using namespace std; /* Returns the productof max product subarray. */int maxSubarrayProduct(int arr[], int n){ // max positive product // ending at the current position int max_ending_here = arr[0]; // min negative product ending // at the current position int min_ending_here = arr[0]; // Initialize overall max product int max_so_far = arr[0]; /* Traverse through the array. the maximum product subarray ending at an index will be the maximum of the element itself, the product of element and max product ending previously and the min product ending previously. */ for (int i = 1; i < n; i++) { int temp = max({ arr[i], arr[i] * max_ending_here, arr[i] * min_ending_here }); min_ending_here = min({ arr[i], arr[i] * max_ending_here, arr[i] * min_ending_here }); max_ending_here = temp; max_so_far = max(max_so_far, max_ending_here); } return max_so_far;} // Driver codeint main(){ int arr[] = { 1, -2, -3, 0, 7, -8, -2 }; int n = sizeof(arr) / sizeof(arr[0]); cout << \"Maximum Sub array product is \" << maxSubarrayProduct(arr, n); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)", "e": 28933, "s": 27599, "text": null }, { "code": "// C program to find Maximum Product Subarray#include <stdio.h> // Find maximum between two numbers.int max(int num1, int num2){ return (num1 > num2) ? num1 : num2;} // Find minimum between two numbers.int min(int num1, int num2){ return (num1 > num2) ? num2 : num1;} /* Returns the product of max product subarray. */int maxSubarrayProduct(int arr[], int n){ // max positive product // ending at the current position int max_ending_here = arr[0]; // min negative product ending // at the current position int min_ending_here = arr[0]; // Initialize overall max product int max_so_far = arr[0]; /* Traverse through the array. the maximum product subarray ending at an index will be the maximum of the element itself, the product of element and max product ending previously and the min product ending previously. */ for (int i = 1; i < n; i++) { int temp = max(max(arr[i], arr[i] * max_ending_here), arr[i] * min_ending_here); min_ending_here = min(min(arr[i], arr[i] * max_ending_here), arr[i] * min_ending_here); max_ending_here = temp; max_so_far = max(max_so_far, max_ending_here);}return max_so_far;} // Driver codeint main(){ int arr[] = { 1, -2, -3, 0, 7, -8, -2 }; int n = sizeof(arr) / sizeof(arr[0]); printf(\"Maximum Sub array product is %d\", maxSubarrayProduct(arr, n)); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)", "e": 30422, "s": 28933, "text": null }, { "code": "/*package whatever //do not write package name here */import java.io.*; class GFG { // Java program to find Maximum Product Subarray // Returns the product // of max product subarray. static int maxSubarrayProduct(int arr[],int n){ // max positive product // ending at the current position int max_ending_here = arr[0]; // min negative product ending // at the current position int min_ending_here = arr[0]; // Initialize overall max product int max_so_far = arr[0]; // /* Traverse through the array. // the maximum product subarray ending at an index // will be the maximum of the element itself, // the product of element and max product ending previously // and the min product ending previously. */ for(int i=1;i<n;i++){ int temp = Math.max(Math.max(arr[i], arr[i] * max_ending_here), arr[i] * min_ending_here); min_ending_here = Math.min(Math.min(arr[i], arr[i] * max_ending_here), arr[i] * min_ending_here); max_ending_here = temp; max_so_far = Math.max(max_so_far, max_ending_here); } return max_so_far; } // Driver code public static void main(String args[]) { int[] arr = { 1, -2, -3, 0, 7, -8, -2 }; int n = arr.length; System.out.printf(\"Maximum Sub array product is %d\",maxSubarrayProduct(arr, n)); }} // This code is contributed by shinjanpatra", "e": 31786, "s": 30422, "text": null }, { "code": "# Python3 program to find Maximum Product Subarray # Returns the product# of max product subarray.def maxSubarrayProduct(arr, n): # max positive product # ending at the current position max_ending_here = arr[0] # min negative product ending # at the current position min_ending_here = arr[0] # Initialize overall max product max_so_far = arr[0] # /* Traverse through the array. # the maximum product subarray ending at an index # will be the maximum of the element itself, # the product of element and max product ending previously # and the min product ending previously. */ for i in range(1, n): temp = max(max(arr[i], arr[i] * max_ending_here), arr[i] * min_ending_here) min_ending_here = min(min(arr[i], arr[i] * max_ending_here), arr[i] * min_ending_here) max_ending_here = temp max_so_far = max(max_so_far, max_ending_here) return max_so_far # Driver codearr = [ 1, -2, -3, 0, 7, -8, -2 ]n = len(arr)print(f\"Maximum Sub array product is {maxSubarrayProduct(arr, n)}\") # This code is contributed by shinjanpatra", "e": 32898, "s": 31786, "text": null }, { "code": "<script> // JavaScript program to find Maximum Product Subarray /* Returns the productof max product subarray. */function maxSubarrayProduct(arr, n){ // max positive product // ending at the current position let max_ending_here = arr[0]; // min negative product ending // at the current position let min_ending_here = arr[0]; // Initialize overall max product let max_so_far = arr[0]; /* Traverse through the array. the maximum product subarray ending at an index will be the maximum of the element itself, the product of element and max product ending previously and the min product ending previously. */ for (let i = 1; i < n; i++) { let temp = Math.max(Math.max(arr[i], arr[i] * max_ending_here), arr[i] * min_ending_here); min_ending_here = Math.min(Math.min(arr[i], arr[i] * max_ending_here), arr[i] * min_ending_here); max_ending_here = temp; max_so_far = Math.max(max_so_far, max_ending_here); } return max_so_far;} // Driver codelet arr = [ 1, -2, -3, 0, 7, -8, -2 ]let n = arr.lengthdocument.write(\"Maximum Sub array product is \"+maxSubarrayProduct(arr, n)); // This code is contributed by shinjanpatra </script>", "e": 34116, "s": 32898, "text": null }, { "code": "// C# program to find maximum product subarrayusing System; class GFG { /* Returns the product of max product subarray. Assumes that the given array always has a subarray with product more than 1 */ static int maxSubarrayProduct(int[] arr) { // max positive product // ending at the current position int max_ending_here = arr[0]; // min negative product ending // at the current position int min_ending_here = arr[0]; // Initialize overall max product int max_so_far = arr[0]; /* Traverse through the array. the maximum product subarray ending at an index will be the maximum of the element itself, the product of element and max product ending previously and the min product ending previously. */ for(int i=1;i<arr.Length;i++) { int temp = Math.Max(Math.Max(arr[i], arr[i] * max_ending_here), arr[i] * min_ending_here); min_ending_here = Math.Min(Math.Min(arr[i], arr[i] * max_ending_here), arr[i] * min_ending_here); max_ending_here = temp; max_so_far = Math.Max(max_so_far, max_ending_here); } return max_so_far; } // Driver Code public static void Main() { int[] arr = { 1, -2, -3, 0, 7, -8, -2 }; Console.WriteLine(\"Maximum Sub array product is \" + maxSubarrayProduct(arr)); }} // This code is contributed by CodeWithMini", "e": 35589, "s": 34116, "text": null }, { "code": null, "e": 35622, "s": 35589, "text": "Maximum Sub array product is 112" }, { "code": null, "e": 35665, "s": 35622, "text": "Time Complexity: O(N)Auxiliary Space: O(1)" }, { "code": null, "e": 35866, "s": 35665, "text": "This article is compiled by Dheeraj Jain and reviewed by GeeksforGeeks team. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above" }, { "code": null, "e": 35879, "s": 35866, "text": "nitin mittal" }, { "code": null, "e": 35889, "s": 35879, "text": "mahendera" }, { "code": null, "e": 35903, "s": 35889, "text": "rathbhupendra" }, { "code": null, "e": 35916, "s": 35903, "text": "redlilacblue" }, { "code": null, "e": 35920, "s": 35916, "text": "gp6" }, { "code": null, "e": 35938, "s": 35920, "text": "ManishKumarSavita" }, { "code": null, "e": 35954, "s": 35938, "text": "yashbeersingh42" }, { "code": null, "e": 35962, "s": 35954, "text": "khritik" }, { "code": null, "e": 35981, "s": 35962, "text": "shivanisinghss2110" }, { "code": null, "e": 35999, "s": 35981, "text": "divyeshrabadiya07" }, { "code": null, "e": 36015, "s": 35999, "text": "mayanktyagi1709" }, { "code": null, "e": 36029, "s": 36015, "text": "jana_sayantan" }, { "code": null, "e": 36050, "s": 36029, "text": "kaustavbhattachaarya" }, { "code": null, "e": 36067, "s": 36050, "text": "sarthakbhagwatin" }, { "code": null, "e": 36083, "s": 36067, "text": "amartyaghoshgfg" }, { "code": null, "e": 36088, "s": 36083, "text": "teko" }, { "code": null, "e": 36101, "s": 36088, "text": "shinjanpatra" }, { "code": null, "e": 36116, "s": 36101, "text": "adityakumar129" }, { "code": null, "e": 36129, "s": 36116, "text": "codewithmini" }, { "code": null, "e": 36136, "s": 36129, "text": "Amazon" }, { "code": null, "e": 36146, "s": 36136, "text": "Microsoft" }, { "code": null, "e": 36161, "s": 36146, "text": "Morgan Stanley" }, { "code": null, "e": 36168, "s": 36161, "text": "Myntra" }, { "code": null, "e": 36184, "s": 36168, "text": "Myntra-Question" }, { "code": null, "e": 36191, "s": 36184, "text": "Arrays" }, { "code": null, "e": 36206, "s": 36191, "text": "Morgan Stanley" }, { "code": null, "e": 36213, "s": 36206, "text": "Amazon" }, { "code": null, "e": 36223, "s": 36213, "text": "Microsoft" }, { "code": null, "e": 36230, "s": 36223, "text": "Myntra" }, { "code": null, "e": 36237, "s": 36230, "text": "Arrays" }, { "code": null, "e": 36335, "s": 36237, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36403, "s": 36335, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 36447, "s": 36403, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 36479, "s": 36447, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 36527, "s": 36479, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 36541, "s": 36527, "text": "Linear Search" }, { "code": null, "e": 36626, "s": 36541, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 36649, "s": 36626, "text": "Introduction to Arrays" }, { "code": null, "e": 36705, "s": 36649, "text": "K'th Smallest/Largest Element in Unsorted Array | Set 1" }, { "code": null, "e": 36732, "s": 36705, "text": "Subset Sum Problem | DP-25" } ]
Virtual Functions and Runtime Polymorphism in C++
22 Jun, 2022 A virtual function is a member function that is declared in the base class using the keyword virtual and is re-defined (Overriden) in the derived class. It tells the compiler to perform late binding where the compiler matches the object with the right called function and executes it during the runtime. This technique of falls under Runtime Polymorphism. The term Polymorphism means the ability to take many forms. It occurs if there is a hierarchy of classes that are all related to each other by inheritance. In simple words, when we break down Polymorphism into ‘Poly – Many’ and ‘morphism – Forms’ it means showing different characteristics in different situations. Class Hierarchy Note: In C++ what calling a virtual functions means is that; if we call a member function then it could cause a different function to be executed instead depending on what type of object invoked it. Because overriding from derived classes hasn’t happened yet, the virtual call mechanism is disallowed in constructors. Also to mention that objects are built from the ground up or follows a bottom to top approach. Consider the following simple program as an example of runtime polymorphism. The main thing to note about the program is that the derived class’s function is called using a base class pointer.The idea is that virtual functions are called according to the type of the object instance pointed to or referenced, not according to the type of the pointer or reference.In other words, virtual functions are resolved late, at runtime. Now, we’ll look at an example without using the concepts of virtual function to clarify your understanding. C++ // C++ program to demonstrate how we will calculate// area of shapes without virtual function#include <iostream>using namespace std; // Base classclass Shape {public: // parameterized constructor Shape(int l, int w) { length = l; width = w; } int get_Area() { cout << "This is call to parent class area\n"; // Returning 1 in user-defined function means true return 1; } protected: int length, width;}; // Derived classclass Square : public Shape {public: Square(int l = 0, int w = 0) : Shape(l, w) { } // declaring and initializing derived class // constructor int get_Area() { cout << "Square area: " << length * width << '\n'; return (length * width); }};// Derived classclass Rectangle : public Shape {public: Rectangle(int l = 0, int w = 0) : Shape(l, w) { } // declaring and initializing derived class // constructor int get_Area() { cout << "Rectangle area: " << length * width << '\n'; return (length * width); }}; int main(){ Shape* s; // Making object of child class Square Square sq(5, 5); // Making object of child class Rectangle Rectangle rec(4, 5); s = &sq; // reference variable s->get_Area(); s = &rec; // reference variable s->get_Area(); return 0; // too tell the program executed // successfully} This is call to parent class area This is call to parent class area In the above example: We store the address of each child’s class Rectangle and Square object in s and Then we call the get_Area() function on it, Ideally, it should have called the respective get_Area() functions of the child classes but Instead, it calls the get_Area() defined in the base class. This happens due to static linkage which means the call to get_Area() is getting set only once by the compiler which is in the base class. Example: C++ Program to Calculate the Area of Shapes using Virtual Function C++ // C++ program to demonstrate how we will calculate// the area of shapes USING VIRTUAL FUNCTION#include <fstream>#include <iostream>using namespace std; // Declaration of Base classclass Shape {public: // Usage of virtual constructor virtual void calculate() { cout << "Area of your Shape "; } // usage of virtual Destuctor to avoid memory leak virtual ~Shape() { cout << "Shape Destuctor Call\n"; }}; // Declaration of Derived classclass Rectangle : public Shape {public: int width, height, area; void calculate() { cout << "Enter Width of Rectangle: "; cin >> width; cout << "Enter Height of Rectangle: "; cin >> height; area = height * width; cout << "Area of Rectangle: " << area << "\n"; } // Virtual Destuctor for every Derived class virtual ~Rectangle() { cout << "Rectangle Destuctor Call\n"; }}; // Declaration of 2nd derived classclass Square : public Shape {public: int side, area; void calculate() { cout << "Enter one side your of Square: "; cin >> side; area = side * side; cout << "Area of Square: " << area << "\n"; } // Virtual Destuctor for every Derived class virtual ~Square() { cout << "Square Destuctor Call\n"; }}; int main(){ // base class pointer Shape* S; Rectangle r; // initialization of reference variable S = &r; // calling of Rectangle function S->calculate(); Square sq; // initialization of reference variable S = &sq; // calling of Square function S->calculate(); // return 0 to tell the program executed // successfully return 0;} Output: Enter Width of Rectangle: 10 Enter Height of Rectangle: 20 Area of Rectangle: 200 Enter one side your of Square: 16 Area of Square: 256 What is the use? Virtual functions allow us to create a list of base class pointers and call methods of any of the derived classes without even knowing the kind of derived class object. Consider employee management software for an organization.Let the code has a simple base class Employee, the class contains virtual functions like raiseSalary(), transfer(), promote(), etc. Different types of employees like Managers, Engineers, etc., may have their own implementations of the virtual functions present in base class Employee. In our complete software, we just need to pass a list of employees everywhere and call appropriate functions without even knowing the type of employee. For example, we can easily raise the salary of all employees by iterating through the list of employees. Every type of employee may have its own logic in its class, but we don’t need to worry about them because if raiseSalary() is present for a specific employee type, only that function would be called. CPP // C++ program to demonstrate how a virtual function// is used in a real life scenario class Employee {public: virtual void raiseSalary() { // common raise salary code } virtual void promote() { // common promote code }}; class Manager : public Employee { virtual void raiseSalary() { // Manager specific raise salary code, may contain // increment of manager specific incentives } virtual void promote() { // Manager specific promote }}; // Similarly, there may be other types of employees // We need a very simple function// to increment the salary of all employees// Note that emp[] is an array of pointers// and actual pointed objects can// be any type of employees.// This function should ideally// be in a class like Organization,// we have made it global to keep things simplevoid globalRaiseSalary(Employee* emp[], int n){ for (int i = 0; i < n; i++) { // Polymorphic Call: Calls raiseSalary() // according to the actual object, not // according to the type of pointer emp[i]->raiseSalary(); }} Like the ‘globalRaiseSalary()‘ function, there can be many other operations that can be performed on a list of employees without even knowing the type of the object instance. Virtual functions are so useful that later languages like Java keep all methods virtual by default. The compiler maintains two things to serve this purpose: vtable: A table of function pointers, maintained per class. vptr: A pointer to vtable, maintained per object instance (see this for an example). The compiler adds additional code at two places to maintain and use vptr. 1. Code in every constructor. This code sets the vptr of the object being created. This code sets vptr to point to the vtable of the class. 2. Code with polymorphic function call (e.g. bp->show() in above code). Wherever a polymorphic call is made, the compiler inserts code to first look for vptr using a base class pointer or reference (In the above example, since the pointed or referred object is of a derived type, vptr of a derived class is accessed). Once vptr is fetched, vtable of derived class can be accessed. Using vtable, the address of the derived class function show() is accessed and called. Is this a standard way for implementation of run-time polymorphism in C++? The C++ standards do not mandate exactly how runtime polymorphism must be implemented, but compilers generally use minor variations on the same basic model. brain56 scripter architgwl2000 varshagumber28 abhaysasidharan adarshlondhe19 rohitbadgujar kziemianfvt himeshchauhan10 harsh_shokeen rkbhola5 sumitgumber28 simranarora5sos themrinmoy CPP-Functions cpp-inheritance cpp-virtual C++ School Programming CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Templates in C++ with Examples Operator Overloading in C++ unordered_map in C++ STL Socket Programming in C/C++ Queue in C++ Standard Template Library (STL) Python Dictionary Reverse a string in Java Introduction To PYTHON Interfaces in Java C++ Data Types
[ { "code": null, "e": 54, "s": 26, "text": "\n22 Jun, 2022" }, { "code": null, "e": 410, "s": 54, "text": "A virtual function is a member function that is declared in the base class using the keyword virtual and is re-defined (Overriden) in the derived class. It tells the compiler to perform late binding where the compiler matches the object with the right called function and executes it during the runtime. This technique of falls under Runtime Polymorphism." }, { "code": null, "e": 726, "s": 410, "text": "The term Polymorphism means the ability to take many forms. It occurs if there is a hierarchy of classes that are all related to each other by inheritance. In simple words, when we break down Polymorphism into ‘Poly – Many’ and ‘morphism – Forms’ it means showing different characteristics in different situations. " }, { "code": null, "e": 742, "s": 726, "text": "Class Hierarchy" }, { "code": null, "e": 1155, "s": 742, "text": "Note: In C++ what calling a virtual functions means is that; if we call a member function then it could cause a different function to be executed instead depending on what type of object invoked it. Because overriding from derived classes hasn’t happened yet, the virtual call mechanism is disallowed in constructors. Also to mention that objects are built from the ground up or follows a bottom to top approach." }, { "code": null, "e": 1583, "s": 1155, "text": "Consider the following simple program as an example of runtime polymorphism. The main thing to note about the program is that the derived class’s function is called using a base class pointer.The idea is that virtual functions are called according to the type of the object instance pointed to or referenced, not according to the type of the pointer or reference.In other words, virtual functions are resolved late, at runtime." }, { "code": null, "e": 1691, "s": 1583, "text": "Now, we’ll look at an example without using the concepts of virtual function to clarify your understanding." }, { "code": null, "e": 1695, "s": 1691, "text": "C++" }, { "code": "// C++ program to demonstrate how we will calculate// area of shapes without virtual function#include <iostream>using namespace std; // Base classclass Shape {public: // parameterized constructor Shape(int l, int w) { length = l; width = w; } int get_Area() { cout << \"This is call to parent class area\\n\"; // Returning 1 in user-defined function means true return 1; } protected: int length, width;}; // Derived classclass Square : public Shape {public: Square(int l = 0, int w = 0) : Shape(l, w) { } // declaring and initializing derived class // constructor int get_Area() { cout << \"Square area: \" << length * width << '\\n'; return (length * width); }};// Derived classclass Rectangle : public Shape {public: Rectangle(int l = 0, int w = 0) : Shape(l, w) { } // declaring and initializing derived class // constructor int get_Area() { cout << \"Rectangle area: \" << length * width << '\\n'; return (length * width); }}; int main(){ Shape* s; // Making object of child class Square Square sq(5, 5); // Making object of child class Rectangle Rectangle rec(4, 5); s = &sq; // reference variable s->get_Area(); s = &rec; // reference variable s->get_Area(); return 0; // too tell the program executed // successfully}", "e": 3102, "s": 1695, "text": null }, { "code": null, "e": 3170, "s": 3102, "text": "This is call to parent class area\nThis is call to parent class area" }, { "code": null, "e": 3192, "s": 3170, "text": "In the above example:" }, { "code": null, "e": 3272, "s": 3192, "text": "We store the address of each child’s class Rectangle and Square object in s and" }, { "code": null, "e": 3316, "s": 3272, "text": "Then we call the get_Area() function on it," }, { "code": null, "e": 3408, "s": 3316, "text": "Ideally, it should have called the respective get_Area() functions of the child classes but" }, { "code": null, "e": 3468, "s": 3408, "text": "Instead, it calls the get_Area() defined in the base class." }, { "code": null, "e": 3607, "s": 3468, "text": "This happens due to static linkage which means the call to get_Area() is getting set only once by the compiler which is in the base class." }, { "code": null, "e": 3683, "s": 3607, "text": "Example: C++ Program to Calculate the Area of Shapes using Virtual Function" }, { "code": null, "e": 3687, "s": 3683, "text": "C++" }, { "code": "// C++ program to demonstrate how we will calculate// the area of shapes USING VIRTUAL FUNCTION#include <fstream>#include <iostream>using namespace std; // Declaration of Base classclass Shape {public: // Usage of virtual constructor virtual void calculate() { cout << \"Area of your Shape \"; } // usage of virtual Destuctor to avoid memory leak virtual ~Shape() { cout << \"Shape Destuctor Call\\n\"; }}; // Declaration of Derived classclass Rectangle : public Shape {public: int width, height, area; void calculate() { cout << \"Enter Width of Rectangle: \"; cin >> width; cout << \"Enter Height of Rectangle: \"; cin >> height; area = height * width; cout << \"Area of Rectangle: \" << area << \"\\n\"; } // Virtual Destuctor for every Derived class virtual ~Rectangle() { cout << \"Rectangle Destuctor Call\\n\"; }}; // Declaration of 2nd derived classclass Square : public Shape {public: int side, area; void calculate() { cout << \"Enter one side your of Square: \"; cin >> side; area = side * side; cout << \"Area of Square: \" << area << \"\\n\"; } // Virtual Destuctor for every Derived class virtual ~Square() { cout << \"Square Destuctor Call\\n\"; }}; int main(){ // base class pointer Shape* S; Rectangle r; // initialization of reference variable S = &r; // calling of Rectangle function S->calculate(); Square sq; // initialization of reference variable S = &sq; // calling of Square function S->calculate(); // return 0 to tell the program executed // successfully return 0;}", "e": 5382, "s": 3687, "text": null }, { "code": null, "e": 5390, "s": 5382, "text": "Output:" }, { "code": null, "e": 5526, "s": 5390, "text": "Enter Width of Rectangle: 10\nEnter Height of Rectangle: 20\nArea of Rectangle: 200\nEnter one side your of Square: 16\nArea of Square: 256" }, { "code": null, "e": 5713, "s": 5526, "text": "What is the use? Virtual functions allow us to create a list of base class pointers and call methods of any of the derived classes without even knowing the kind of derived class object. " }, { "code": null, "e": 6057, "s": 5713, "text": "Consider employee management software for an organization.Let the code has a simple base class Employee, the class contains virtual functions like raiseSalary(), transfer(), promote(), etc. Different types of employees like Managers, Engineers, etc., may have their own implementations of the virtual functions present in base class Employee. " }, { "code": null, "e": 6514, "s": 6057, "text": "In our complete software, we just need to pass a list of employees everywhere and call appropriate functions without even knowing the type of employee. For example, we can easily raise the salary of all employees by iterating through the list of employees. Every type of employee may have its own logic in its class, but we don’t need to worry about them because if raiseSalary() is present for a specific employee type, only that function would be called." }, { "code": null, "e": 6518, "s": 6514, "text": "CPP" }, { "code": "// C++ program to demonstrate how a virtual function// is used in a real life scenario class Employee {public: virtual void raiseSalary() { // common raise salary code } virtual void promote() { // common promote code }}; class Manager : public Employee { virtual void raiseSalary() { // Manager specific raise salary code, may contain // increment of manager specific incentives } virtual void promote() { // Manager specific promote }}; // Similarly, there may be other types of employees // We need a very simple function// to increment the salary of all employees// Note that emp[] is an array of pointers// and actual pointed objects can// be any type of employees.// This function should ideally// be in a class like Organization,// we have made it global to keep things simplevoid globalRaiseSalary(Employee* emp[], int n){ for (int i = 0; i < n; i++) { // Polymorphic Call: Calls raiseSalary() // according to the actual object, not // according to the type of pointer emp[i]->raiseSalary(); }}", "e": 7628, "s": 6518, "text": null }, { "code": null, "e": 7903, "s": 7628, "text": "Like the ‘globalRaiseSalary()‘ function, there can be many other operations that can be performed on a list of employees without even knowing the type of the object instance. Virtual functions are so useful that later languages like Java keep all methods virtual by default." }, { "code": null, "e": 7960, "s": 7903, "text": "The compiler maintains two things to serve this purpose:" }, { "code": null, "e": 8021, "s": 7960, "text": "vtable: A table of function pointers, maintained per class. " }, { "code": null, "e": 8107, "s": 8021, "text": "vptr: A pointer to vtable, maintained per object instance (see this for an example). " }, { "code": null, "e": 8181, "s": 8107, "text": "The compiler adds additional code at two places to maintain and use vptr." }, { "code": null, "e": 8322, "s": 8181, "text": "1. Code in every constructor. This code sets the vptr of the object being created. This code sets vptr to point to the vtable of the class. " }, { "code": null, "e": 8790, "s": 8322, "text": "2. Code with polymorphic function call (e.g. bp->show() in above code). Wherever a polymorphic call is made, the compiler inserts code to first look for vptr using a base class pointer or reference (In the above example, since the pointed or referred object is of a derived type, vptr of a derived class is accessed). Once vptr is fetched, vtable of derived class can be accessed. Using vtable, the address of the derived class function show() is accessed and called." }, { "code": null, "e": 9022, "s": 8790, "text": "Is this a standard way for implementation of run-time polymorphism in C++? The C++ standards do not mandate exactly how runtime polymorphism must be implemented, but compilers generally use minor variations on the same basic model." }, { "code": null, "e": 9030, "s": 9022, "text": "brain56" }, { "code": null, "e": 9039, "s": 9030, "text": "scripter" }, { "code": null, "e": 9053, "s": 9039, "text": "architgwl2000" }, { "code": null, "e": 9068, "s": 9053, "text": "varshagumber28" }, { "code": null, "e": 9084, "s": 9068, "text": "abhaysasidharan" }, { "code": null, "e": 9099, "s": 9084, "text": "adarshlondhe19" }, { "code": null, "e": 9113, "s": 9099, "text": "rohitbadgujar" }, { "code": null, "e": 9125, "s": 9113, "text": "kziemianfvt" }, { "code": null, "e": 9141, "s": 9125, "text": "himeshchauhan10" }, { "code": null, "e": 9155, "s": 9141, "text": "harsh_shokeen" }, { "code": null, "e": 9164, "s": 9155, "text": "rkbhola5" }, { "code": null, "e": 9178, "s": 9164, "text": "sumitgumber28" }, { "code": null, "e": 9194, "s": 9178, "text": "simranarora5sos" }, { "code": null, "e": 9205, "s": 9194, "text": "themrinmoy" }, { "code": null, "e": 9219, "s": 9205, "text": "CPP-Functions" }, { "code": null, "e": 9235, "s": 9219, "text": "cpp-inheritance" }, { "code": null, "e": 9247, "s": 9235, "text": "cpp-virtual" }, { "code": null, "e": 9251, "s": 9247, "text": "C++" }, { "code": null, "e": 9270, "s": 9251, "text": "School Programming" }, { "code": null, "e": 9274, "s": 9270, "text": "CPP" }, { "code": null, "e": 9372, "s": 9274, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 9403, "s": 9372, "text": "Templates in C++ with Examples" }, { "code": null, "e": 9431, "s": 9403, "text": "Operator Overloading in C++" }, { "code": null, "e": 9456, "s": 9431, "text": "unordered_map in C++ STL" }, { "code": null, "e": 9484, "s": 9456, "text": "Socket Programming in C/C++" }, { "code": null, "e": 9529, "s": 9484, "text": "Queue in C++ Standard Template Library (STL)" }, { "code": null, "e": 9547, "s": 9529, "text": "Python Dictionary" }, { "code": null, "e": 9572, "s": 9547, "text": "Reverse a string in Java" }, { "code": null, "e": 9595, "s": 9572, "text": "Introduction To PYTHON" }, { "code": null, "e": 9614, "s": 9595, "text": "Interfaces in Java" } ]
Search an element in a sorted and rotated array with duplicates
27 May, 2022 Given an array arr[] which is sorted and rotated, the task is to find an element in the rotated array (with duplicates) in O(log n) time. Note: Print the index where the key exists. In case of multiple answer print any of them Examples: Input: arr[] = {3, 3, 3, 1, 2, 3}, key = 3 Output: 0 arr[0] = 3 Input: arr[] = {3, 3, 3, 1, 2, 3}, key = 11 Output: -1 11 is not present in the given array. Approach: The idea is the same as the previous one without duplicates. The only difference is that due to the existence of duplicates, arr[low] == arr[mid] could be possible, the first half could be out of order (i.e. not in the ascending order, e.g. {3, 1, 2, 3, 3, 3, 3}) and we have to deal this case separately. In that case, it is guaranteed that arr[high] also equal to arr[mid], so the condition arr[mid] == arr[low] == arr[high] can be checked before the original logic, and if so then move left and right both towards the middle by 1 and repeat. Chapters descriptions off, selected captions settings, opens captions settings dialog captions off, selected English This is a modal window. Beginning of dialog window. Escape will cancel and close the window. End of dialog window. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the index of the// key in arr[l..h] if the key is present// otherwise return -1int search(int arr[], int l, int h, int key){ if (l > h) return -1; int mid = l + (h - l) / 2; if (arr[mid] == key) return mid; // The tricky case, just update left and right if ((arr[l] == arr[mid]) && (arr[h] == arr[mid])) { ++l; --h; return search(arr, l, h, key); } // If arr[l...mid] is sorted if (arr[l] <= arr[mid]) { // As this subarray is sorted, we can quickly // check if key lies in any of the halves if (key >= arr[l] && key <= arr[mid]) return search(arr, l, mid - 1, key); // If key does not lie in the first half // subarray then divide the other half // into two subarrays such that we can // quickly check if key lies in the other half return search(arr, mid + 1, h, key); } // If arr[l..mid] first subarray is not sorted // then arr[mid... h] must be sorted subarray if (key >= arr[mid] && key <= arr[h]) return search(arr, mid + 1, h, key); return search(arr, l, mid - 1, key);} // Driver codeint main(){ int arr[] = { 3, 3, 1, 2, 3, 3 }; int n = sizeof(arr) / sizeof(int); int key = 3; cout << search(arr, 0, n - 1, key); return 0;} // Java implementation of the approachclass GFG{ // Function to return the index of the // key in arr[l..h] if the key is present // otherwise return -1 static int search(int arr[], int l, int h, int key) { if (l > h) return -1; int mid = l + (h - l) / 2; if (arr[mid] == key) return mid; // The tricky case, just update left and right if ((arr[l] == arr[mid]) && (arr[h] == arr[mid])) { l++; h--; return search(arr,l,h,key); } // If arr[l...mid] is sorted else if (arr[l] <= arr[mid]) { // As this subarray is sorted, we can quickly // check if key lies in any of the halves if (key >= arr[l] && key <= arr[mid]) return search(arr, l, mid - 1, key); // If key does not lie in the first half // subarray then divide the other half // into two subarrays such that we can // quickly check if key lies in the other half else return search(arr, mid + 1, h, key); } // If arr[l..mid] first subarray is not sorted // then arr[mid... h] must be sorted subarray else if (key >= arr[mid] && key <= arr[h]) return search(arr, mid + 1, h, key); return search(arr, l, mid - 1, key); } // Driver code public static void main (String[] args) { int arr[] ={3, 3, 1, 2, 3, 3}; int n = arr.length; int key = 3; System.out.println(search(arr, 0, n - 1, key)); }} // This code is contributed by AnkitRai01 # Python3 implementation of the approach # Function to return the index of the# key in arr[l..h] if the key is present# otherwise return -1def search(arr, l, h, key) : if (l > h) : return -1; mid = (l + h) // 2; if (arr[mid] == key) : return mid; # The tricky case, just update left and right if ((arr[l] == arr[mid]) and (arr[h] == arr[mid])) : l += 1; h -= 1; return search(arr, l, h, key) # If arr[l...mid] is sorted if (arr[l] <= arr[mid]) : # As this subarray is sorted, we can quickly # check if key lies in any of the halves if (key >= arr[l] and key <= arr[mid]) : return search(arr, l, mid - 1, key); # If key does not lie in the first half # subarray then divide the other half # into two subarrays such that we can # quickly check if key lies in the other half return search(arr, mid + 1, h, key); # If arr[l..mid] first subarray is not sorted # then arr[mid... h] must be sorted subarray if (key >= arr[mid] and key <= arr[h]) : return search(arr, mid + 1, h, key); return search(arr, l, mid - 1, key); # Driver codeif __name__ == "__main__" : arr = [ 3, 3, 1, 2, 3, 3 ]; n = len(arr); key = 3; print(search(arr, 0, n - 1, key)); # This code is contributed by AnkitRai01 // C# implementation of the approachusing System; class GFG{ // Function to return the index of the // key in arr[l..h] if the key is present // otherwise return -1 static int search(int []arr, int l, int h, int key) { if (l > h) return -1; int mid = l + (h - l) / 2; if (arr[mid] == key) return mid; // The tricky case, just update left and right if ((arr[l] == arr[mid]) && (arr[h] == arr[mid])) { ++l; --h; return search(arr, l, h, key) } // If arr[l...mid] is sorted if (arr[l] <= arr[mid]) { // As this subarray is sorted, we can quickly // check if key lies in any of the halves if (key >= arr[l] && key <= arr[mid]) return search(arr, l, mid - 1, key); // If key does not lie in the first half // subarray then divide the other half // into two subarrays such that we can // quickly check if key lies in the other half return search(arr, mid + 1, h, key); } // If arr[l..mid] first subarray is not sorted // then arr[mid... h] must be sorted subarray if (key >= arr[mid] && key <= arr[h]) return search(arr, mid + 1, h, key); return search(arr, l, mid - 1, key); } // Driver code public static void Main () { int []arr = { 3, 3, 1, 2, 3, 3 }; int n = arr.Length; int key = 3; Console.WriteLine(search(arr, 0, n - 1, key)); }} // This code is contributed by AnkitRai01 <script> // Javascript implementation of the approach // Function to return the index of the // key in arr[l..h] if the key is present // otherwise return -1 function search(arr, l, h, key) { if (l > h) return -1; let mid = parseInt((l + h) / 2, 10); if (arr[mid] == key) return mid; // The tricky case, just update left and right if ((arr[l] == arr[mid]) && (arr[h] == arr[mid])) { ++l; --h; return search(arr, l, h, key) } // If arr[l...mid] is sorted if (arr[l] <= arr[mid]) { // As this subarray is sorted, we can quickly // check if key lies in any of the halves if (key >= arr[l] && key <= arr[mid]) return search(arr, l, mid - 1, key); // If key does not lie in the first half // subarray then divide the other half // into two subarrays such that we can // quickly check if key lies in the other half return search(arr, mid + 1, h, key); } // If arr[l..mid] first subarray is not sorted // then arr[mid... h] must be sorted subarray if (key >= arr[mid] && key <= arr[h]) return search(arr, mid + 1, h, key); return search(arr, l, mid - 1, key); } let arr = [ 3, 3, 1, 2, 3, 3 ]; let n = arr.length; let key = 3; document.write(search(arr, 0, n - 1, key)); </script> 4 Time Complexity: O(logn), where n represents the size of the given array.Auxiliary Space: O(logn) due to recursive stack space. ankthon ishabhargav sarthakbansal2000 decode2207 16kumar01rishabh samim2000 Binary Search Arrays Sorting Arrays Sorting Binary Search Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Data Structures Window Sliding Technique Search, insert and delete in an unsorted array Chocolate Distribution Problem Find duplicates in O(n) time and O(1) extra space | Set 1 Merge Sort Bubble Sort Algorithm QuickSort Insertion Sort Selection Sort Algorithm
[ { "code": null, "e": 52, "s": 24, "text": "\n27 May, 2022" }, { "code": null, "e": 279, "s": 52, "text": "Given an array arr[] which is sorted and rotated, the task is to find an element in the rotated array (with duplicates) in O(log n) time. Note: Print the index where the key exists. In case of multiple answer print any of them" }, { "code": null, "e": 290, "s": 279, "text": "Examples: " }, { "code": null, "e": 354, "s": 290, "text": "Input: arr[] = {3, 3, 3, 1, 2, 3}, key = 3 Output: 0 arr[0] = 3" }, { "code": null, "e": 448, "s": 354, "text": "Input: arr[] = {3, 3, 3, 1, 2, 3}, key = 11 Output: -1 11 is not present in the given array. " }, { "code": null, "e": 1003, "s": 448, "text": "Approach: The idea is the same as the previous one without duplicates. The only difference is that due to the existence of duplicates, arr[low] == arr[mid] could be possible, the first half could be out of order (i.e. not in the ascending order, e.g. {3, 1, 2, 3, 3, 3, 3}) and we have to deal this case separately. In that case, it is guaranteed that arr[high] also equal to arr[mid], so the condition arr[mid] == arr[low] == arr[high] can be checked before the original logic, and if so then move left and right both towards the middle by 1 and repeat." }, { "code": null, "e": 1012, "s": 1003, "text": "Chapters" }, { "code": null, "e": 1039, "s": 1012, "text": "descriptions off, selected" }, { "code": null, "e": 1089, "s": 1039, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 1112, "s": 1089, "text": "captions off, selected" }, { "code": null, "e": 1120, "s": 1112, "text": "English" }, { "code": null, "e": 1144, "s": 1120, "text": "This is a modal window." }, { "code": null, "e": 1213, "s": 1144, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 1235, "s": 1213, "text": "End of dialog window." }, { "code": null, "e": 1287, "s": 1235, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 1291, "s": 1287, "text": "C++" }, { "code": null, "e": 1296, "s": 1291, "text": "Java" }, { "code": null, "e": 1304, "s": 1296, "text": "Python3" }, { "code": null, "e": 1307, "s": 1304, "text": "C#" }, { "code": null, "e": 1318, "s": 1307, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the index of the// key in arr[l..h] if the key is present// otherwise return -1int search(int arr[], int l, int h, int key){ if (l > h) return -1; int mid = l + (h - l) / 2; if (arr[mid] == key) return mid; // The tricky case, just update left and right if ((arr[l] == arr[mid]) && (arr[h] == arr[mid])) { ++l; --h; return search(arr, l, h, key); } // If arr[l...mid] is sorted if (arr[l] <= arr[mid]) { // As this subarray is sorted, we can quickly // check if key lies in any of the halves if (key >= arr[l] && key <= arr[mid]) return search(arr, l, mid - 1, key); // If key does not lie in the first half // subarray then divide the other half // into two subarrays such that we can // quickly check if key lies in the other half return search(arr, mid + 1, h, key); } // If arr[l..mid] first subarray is not sorted // then arr[mid... h] must be sorted subarray if (key >= arr[mid] && key <= arr[h]) return search(arr, mid + 1, h, key); return search(arr, l, mid - 1, key);} // Driver codeint main(){ int arr[] = { 3, 3, 1, 2, 3, 3 }; int n = sizeof(arr) / sizeof(int); int key = 3; cout << search(arr, 0, n - 1, key); return 0;}", "e": 2737, "s": 1318, "text": null }, { "code": "// Java implementation of the approachclass GFG{ // Function to return the index of the // key in arr[l..h] if the key is present // otherwise return -1 static int search(int arr[], int l, int h, int key) { if (l > h) return -1; int mid = l + (h - l) / 2; if (arr[mid] == key) return mid; // The tricky case, just update left and right if ((arr[l] == arr[mid]) && (arr[h] == arr[mid])) { l++; h--; return search(arr,l,h,key); } // If arr[l...mid] is sorted else if (arr[l] <= arr[mid]) { // As this subarray is sorted, we can quickly // check if key lies in any of the halves if (key >= arr[l] && key <= arr[mid]) return search(arr, l, mid - 1, key); // If key does not lie in the first half // subarray then divide the other half // into two subarrays such that we can // quickly check if key lies in the other half else return search(arr, mid + 1, h, key); } // If arr[l..mid] first subarray is not sorted // then arr[mid... h] must be sorted subarray else if (key >= arr[mid] && key <= arr[h]) return search(arr, mid + 1, h, key); return search(arr, l, mid - 1, key); } // Driver code public static void main (String[] args) { int arr[] ={3, 3, 1, 2, 3, 3}; int n = arr.length; int key = 3; System.out.println(search(arr, 0, n - 1, key)); }} // This code is contributed by AnkitRai01", "e": 4436, "s": 2737, "text": null }, { "code": "# Python3 implementation of the approach # Function to return the index of the# key in arr[l..h] if the key is present# otherwise return -1def search(arr, l, h, key) : if (l > h) : return -1; mid = (l + h) // 2; if (arr[mid] == key) : return mid; # The tricky case, just update left and right if ((arr[l] == arr[mid]) and (arr[h] == arr[mid])) : l += 1; h -= 1; return search(arr, l, h, key) # If arr[l...mid] is sorted if (arr[l] <= arr[mid]) : # As this subarray is sorted, we can quickly # check if key lies in any of the halves if (key >= arr[l] and key <= arr[mid]) : return search(arr, l, mid - 1, key); # If key does not lie in the first half # subarray then divide the other half # into two subarrays such that we can # quickly check if key lies in the other half return search(arr, mid + 1, h, key); # If arr[l..mid] first subarray is not sorted # then arr[mid... h] must be sorted subarray if (key >= arr[mid] and key <= arr[h]) : return search(arr, mid + 1, h, key); return search(arr, l, mid - 1, key); # Driver codeif __name__ == \"__main__\" : arr = [ 3, 3, 1, 2, 3, 3 ]; n = len(arr); key = 3; print(search(arr, 0, n - 1, key)); # This code is contributed by AnkitRai01", "e": 5790, "s": 4436, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{ // Function to return the index of the // key in arr[l..h] if the key is present // otherwise return -1 static int search(int []arr, int l, int h, int key) { if (l > h) return -1; int mid = l + (h - l) / 2; if (arr[mid] == key) return mid; // The tricky case, just update left and right if ((arr[l] == arr[mid]) && (arr[h] == arr[mid])) { ++l; --h; return search(arr, l, h, key) } // If arr[l...mid] is sorted if (arr[l] <= arr[mid]) { // As this subarray is sorted, we can quickly // check if key lies in any of the halves if (key >= arr[l] && key <= arr[mid]) return search(arr, l, mid - 1, key); // If key does not lie in the first half // subarray then divide the other half // into two subarrays such that we can // quickly check if key lies in the other half return search(arr, mid + 1, h, key); } // If arr[l..mid] first subarray is not sorted // then arr[mid... h] must be sorted subarray if (key >= arr[mid] && key <= arr[h]) return search(arr, mid + 1, h, key); return search(arr, l, mid - 1, key); } // Driver code public static void Main () { int []arr = { 3, 3, 1, 2, 3, 3 }; int n = arr.Length; int key = 3; Console.WriteLine(search(arr, 0, n - 1, key)); }} // This code is contributed by AnkitRai01", "e": 7458, "s": 5790, "text": null }, { "code": "<script> // Javascript implementation of the approach // Function to return the index of the // key in arr[l..h] if the key is present // otherwise return -1 function search(arr, l, h, key) { if (l > h) return -1; let mid = parseInt((l + h) / 2, 10); if (arr[mid] == key) return mid; // The tricky case, just update left and right if ((arr[l] == arr[mid]) && (arr[h] == arr[mid])) { ++l; --h; return search(arr, l, h, key) } // If arr[l...mid] is sorted if (arr[l] <= arr[mid]) { // As this subarray is sorted, we can quickly // check if key lies in any of the halves if (key >= arr[l] && key <= arr[mid]) return search(arr, l, mid - 1, key); // If key does not lie in the first half // subarray then divide the other half // into two subarrays such that we can // quickly check if key lies in the other half return search(arr, mid + 1, h, key); } // If arr[l..mid] first subarray is not sorted // then arr[mid... h] must be sorted subarray if (key >= arr[mid] && key <= arr[h]) return search(arr, mid + 1, h, key); return search(arr, l, mid - 1, key); } let arr = [ 3, 3, 1, 2, 3, 3 ]; let n = arr.length; let key = 3; document.write(search(arr, 0, n - 1, key)); </script>", "e": 9011, "s": 7458, "text": null }, { "code": null, "e": 9013, "s": 9011, "text": "4" }, { "code": null, "e": 9141, "s": 9013, "text": "Time Complexity: O(logn), where n represents the size of the given array.Auxiliary Space: O(logn) due to recursive stack space." }, { "code": null, "e": 9149, "s": 9141, "text": "ankthon" }, { "code": null, "e": 9161, "s": 9149, "text": "ishabhargav" }, { "code": null, "e": 9179, "s": 9161, "text": "sarthakbansal2000" }, { "code": null, "e": 9190, "s": 9179, "text": "decode2207" }, { "code": null, "e": 9207, "s": 9190, "text": "16kumar01rishabh" }, { "code": null, "e": 9217, "s": 9207, "text": "samim2000" }, { "code": null, "e": 9231, "s": 9217, "text": "Binary Search" }, { "code": null, "e": 9238, "s": 9231, "text": "Arrays" }, { "code": null, "e": 9246, "s": 9238, "text": "Sorting" }, { "code": null, "e": 9253, "s": 9246, "text": "Arrays" }, { "code": null, "e": 9261, "s": 9253, "text": "Sorting" }, { "code": null, "e": 9275, "s": 9261, "text": "Binary Search" }, { "code": null, "e": 9373, "s": 9275, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 9405, "s": 9373, "text": "Introduction to Data Structures" }, { "code": null, "e": 9430, "s": 9405, "text": "Window Sliding Technique" }, { "code": null, "e": 9477, "s": 9430, "text": "Search, insert and delete in an unsorted array" }, { "code": null, "e": 9508, "s": 9477, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 9566, "s": 9508, "text": "Find duplicates in O(n) time and O(1) extra space | Set 1" }, { "code": null, "e": 9577, "s": 9566, "text": "Merge Sort" }, { "code": null, "e": 9599, "s": 9577, "text": "Bubble Sort Algorithm" }, { "code": null, "e": 9609, "s": 9599, "text": "QuickSort" }, { "code": null, "e": 9624, "s": 9609, "text": "Insertion Sort" } ]
C++ Program to Implement Hash Tables with Linear Probing
A hash table is a data structure which is used to store key-value pairs. Hash function is used by hash table to compute an index into an array in which an element will be inserted or searched. Linear probing is a collision resolving technique in Open Addressed Hash tables. In this method, each cell of a hash table stores a single key–value pair. If a collision is occurred by mapping a new key to a cell of the hash table that is already occupied by another key. This method searches the table for the following closest free location and inserts the new key there. This is a C++ Program to Implement Hash Tables with Linear Probing. For Insert: Begin Declare Function Insert(int k, int v) int hash_val = HashFunc(k) intialize init = -1 intialize delindex = -1 while (hash_val != init and (ht[hash_val]==DelNode::getNode() or ht[hash_val] != NULL and ht[hash_val]->k != k)) if (init == -1) init = hash_val if (ht[hash_val] == DelNode::getNode()) delindex = hash_val hash_val = HashFunc(hash_val + 1) if (ht[hash_val] == NULL || hash_val == init) if(delindex != -1) ht[delindex] = new HashTable(k, v) else ht[hash_val] = new HashTable(k, v) if(init != hash_val) if (ht[hash_val] != DelNode::getNode()) if (ht[hash_val] != NULL) if (ht[hash_val]->k== k) ht[hash_val]->v = v else ht[hash_val] = new HashTable(k, v) End. For Search a key: Begin Declare Function SearchKey(int k) int hash_val = HashFunc(k) int init = -1 while (hash_val != init and (ht[hash_val] == DelNode::getNode() or ht[hash_val] != NULL and ht[hash_val]->k!= k)) if (init == -1) init = hash_val hash_val = HashFunc(hash_val + 1) if (ht[hash_val] == NULL or hash_val == init) return -1 else return ht[hash_val]->v End. For Delete: Begin Declare Function Remove(int k) int hash_val = HashFunc(k) intialize init = -1 while (hash_val != init and (ht[hash_val] == DelNode::getNode() or ht[hash_val] != NULL and ht[hash_val]->k!= k)) if (init == -1) init = hash_val hash_val = HashFunc(hash_val + 1) if (hash_val != init && ht[hash_val] != NULL) delete ht[hash_val] ht[hash_val] = DelNode::getNode() End Live Demo #include <iostream> #include <cstdio> #include <cstdlib> using namespace std; const int T_S = 5; class HashTable { public: int k; int v; HashTable(int k, int v) { this->k = k; this->v = v; } }; class DelNode:public HashTable { private: static DelNode *en; DelNode():HashTable(-1, -1) {} public: static DelNode *getNode() { if (en == NULL) en = new DelNode(); return en; } }; DelNode *DelNode::en = NULL; class HashMapTable { private: HashTable **ht; public: HashMapTable() { ht = new HashTable* [T_S]; for (int i = 0; i < T_S; i++) { ht[i] = NULL; } } int HashFunc(int k) { return k % T_S; } void Insert(int k, int v) { int hash_val = HashFunc(k); int init = -1; int delindex = -1; while (hash_val != init && (ht[hash_val] == DelNode::getNode() || ht[hash_val] != NULL && ht[hash_val]->k != k)) { if (init == -1) init = hash_val; if (ht[hash_val] == DelNode::getNode()) delindex = hash_val; hash_val = HashFunc(hash_val + 1); } if (ht[hash_val] == NULL || hash_val == init) { if(delindex != -1) ht[delindex] = new HashTable(k, v); else ht[hash_val] = new HashTable(k, v); } if(init != hash_val) { if (ht[hash_val] != DelNode::getNode()) { if (ht[hash_val] != NULL) { if (ht[hash_val]->k== k) ht[hash_val]->v = v; } } else ht[hash_val] = new HashTable(k, v); } } int SearchKey(int k) { int hash_val = HashFunc(k); int init = -1; while (hash_val != init && (ht[hash_val] == DelNode::getNode() || ht[hash_val] != NULL && ht[hash_val]->k!= k)) { if (init == -1) init = hash_val; hash_val = HashFunc(hash_val + 1); } if (ht[hash_val] == NULL || hash_val == init) return -1; else return ht[hash_val]->v; } void Remove(int k) { int hash_val = HashFunc(k); int init = -1; while (hash_val != init && (ht[hash_val] == DelNode::getNode() || ht[hash_val] != NULL && ht[hash_val]->k!= k)) { if (init == -1) init = hash_val; hash_val = HashFunc(hash_val + 1); } if (hash_val != init && ht[hash_val] != NULL) { delete ht[hash_val]; ht[hash_val] = DelNode::getNode(); } } ~HashMapTable() { delete[] ht; } }; int main() { HashMapTable hash; int k, v; int c; while(1) { cout<<"1.Insert element into the table"<<endl; cout<<"2.Search element from the key"<<endl; cout<<"3.Delete element at a key"<<endl; cout<<"4.Exit"<<endl; cout<<"Enter your choice: "; cin>>c; switch(c) { case 1: cout<<"Enter element to be inserted: "; cin>>v; cout<<"Enter key at which element to be inserted: "; cin>>k; hash.Insert(k, v); break; case 2: cout<<"Enter key of the element to be searched: "; cin>>k; if(hash.SearchKey(k) == -1) { cout<<"No element found at key "<<k<<endl; continue; } else { cout<<"Element at key "<<k<<" : "; cout<<hash.SearchKey(k)<<endl; } break; case 3: cout<<"Enter key of the element to be deleted: "; cin>>k; hash.Remove(k); break; case 4: exit(1); default: cout<<"\nEnter correct option\n"; } } return 0; } 1.Insert element into the table 2.Search element from the key 3.Delete element at a key 4.Exit Enter your choice: 1 Enter element to be inserted: 10 Enter key at which element to be inserted: 2 1.Insert element into the table 2.Search element from the key 3.Delete element at a key 4.Exit Enter your choice: 1 Enter element to be inserted: 7 Enter key at which element to be inserted: 6 1.Insert element into the table 2.Search element from the key 3.Delete element at a key 4.Exit Enter your choice: 1 Enter element to be inserted: 4 Enter key at which element to be inserted: 5 1.Insert element into the table 2.Search element from the key 3.Delete element at a key 4.Exit Enter your choice: 1 Enter element to be inserted: 12 Enter key at which element to be inserted: 3 1.Insert element into the table 2.Search element from the key 3.Delete element at a key 4.Exit Enter your choice: 15 Enter correct option 1.Insert element into the table 2.Search element from the key 3.Delete element at a key 4.Exit Enter your choice: 1 Enter element to be inserted: 15 Enter key at which element to be inserted: 8 1.Insert element into the table 2.Search element from the key 3.Delete element at a key 4.Exit Enter your choice: 2 Enter key of the element to be searched: 6 Element at key 6 : 7 1.Insert element into the table 2.Search element from the key 3.Delete element at a key 4.Exit Enter your choice: 3 Enter key of the element to be deleted: 2 1.Insert element into the table 2.Search element from the key 3.Delete element at a key 4.Exit Enter your choice: 2 Enter key of the element to be searched: 2 No element found at key 2 1.Insert element into the table 2.Search element from the key 3.Delete element at a key 4.Exit Enter your choice: 4
[ { "code": null, "e": 1380, "s": 1187, "text": "A hash table is a data structure which is used to store key-value pairs. Hash function is used by hash table to compute an index into an array in which an element will be inserted or searched." }, { "code": null, "e": 1754, "s": 1380, "text": "Linear probing is a collision resolving technique in Open Addressed Hash tables. In this method, each cell of a hash table stores a single key–value pair. If a collision is occurred by mapping a new key to a cell of the hash table that is already occupied by another key. This method searches the table for the following closest free location and inserts the new key there." }, { "code": null, "e": 1822, "s": 1754, "text": "This is a C++ Program to Implement Hash Tables with Linear Probing." }, { "code": null, "e": 1834, "s": 1822, "text": "For Insert:" }, { "code": null, "e": 2727, "s": 1834, "text": "Begin\n Declare Function Insert(int k, int v)\n int hash_val = HashFunc(k)\n intialize init = -1\n intialize delindex = -1\n while (hash_val != init and\n (ht[hash_val]==DelNode::getNode() or ht[hash_val]\n != NULL and ht[hash_val]->k != k))\n if (init == -1)\n init = hash_val\n if (ht[hash_val] == DelNode::getNode())\n delindex = hash_val\n hash_val = HashFunc(hash_val + 1)\n if (ht[hash_val] == NULL || hash_val == init)\n if(delindex != -1)\n ht[delindex] = new HashTable(k, v)\n else\n ht[hash_val] = new HashTable(k, v)\n if(init != hash_val)\n if (ht[hash_val] != DelNode::getNode())\n if (ht[hash_val] != NULL)\n if (ht[hash_val]->k== k)\n ht[hash_val]->v = v\n else\n ht[hash_val] = new HashTable(k, v)\nEnd." }, { "code": null, "e": 2745, "s": 2727, "text": "For Search a key:" }, { "code": null, "e": 3203, "s": 2745, "text": "Begin\n Declare Function SearchKey(int k)\n int hash_val = HashFunc(k)\n int init = -1\n while (hash_val != init and (ht[hash_val]\n == DelNode::getNode() or ht[hash_val]\n != NULL and ht[hash_val]->k!= k))\n if (init == -1)\n init = hash_val\n hash_val = HashFunc(hash_val + 1)\n if (ht[hash_val] == NULL or hash_val == init)\n return -1\n else\n return ht[hash_val]->v\nEnd." }, { "code": null, "e": 3215, "s": 3203, "text": "For Delete:" }, { "code": null, "e": 3676, "s": 3215, "text": "Begin\n Declare Function Remove(int k)\n int hash_val = HashFunc(k)\n intialize init = -1\n while (hash_val != init and (ht[hash_val]\n == DelNode::getNode() or ht[hash_val]\n != NULL and ht[hash_val]->k!= k))\n if (init == -1)\n init = hash_val\n hash_val = HashFunc(hash_val + 1)\n if (hash_val != init && ht[hash_val] != NULL)\n delete ht[hash_val]\n ht[hash_val] = DelNode::getNode()\nEnd" }, { "code": null, "e": 3687, "s": 3676, "text": " Live Demo" }, { "code": null, "e": 7659, "s": 3687, "text": "#include <iostream>\n#include <cstdio>\n#include <cstdlib>\nusing namespace std;\nconst int T_S = 5;\nclass HashTable {\n public:\n int k;\n int v;\n HashTable(int k, int v) {\n this->k = k;\n this->v = v;\n }\n};\nclass DelNode:public HashTable {\n private:\n static DelNode *en;\n DelNode():HashTable(-1, -1) {}\n public:\n static DelNode *getNode() {\n if (en == NULL)\n en = new DelNode();\n return en;\n }\n};\nDelNode *DelNode::en = NULL;\nclass HashMapTable {\n private:\n HashTable **ht;\n public:\n HashMapTable() {\n ht = new HashTable* [T_S];\n for (int i = 0; i < T_S; i++) {\n ht[i] = NULL;\n }\n }\n int HashFunc(int k) {\n return k % T_S;\n }\n void Insert(int k, int v) {\n int hash_val = HashFunc(k);\n int init = -1;\n int delindex = -1;\n while (hash_val != init && (ht[hash_val] == DelNode::getNode() || ht[hash_val] != NULL && ht[hash_val]->k != k)) {\n if (init == -1)\n init = hash_val;\n if (ht[hash_val] == DelNode::getNode())\n delindex = hash_val;\n hash_val = HashFunc(hash_val + 1);\n }\n if (ht[hash_val] == NULL || hash_val == init) {\n if(delindex != -1)\n ht[delindex] = new HashTable(k, v);\n else\n ht[hash_val] = new HashTable(k, v);\n }\n if(init != hash_val) {\n if (ht[hash_val] != DelNode::getNode()) {\n if (ht[hash_val] != NULL) {\n if (ht[hash_val]->k== k)\n ht[hash_val]->v = v;\n }\n } else\n ht[hash_val] = new HashTable(k, v);\n }\n }\n int SearchKey(int k) {\n int hash_val = HashFunc(k);\n int init = -1;\n while (hash_val != init && (ht[hash_val] == DelNode::getNode() || ht[hash_val] != NULL && ht[hash_val]->k!= k)) {\n if (init == -1)\n init = hash_val;\n hash_val = HashFunc(hash_val + 1);\n }\n if (ht[hash_val] == NULL || hash_val == init)\n return -1;\n else\n return ht[hash_val]->v;\n }\n void Remove(int k) {\n int hash_val = HashFunc(k);\n int init = -1;\n while (hash_val != init && (ht[hash_val] == DelNode::getNode() || ht[hash_val] != NULL && ht[hash_val]->k!= k)) {\n if (init == -1)\n init = hash_val;\n hash_val = HashFunc(hash_val + 1);\n }\n if (hash_val != init && ht[hash_val] != NULL) {\n delete ht[hash_val];\n ht[hash_val] = DelNode::getNode();\n }\n }\n ~HashMapTable() {\n delete[] ht;\n }\n};\nint main() {\n HashMapTable hash;\n int k, v;\n int c;\n while(1) {\n cout<<\"1.Insert element into the table\"<<endl;\n cout<<\"2.Search element from the key\"<<endl;\n cout<<\"3.Delete element at a key\"<<endl;\n cout<<\"4.Exit\"<<endl;\n cout<<\"Enter your choice: \";\n cin>>c;\n switch(c) {\n case 1:\n cout<<\"Enter element to be inserted: \";\n cin>>v;\n cout<<\"Enter key at which element to be inserted: \";\n cin>>k;\n hash.Insert(k, v);\n break;\n case 2:\n cout<<\"Enter key of the element to be searched: \";\n cin>>k;\n if(hash.SearchKey(k) == -1) {\n cout<<\"No element found at key \"<<k<<endl;\n continue;\n } else {\n cout<<\"Element at key \"<<k<<\" : \";\n cout<<hash.SearchKey(k)<<endl;\n }\n break;\n case 3:\n cout<<\"Enter key of the element to be deleted: \";\n cin>>k;\n hash.Remove(k);\n break;\n case 4:\n exit(1);\n default:\n cout<<\"\\nEnter correct option\\n\";\n }\n }\n return 0;\n}" }, { "code": null, "e": 9404, "s": 7659, "text": "1.Insert element into the table\n2.Search element from the key\n3.Delete element at a key\n4.Exit\nEnter your choice: 1\nEnter element to be inserted: 10\nEnter key at which element to be inserted: 2\n1.Insert element into the table\n2.Search element from the key\n3.Delete element at a key\n4.Exit\nEnter your choice: 1\nEnter element to be inserted: 7\nEnter key at which element to be inserted: 6\n1.Insert element into the table\n2.Search element from the key\n3.Delete element at a key\n4.Exit\nEnter your choice: 1\nEnter element to be inserted: 4\nEnter key at which element to be inserted: 5\n1.Insert element into the table\n2.Search element from the key\n3.Delete element at a key\n4.Exit\nEnter your choice: 1\nEnter element to be inserted: 12\nEnter key at which element to be inserted: 3\n1.Insert element into the table\n2.Search element from the key\n3.Delete element at a key\n4.Exit\nEnter your choice: 15\nEnter correct option\n1.Insert element into the table\n2.Search element from the key\n3.Delete element at a key\n4.Exit\nEnter your choice: 1\nEnter element to be inserted: 15\nEnter key at which element to be inserted: 8\n1.Insert element into the table\n2.Search element from the key\n3.Delete element at a key\n4.Exit\nEnter your choice: 2\nEnter key of the element to be searched: 6\nElement at key 6 : 7\n1.Insert element into the table\n2.Search element from the key\n3.Delete element at a key\n4.Exit\nEnter your choice: 3\nEnter key of the element to be deleted: 2\n1.Insert element into the table\n2.Search element from the key\n3.Delete element at a key\n4.Exit\nEnter your choice: 2\nEnter key of the element to be searched: 2\nNo element found at key 2\n1.Insert element into the table\n2.Search element from the key\n3.Delete element at a key\n4.Exit\nEnter your choice: 4" } ]
compgen command in Linux with Examples
22 Jun, 2020 compgen is a bash built-in command which is used to list all the commands that could be executed in the Linux system. This command could also be used to count the total number of commands present in the terminal or even to look for a command with the specific keyword. This command is even used to print the bash details like bash builtin functions and stuff. 1. To list all commands available to be directly executed. compgen -c This will list all the commands available to you for direct use. 2. To search for commands having a specific keyword compgen -c | grep gnome This will search the commands having the keyword gnome in them. 3. To count total number of commands available for use compgen -c | wc -l This command will count the total number of commands that could be used. 4. To list all the bash alias compgen -a This command will list all the bash alias present in your system. 5. To list all the bash built-ins compgen -b This command will list all the bash built-ins present in your system. 6. To list all the bash keywords compgen -k This command will list all the bash keywords present in your system. 7. To list all the bash functions. compgen -A function This command will list all the bash functions present in your system. linux-command Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Docker - COPY Instruction scp command in Linux with Examples chown command in Linux with Examples SED command in Linux | Set 2 nohup Command in Linux with Examples mv command in Linux with examples chmod command in Linux with examples Array Basics in Shell Scripting | Set 1 Introduction to Linux Operating System Basic Operators in Shell Scripting
[ { "code": null, "e": 52, "s": 24, "text": "\n22 Jun, 2020" }, { "code": null, "e": 412, "s": 52, "text": "compgen is a bash built-in command which is used to list all the commands that could be executed in the Linux system. This command could also be used to count the total number of commands present in the terminal or even to look for a command with the specific keyword. This command is even used to print the bash details like bash builtin functions and stuff." }, { "code": null, "e": 471, "s": 412, "text": "1. To list all commands available to be directly executed." }, { "code": null, "e": 482, "s": 471, "text": "compgen -c" }, { "code": null, "e": 547, "s": 482, "text": "This will list all the commands available to you for direct use." }, { "code": null, "e": 599, "s": 547, "text": "2. To search for commands having a specific keyword" }, { "code": null, "e": 623, "s": 599, "text": "compgen -c | grep gnome" }, { "code": null, "e": 687, "s": 623, "text": "This will search the commands having the keyword gnome in them." }, { "code": null, "e": 742, "s": 687, "text": "3. To count total number of commands available for use" }, { "code": null, "e": 761, "s": 742, "text": "compgen -c | wc -l" }, { "code": null, "e": 834, "s": 761, "text": "This command will count the total number of commands that could be used." }, { "code": null, "e": 864, "s": 834, "text": "4. To list all the bash alias" }, { "code": null, "e": 875, "s": 864, "text": "compgen -a" }, { "code": null, "e": 941, "s": 875, "text": "This command will list all the bash alias present in your system." }, { "code": null, "e": 975, "s": 941, "text": "5. To list all the bash built-ins" }, { "code": null, "e": 986, "s": 975, "text": "compgen -b" }, { "code": null, "e": 1056, "s": 986, "text": "This command will list all the bash built-ins present in your system." }, { "code": null, "e": 1089, "s": 1056, "text": "6. To list all the bash keywords" }, { "code": null, "e": 1100, "s": 1089, "text": "compgen -k" }, { "code": null, "e": 1169, "s": 1100, "text": "This command will list all the bash keywords present in your system." }, { "code": null, "e": 1204, "s": 1169, "text": "7. To list all the bash functions." }, { "code": null, "e": 1224, "s": 1204, "text": "compgen -A function" }, { "code": null, "e": 1294, "s": 1224, "text": "This command will list all the bash functions present in your system." }, { "code": null, "e": 1308, "s": 1294, "text": "linux-command" }, { "code": null, "e": 1319, "s": 1308, "text": "Linux-Unix" }, { "code": null, "e": 1417, "s": 1319, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1443, "s": 1417, "text": "Docker - COPY Instruction" }, { "code": null, "e": 1478, "s": 1443, "text": "scp command in Linux with Examples" }, { "code": null, "e": 1515, "s": 1478, "text": "chown command in Linux with Examples" }, { "code": null, "e": 1544, "s": 1515, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 1581, "s": 1544, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 1615, "s": 1581, "text": "mv command in Linux with examples" }, { "code": null, "e": 1652, "s": 1615, "text": "chmod command in Linux with examples" }, { "code": null, "e": 1692, "s": 1652, "text": "Array Basics in Shell Scripting | Set 1" }, { "code": null, "e": 1731, "s": 1692, "text": "Introduction to Linux Operating System" } ]
Python – Find Index containing String in List
04 Jul, 2022 Given a list, the task is to write a Python Program to find the Index containing String. Example: Input: [‘sravan’, 98, ‘harsha’, ‘jyothika’, ‘deepika’, 78, 90, ‘ramya’] Output: 0 2 3 4 7 Explanation: Index 0 2 3 4 7 contains only string. By using type() operator we can get the string elements indexes from the list, string elements will come under str() type, so we iterate through the entire list with for loop and return the index which is of type string. Python3 # create a list of names and markslist1 = ['sravan', 98, 'harsha', 'jyothika', 'deepika', 78, 90, 'ramya'] # displaylist1 # iterate through list of elementsfor i in list1: # check for type is str if(type(i) is str): # display index print(list1.index(i)) Output: 0 2 3 4 7 By using list comprehension we can get indices of string elements. Syntax: [list.index(iterator) for iterator in list if(type(iterator) is str)] Python3 # create a list of names and markslist1 = ['sravan', 98, 'harsha', 'jyothika', 'deepika', 78, 90, 'ramya'] # displaylist1 # list comprehensionprint([list1.index(i) for i in list1 if(type(i) is str)]) # list comprehension display stringsprint([i for i in list1 if(type(i) is str)]) Output: [0, 2, 3, 4, 7] ['sravan', 'harsha', 'jyothika', 'deepika', 'ramya'] Python3 # create a list of names and markslist1 = ['sravan', 98, 'harsha', 'jyothika', 'deepika', 78, 90, 'ramya'] # displayprint(list1) list2=[] # iterate through list of elementsfor i in list1: # check for type is str if(isinstance(i,str)): # display index list2.append(list1.index(i))print(list2) ['sravan', 98, 'harsha', 'jyothika', 'deepika', 78, 90, 'ramya'] [0, 2, 3, 4, 7] sagar0719kumar kogantibhavya Picked Python list-programs python-list Python Python Programs python-list Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n04 Jul, 2022" }, { "code": null, "e": 142, "s": 53, "text": "Given a list, the task is to write a Python Program to find the Index containing String." }, { "code": null, "e": 151, "s": 142, "text": "Example:" }, { "code": null, "e": 223, "s": 151, "text": "Input: [‘sravan’, 98, ‘harsha’, ‘jyothika’, ‘deepika’, 78, 90, ‘ramya’]" }, { "code": null, "e": 241, "s": 223, "text": "Output: 0 2 3 4 7" }, { "code": null, "e": 292, "s": 241, "text": "Explanation: Index 0 2 3 4 7 contains only string." }, { "code": null, "e": 513, "s": 292, "text": "By using type() operator we can get the string elements indexes from the list, string elements will come under str() type, so we iterate through the entire list with for loop and return the index which is of type string." }, { "code": null, "e": 521, "s": 513, "text": "Python3" }, { "code": "# create a list of names and markslist1 = ['sravan', 98, 'harsha', 'jyothika', 'deepika', 78, 90, 'ramya'] # displaylist1 # iterate through list of elementsfor i in list1: # check for type is str if(type(i) is str): # display index print(list1.index(i))", "e": 813, "s": 521, "text": null }, { "code": null, "e": 821, "s": 813, "text": "Output:" }, { "code": null, "e": 831, "s": 821, "text": "0\n2\n3\n4\n7" }, { "code": null, "e": 898, "s": 831, "text": "By using list comprehension we can get indices of string elements." }, { "code": null, "e": 976, "s": 898, "text": "Syntax: [list.index(iterator) for iterator in list if(type(iterator) is str)]" }, { "code": null, "e": 984, "s": 976, "text": "Python3" }, { "code": "# create a list of names and markslist1 = ['sravan', 98, 'harsha', 'jyothika', 'deepika', 78, 90, 'ramya'] # displaylist1 # list comprehensionprint([list1.index(i) for i in list1 if(type(i) is str)]) # list comprehension display stringsprint([i for i in list1 if(type(i) is str)])", "e": 1273, "s": 984, "text": null }, { "code": null, "e": 1281, "s": 1273, "text": "Output:" }, { "code": null, "e": 1350, "s": 1281, "text": "[0, 2, 3, 4, 7]\n['sravan', 'harsha', 'jyothika', 'deepika', 'ramya']" }, { "code": null, "e": 1358, "s": 1350, "text": "Python3" }, { "code": "# create a list of names and markslist1 = ['sravan', 98, 'harsha', 'jyothika', 'deepika', 78, 90, 'ramya'] # displayprint(list1) list2=[] # iterate through list of elementsfor i in list1: # check for type is str if(isinstance(i,str)): # display index list2.append(list1.index(i))print(list2)", "e": 1677, "s": 1358, "text": null }, { "code": null, "e": 1758, "s": 1677, "text": "['sravan', 98, 'harsha', 'jyothika', 'deepika', 78, 90, 'ramya']\n[0, 2, 3, 4, 7]" }, { "code": null, "e": 1773, "s": 1758, "text": "sagar0719kumar" }, { "code": null, "e": 1787, "s": 1773, "text": "kogantibhavya" }, { "code": null, "e": 1794, "s": 1787, "text": "Picked" }, { "code": null, "e": 1815, "s": 1794, "text": "Python list-programs" }, { "code": null, "e": 1827, "s": 1815, "text": "python-list" }, { "code": null, "e": 1834, "s": 1827, "text": "Python" }, { "code": null, "e": 1850, "s": 1834, "text": "Python Programs" }, { "code": null, "e": 1862, "s": 1850, "text": "python-list" } ]
C# | Byte.CompareTo(Byte) Method
07 Dec, 2021 This method is used to compare this instance to a specified 8-bit unsigned integer and returns an indication of their relative values.Syntax: public int CompareTo (byte value); Here, the value is an 8-bit unsigned integer to compare.Return Value: This method returns a signed integer that indicates the relative order of this instance and value. Less than zero: This instance is less than value. Zero: This instance is equal to value. Greater than zero: This instance is greater than value. Below programs illustrate the use of Byte.CompareTo(Byte) Method:Example 1: CSHARP // C# program to demonstrate// Byte.CompareTo(byte)// Methodusing System; class GFG { // Main Method public static void Main() { // Declaring val1 and val2 byte val1, val2; // initializing the val1, // val2 and val3 val1 = 12; val2 = 13; // getting compared constant // using CompareTo method int i = val2.CompareTo(val1); // checking the condition if (i > 0) Console.Write("val2 is greater than val1"); else if (i < 0) Console.Write("val2 is less than val1"); else Console.Write("val1 is equal to val1"); }} val2 is greater than val1 Example 2: CSHARP // C# program to demonstrate// Byte.CompareTo(byte)// Methodusing System; class GFG { // Main Method public static void Main() { // checking the condition // calling check() method check((byte)10, (byte)20); check((byte)30, (byte)20); check((byte)10, (byte)10); check((byte)5, (byte)7); check((byte)40, (byte)50); check((byte)1, (byte)2); } // Defining the check method public static void check(byte v1, byte v2) { // getting compared constant // using CompareTo() method int i = v1.CompareTo(v2); // checking the condition if (i > 0) Console.WriteLine(v1 + " is greater than " + v2); else if (i < 0) Console.WriteLine(v1 + " is less than " + v2); else Console.WriteLine(v1 + " is equal to " + v2); }} 10 is less than 20 30 is greater than 20 10 is equal to 10 5 is less than 7 40 is less than 50 1 is less than 2 Reference: https://docs.microsoft.com/en-us/dotnet/api/system.byte.compareto?view=netframework-4.7.2#System_Byte_CompareTo_System_Byte_ simranarora5sos CSharp-Byte-Struct CSharp-method C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n07 Dec, 2021" }, { "code": null, "e": 170, "s": 28, "text": "This method is used to compare this instance to a specified 8-bit unsigned integer and returns an indication of their relative values.Syntax:" }, { "code": null, "e": 205, "s": 170, "text": "public int CompareTo (byte value);" }, { "code": null, "e": 375, "s": 205, "text": "Here, the value is an 8-bit unsigned integer to compare.Return Value: This method returns a signed integer that indicates the relative order of this instance and value. " }, { "code": null, "e": 425, "s": 375, "text": "Less than zero: This instance is less than value." }, { "code": null, "e": 464, "s": 425, "text": "Zero: This instance is equal to value." }, { "code": null, "e": 520, "s": 464, "text": "Greater than zero: This instance is greater than value." }, { "code": null, "e": 596, "s": 520, "text": "Below programs illustrate the use of Byte.CompareTo(Byte) Method:Example 1:" }, { "code": null, "e": 603, "s": 596, "text": "CSHARP" }, { "code": "// C# program to demonstrate// Byte.CompareTo(byte)// Methodusing System; class GFG { // Main Method public static void Main() { // Declaring val1 and val2 byte val1, val2; // initializing the val1, // val2 and val3 val1 = 12; val2 = 13; // getting compared constant // using CompareTo method int i = val2.CompareTo(val1); // checking the condition if (i > 0) Console.Write(\"val2 is greater than val1\"); else if (i < 0) Console.Write(\"val2 is less than val1\"); else Console.Write(\"val1 is equal to val1\"); }}", "e": 1255, "s": 603, "text": null }, { "code": null, "e": 1281, "s": 1255, "text": "val2 is greater than val1" }, { "code": null, "e": 1294, "s": 1283, "text": "Example 2:" }, { "code": null, "e": 1301, "s": 1294, "text": "CSHARP" }, { "code": "// C# program to demonstrate// Byte.CompareTo(byte)// Methodusing System; class GFG { // Main Method public static void Main() { // checking the condition // calling check() method check((byte)10, (byte)20); check((byte)30, (byte)20); check((byte)10, (byte)10); check((byte)5, (byte)7); check((byte)40, (byte)50); check((byte)1, (byte)2); } // Defining the check method public static void check(byte v1, byte v2) { // getting compared constant // using CompareTo() method int i = v1.CompareTo(v2); // checking the condition if (i > 0) Console.WriteLine(v1 + \" is greater than \" + v2); else if (i < 0) Console.WriteLine(v1 + \" is less than \" + v2); else Console.WriteLine(v1 + \" is equal to \" + v2); }}", "e": 2172, "s": 1301, "text": null }, { "code": null, "e": 2284, "s": 2172, "text": "10 is less than 20\n30 is greater than 20\n10 is equal to 10\n5 is less than 7\n40 is less than 50\n1 is less than 2" }, { "code": null, "e": 2298, "s": 2286, "text": "Reference: " }, { "code": null, "e": 2423, "s": 2298, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.byte.compareto?view=netframework-4.7.2#System_Byte_CompareTo_System_Byte_" }, { "code": null, "e": 2439, "s": 2423, "text": "simranarora5sos" }, { "code": null, "e": 2458, "s": 2439, "text": "CSharp-Byte-Struct" }, { "code": null, "e": 2472, "s": 2458, "text": "CSharp-method" }, { "code": null, "e": 2475, "s": 2472, "text": "C#" } ]
Simple and fast Question Answering system using HuggingFace DistilBERT — single & batch inference examples provided. | by Ramsri Goutham | Towards Data Science
Question Answering systems have many use cases like automatically responding to a customer’s query by reading through the company’s documents and finding a perfect answer. In this blog post, we will see how we can implement a state-of-the-art, super-fast, and lightweight question answering system using DistilBERT from Huggingface transformers library. The input will be a short paragraph what we call context, and a question - Context :The US has passed the peak on new coronavirus cases, President Donald Trump said and predicted that some states would reopen this month.The US has over 637,000 confirmed Covid-19 cases and over 30,826 deaths, the highest for any country in the world.Question:What was President Donald Trump's prediction? The output from our question-answering system will be an answer from the context paragraph as shown below — Answer: some states would reopen this month. First, let’s see how we can answer a single question as shown above. Then we will see how we can leverage batch processing to answer multiple questions at once from the context. Install the latest version of the transformers library - pip install transformers==2.8.0pip install torch==1.4.0 Single Inference : Here is the code to do single inference with DistilBERT: The output will be : Question What was President Donald Trump's prediction?Answer Tokens:['some', 'states', 'would', 're', '##open', 'this', 'month']Answer : some states would reopen this month Now let’s try to do the same with batch inference where we try to pass three questions and get answers for them as a batch - Three questions are - 1. What was President Donald Trump's prediction?2. How many deaths have been reported from the virus?3. How many cases have been reported in the United States? Here is the code to do batch inference with DistilBERT : The output will be — Context : The US has passed the peak on new coronavirus cases, President Donald Trump said and predicted that some states would reopen this month.The US has over 637,000 confirmed Covid-19 cases and over 30,826 deaths, the highest for any country in the world.Question: What was President Donald Trump's prediction?Answer: some states would reopen this monthQuestion: How many deaths have been reported from the virus?Answer: 30 , 826Question: How many cases have been reported in the United States?Answer: over 637 , 000 If you are interested in automatic question generation from context rather than question answering, you can check out my various algorithms and open-sourced code in the links below - True or False Question GenerationMultiple Choice Question GenerationGenerate pronoun questions for English language learningGrammar MCQ generation True or False Question Generation Multiple Choice Question Generation Generate pronoun questions for English language learning Grammar MCQ generation Happy coding! I launched a very interesting Udemy course titled “Question generation using NLP” expanding on some of the techniques discussed in this blog post. If you would like to take a look at it, here is the link.
[ { "code": null, "e": 343, "s": 171, "text": "Question Answering systems have many use cases like automatically responding to a customer’s query by reading through the company’s documents and finding a perfect answer." }, { "code": null, "e": 525, "s": 343, "text": "In this blog post, we will see how we can implement a state-of-the-art, super-fast, and lightweight question answering system using DistilBERT from Huggingface transformers library." }, { "code": null, "e": 600, "s": 525, "text": "The input will be a short paragraph what we call context, and a question -" }, { "code": null, "e": 914, "s": 600, "text": "Context :The US has passed the peak on new coronavirus cases, President Donald Trump said and predicted that some states would reopen this month.The US has over 637,000 confirmed Covid-19 cases and over 30,826 deaths, the highest for any country in the world.Question:What was President Donald Trump's prediction?" }, { "code": null, "e": 1022, "s": 914, "text": "The output from our question-answering system will be an answer from the context paragraph as shown below —" }, { "code": null, "e": 1067, "s": 1022, "text": "Answer: some states would reopen this month." }, { "code": null, "e": 1245, "s": 1067, "text": "First, let’s see how we can answer a single question as shown above. Then we will see how we can leverage batch processing to answer multiple questions at once from the context." }, { "code": null, "e": 1302, "s": 1245, "text": "Install the latest version of the transformers library -" }, { "code": null, "e": 1358, "s": 1302, "text": "pip install transformers==2.8.0pip install torch==1.4.0" }, { "code": null, "e": 1377, "s": 1358, "text": "Single Inference :" }, { "code": null, "e": 1434, "s": 1377, "text": "Here is the code to do single inference with DistilBERT:" }, { "code": null, "e": 1455, "s": 1434, "text": "The output will be :" }, { "code": null, "e": 1630, "s": 1455, "text": "Question What was President Donald Trump's prediction?Answer Tokens:['some', 'states', 'would', 're', '##open', 'this', 'month']Answer : some states would reopen this month" }, { "code": null, "e": 1755, "s": 1630, "text": "Now let’s try to do the same with batch inference where we try to pass three questions and get answers for them as a batch -" }, { "code": null, "e": 1777, "s": 1755, "text": "Three questions are -" }, { "code": null, "e": 1937, "s": 1777, "text": "1. What was President Donald Trump's prediction?2. How many deaths have been reported from the virus?3. How many cases have been reported in the United States?" }, { "code": null, "e": 1994, "s": 1937, "text": "Here is the code to do batch inference with DistilBERT :" }, { "code": null, "e": 2015, "s": 1994, "text": "The output will be —" }, { "code": null, "e": 2544, "s": 2015, "text": "Context : The US has passed the peak on new coronavirus cases, President Donald Trump said and predicted that some states would reopen this month.The US has over 637,000 confirmed Covid-19 cases and over 30,826 deaths, the highest for any country in the world.Question: What was President Donald Trump's prediction?Answer: some states would reopen this monthQuestion: How many deaths have been reported from the virus?Answer: 30 , 826Question: How many cases have been reported in the United States?Answer: over 637 , 000" }, { "code": null, "e": 2727, "s": 2544, "text": "If you are interested in automatic question generation from context rather than question answering, you can check out my various algorithms and open-sourced code in the links below -" }, { "code": null, "e": 2874, "s": 2727, "text": "True or False Question GenerationMultiple Choice Question GenerationGenerate pronoun questions for English language learningGrammar MCQ generation" }, { "code": null, "e": 2908, "s": 2874, "text": "True or False Question Generation" }, { "code": null, "e": 2944, "s": 2908, "text": "Multiple Choice Question Generation" }, { "code": null, "e": 3001, "s": 2944, "text": "Generate pronoun questions for English language learning" }, { "code": null, "e": 3024, "s": 3001, "text": "Grammar MCQ generation" }, { "code": null, "e": 3038, "s": 3024, "text": "Happy coding!" } ]
Tryit Editor v3.7 - Show Java
static void Main() { // Full name string name = "John Doe"; // Location of the letter D int charPos = name.IndexOf("D"); // Get last name string lastName = name.Substring(charPos); // Print the result
[]
React useContext Hook
React Context is a way to manage state globally. It can be used together with the useState Hook to share state between deeply nested components more easily than with useState alone. State should be held by the highest parent component in the stack that requires access to the state. To illustrate, we have many nested components. The component at the top and bottom of the stack need access to the state. To do this without Context, we will need to pass the state as "props" through each nested component. This is called "prop drilling". Passing "props" through nested components: import { useState } from "react"; import ReactDOM from "react-dom/client"; function Component1() { const [user, setUser] = useState("Jesse Hall"); return ( <> <h1>{`Hello ${user}!`}</h1> <Component2 user={user} /> </> ); } function Component2({ user }) { return ( <> <h1>Component 2</h1> <Component3 user={user} /> </> ); } function Component3({ user }) { return ( <> <h1>Component 3</h1> <Component4 user={user} /> </> ); } function Component4({ user }) { return ( <> <h1>Component 4</h1> <Component5 user={user} /> </> ); } function Component5({ user }) { return ( <> <h1>Component 5</h1> <h2>{`Hello ${user} again!`}</h2> </> ); } const root = ReactDOM.createRoot(document.getElementById('root')); root.render(<Component1 />); Run Example » Even though components 2-4 did not need the state, they had to pass the state along so that it could reach component 5. The solution is to create context. To create context, you must Import createContext and initialize it: import { useState, createContext } from "react"; import ReactDOM from "react-dom/client"; const UserContext = createContext() Next we'll use the Context Provider to wrap the tree of components that need the state Context. Wrap child components in the Context Provider and supply the state value. function Component1() { const [user, setUser] = useState("Jesse Hall"); return ( <UserContext.Provider value={user}> <h1>{`Hello ${user}!`}</h1> <Component2 user={user} /> </UserContext.Provider> ); } Now, all components in this tree will have access to the user Context. In order to use the Context in a child component, we need to access it using the useContext Hook. First, include the useContext in the import statement: import { useState, createContext, useContext } from "react"; Then you can access the user Context in all components: function Component5() { const user = useContext(UserContext); return ( <> <h1>Component 5</h1> <h2>{`Hello ${user} again!`}</h2> </> ); } Here is the full example using React Context: import { useState, createContext, useContext } from "react"; import ReactDOM from "react-dom/client"; const UserContext = createContext(); function Component1() { const [user, setUser] = useState("Jesse Hall"); return ( <UserContext.Provider value={user}> <h1>{`Hello ${user}!`}</h1> <Component2 user={user} /> </UserContext.Provider> ); } function Component2() { return ( <> <h1>Component 2</h1> <Component3 /> </> ); } function Component3() { return ( <> <h1>Component 3</h1> <Component4 /> </> ); } function Component4() { return ( <> <h1>Component 4</h1> <Component5 /> </> ); } function Component5() { const user = useContext(UserContext); return ( <> <h1>Component 5</h1> <h2>{`Hello ${user} again!`}</h2> </> ); } const root = ReactDOM.createRoot(document.getElementById('root')); root.render(<Component1 />); Run Example » We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: [email protected] Your message has been sent to W3Schools.
[ { "code": null, "e": 49, "s": 0, "text": "React Context is a way to manage state globally." }, { "code": null, "e": 182, "s": 49, "text": "It can be used together with the useState Hook to share state between\ndeeply nested components more easily than with useState alone." }, { "code": null, "e": 283, "s": 182, "text": "State should be held by the highest parent component in the stack that requires access to the state." }, { "code": null, "e": 405, "s": 283, "text": "To illustrate, we have many nested components. The component at the top and bottom of the stack need access to the state." }, { "code": null, "e": 538, "s": 405, "text": "To do this without Context, we will need to pass the state as \"props\" through each nested component. This is called \"prop drilling\"." }, { "code": null, "e": 581, "s": 538, "text": "Passing \"props\" through nested components:" }, { "code": null, "e": 1441, "s": 581, "text": "import { useState } from \"react\";\nimport ReactDOM from \"react-dom/client\";\n\nfunction Component1() {\n const [user, setUser] = useState(\"Jesse Hall\");\n\n return (\n <>\n <h1>{`Hello ${user}!`}</h1>\n <Component2 user={user} />\n </>\n );\n}\n\nfunction Component2({ user }) {\n return (\n <>\n <h1>Component 2</h1>\n <Component3 user={user} />\n </>\n );\n}\n\nfunction Component3({ user }) {\n return (\n <>\n <h1>Component 3</h1>\n <Component4 user={user} />\n </>\n );\n}\n\nfunction Component4({ user }) {\n return (\n <>\n <h1>Component 4</h1>\n <Component5 user={user} />\n </>\n );\n}\n\nfunction Component5({ user }) {\n return (\n <>\n <h1>Component 5</h1>\n <h2>{`Hello ${user} again!`}</h2>\n </>\n );\n}\n\nconst root = ReactDOM.createRoot(document.getElementById('root'));\nroot.render(<Component1 />);\n" }, { "code": null, "e": 1458, "s": 1441, "text": "\nRun \nExample »\n" }, { "code": null, "e": 1578, "s": 1458, "text": "Even though components 2-4 did not need the state, they had to pass the state along so that it could reach component 5." }, { "code": null, "e": 1613, "s": 1578, "text": "The solution is to create context." }, { "code": null, "e": 1682, "s": 1613, "text": "To create context, you must Import createContext and initialize \nit:" }, { "code": null, "e": 1810, "s": 1682, "text": "import { useState, createContext } from \"react\";\nimport ReactDOM from \"react-dom/client\";\n\nconst UserContext = createContext()\n" }, { "code": null, "e": 1906, "s": 1810, "text": "Next we'll use the Context Provider to wrap the tree of components that need the state Context." }, { "code": null, "e": 1980, "s": 1906, "text": "Wrap child components in the Context Provider and supply the state value." }, { "code": null, "e": 2208, "s": 1980, "text": "function Component1() {\n const [user, setUser] = useState(\"Jesse Hall\");\n\n return (\n <UserContext.Provider value={user}>\n <h1>{`Hello ${user}!`}</h1>\n <Component2 user={user} />\n </UserContext.Provider>\n );\n}" }, { "code": null, "e": 2279, "s": 2208, "text": "Now, all components in this tree will have access to the user Context." }, { "code": null, "e": 2377, "s": 2279, "text": "In order to use the Context in a child component, we need to access it using the useContext Hook." }, { "code": null, "e": 2433, "s": 2377, "text": "First, include the useContext in the import \nstatement:" }, { "code": null, "e": 2495, "s": 2433, "text": "import { useState, createContext, useContext } from \"react\";\n" }, { "code": null, "e": 2551, "s": 2495, "text": "Then you can access the user Context in all components:" }, { "code": null, "e": 2717, "s": 2551, "text": "function Component5() {\n const user = useContext(UserContext);\n\n return (\n <>\n <h1>Component 5</h1>\n <h2>{`Hello ${user} again!`}</h2>\n </>\n );\n}\n" }, { "code": null, "e": 2763, "s": 2717, "text": "Here is the full example using React Context:" }, { "code": null, "e": 3713, "s": 2763, "text": "import { useState, createContext, useContext } from \"react\";\nimport ReactDOM from \"react-dom/client\";\n\nconst UserContext = createContext();\n\nfunction Component1() {\n const [user, setUser] = useState(\"Jesse Hall\");\n\n return (\n <UserContext.Provider value={user}>\n <h1>{`Hello ${user}!`}</h1>\n <Component2 user={user} />\n </UserContext.Provider>\n );\n}\n\nfunction Component2() {\n return (\n <>\n <h1>Component 2</h1>\n <Component3 />\n </>\n );\n}\n\nfunction Component3() {\n return (\n <>\n <h1>Component 3</h1>\n <Component4 />\n </>\n );\n}\n\nfunction Component4() {\n return (\n <>\n <h1>Component 4</h1>\n <Component5 />\n </>\n );\n}\n\nfunction Component5() {\n const user = useContext(UserContext);\n\n return (\n <>\n <h1>Component 5</h1>\n <h2>{`Hello ${user} again!`}</h2>\n </>\n );\n}\n\nconst root = ReactDOM.createRoot(document.getElementById('root'));\nroot.render(<Component1 />);" }, { "code": null, "e": 3730, "s": 3713, "text": "\nRun \nExample »\n" }, { "code": null, "e": 3763, "s": 3730, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 3805, "s": 3763, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 3912, "s": 3805, "text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:" }, { "code": null, "e": 3931, "s": 3912, "text": "[email protected]" } ]
IsNullOrEmpty() Method in C#
The IsNullOrEmpty() method in C# is used to indicate whether the specified string is null or an empty string (""). The syntax is as follows− public static bool IsNullOrEmpty (string val); Above, the value val is the string to test. Let us now see an example − Live Demo using System; public class Demo { public static void Main(){ string str1 = "Amit"; string str2 = " "; Console.WriteLine("Is string1 null or empty? = "+string.IsNullOrEmpty(str1)); Console.WriteLine("Is string2 null or empty? = "+string.IsNullOrEmpty(str2)); } } This will produce the following output − Is string1 null or empty? = False Is string2 null or empty? = False Let us now see another example − Live Demo using System; public class Demo { public static void Main(){ string str1 = null; string str2 = String.Empty; Console.WriteLine("Is string1 null or empty? = "+string.IsNullOrEmpty(str1)); Console.WriteLine("Is string2 null or empty? = "+string.IsNullOrEmpty(str2)); } } This will produce the following output − Is string1 null or empty? = True Is string2 null or empty? = True
[ { "code": null, "e": 1177, "s": 1062, "text": "The IsNullOrEmpty() method in C# is used to indicate whether the specified string is null or an empty string (\"\")." }, { "code": null, "e": 1203, "s": 1177, "text": "The syntax is as follows−" }, { "code": null, "e": 1250, "s": 1203, "text": "public static bool IsNullOrEmpty (string val);" }, { "code": null, "e": 1294, "s": 1250, "text": "Above, the value val is the string to test." }, { "code": null, "e": 1322, "s": 1294, "text": "Let us now see an example −" }, { "code": null, "e": 1333, "s": 1322, "text": " Live Demo" }, { "code": null, "e": 1625, "s": 1333, "text": "using System;\npublic class Demo {\n public static void Main(){\n string str1 = \"Amit\";\n string str2 = \" \";\n Console.WriteLine(\"Is string1 null or empty? = \"+string.IsNullOrEmpty(str1));\n Console.WriteLine(\"Is string2 null or empty? = \"+string.IsNullOrEmpty(str2));\n }\n}" }, { "code": null, "e": 1666, "s": 1625, "text": "This will produce the following output −" }, { "code": null, "e": 1734, "s": 1666, "text": "Is string1 null or empty? = False\nIs string2 null or empty? = False" }, { "code": null, "e": 1767, "s": 1734, "text": "Let us now see another example −" }, { "code": null, "e": 1778, "s": 1767, "text": " Live Demo" }, { "code": null, "e": 2077, "s": 1778, "text": "using System;\npublic class Demo {\n public static void Main(){\n string str1 = null;\n string str2 = String.Empty;\n Console.WriteLine(\"Is string1 null or empty? = \"+string.IsNullOrEmpty(str1));\n Console.WriteLine(\"Is string2 null or empty? = \"+string.IsNullOrEmpty(str2));\n }\n}" }, { "code": null, "e": 2118, "s": 2077, "text": "This will produce the following output −" }, { "code": null, "e": 2184, "s": 2118, "text": "Is string1 null or empty? = True\nIs string2 null or empty? = True" } ]
Shop in Candy Store | Practice | GeeksforGeeks
In a candy store, there are N different types of candies available and the prices of all the N different types of candies are provided to you. You are now provided with an attractive offer. You can buy a single candy from the store and get at most K other candies ( all are different types ) for free. Now you have to answer two questions. Firstly, you have to find what is the minimum amount of money you have to spend to buy all the N different candies. Secondly, you have to find what is the maximum amount of money you have to spend to buy all the N different candies. In both the cases you must utilize the offer i.e. you buy one candy and get K other candies for free. Example 1: Input: N = 4 K = 2 candies[] = {3 2 1 4} Output: 3 7 Explanation: As according to the offer if you buy one candy you can take at most two more for free. So in the first case, you buy the candy which costs 1 and takes candies worth 3 and 4 for free, also you buy candy worth 2 as well. So min cost : 1+2 =3. In the second case, you can buy the candy which costs 4 and takes candies worth 1 and 2 for free, also you need to buy candy worth 3 as well. So max cost : 3+4 =7. Example 2: Input: N = 5 K = 4 candies[] = {3 2 1 4 5} Output: 1 5 Explanation: For minimimum cost buy the candy with the cost 1 and get all the other candies for free. For maximum cost buy the candy with the cost 5 and get all other candies for free. Your Task: You don't need to read input or print anything. Your task is to complete the function candyStore() which takes the array candies[], its size N and an integer K as input parameters and returns the minimum amount and maximum amount of money to buy all candies according to the offer. Expected Time Complexity: O(NLogN) Expected Auxiliary Space: O(1) Constraints: 1 <= N <= 100000 0 <= K <= N-1 1 <= candies[i] <= 10000 0 vikingwarriorin 11 hours Python Code: def candyStore(self,candies,N,K): candies = sorted(candies) countOfPurchase = (N//(K+1)) if N % (K+1) != 0: countOfPurchase += 1 return sum(candies[:countOfPurchase]), sum(candies[-countOfPurchase:]) 0 vikingwarrior This comment was deleted. 0 chiyan sethuin 7 hours import math class Solution: def candyStore(self, candies, n, k): candies.sort() cnt = math.ceil(n / (k + 1)) return sum(candies[:cnt]), sum(candies[-cnt:]) 0 sikkusaurav12315 hours ago public: vector<int> candyStore(int candies[], int N, int K) { // Write Your Code here sort(candies,candies+N); int dif_can=0; int price=0; vector<int>v; for(int i=0;i<N;i++) { price=price+candies[i]; dif_can=dif_can+K+1; if(dif_can>=N) { v.push_back(price); break; } } reverse(candies,candies+N); dif_can=0; price=0; for(int i=0;i<N;i++) { price=price+candies[i]; dif_can=dif_can+K+1; if(dif_can>=N) { v.push_back(price); break; } } return v; } 0 subrotomukherjee816 hours ago def candyStore(self, a,n,k): # code here mn,mx=0,0 a.sort() val=n//(k+1) if n%(k+1)!=0: val+=1 for i in range(0,n): if i<val: mn+=a[i] a=a[::-1] for i in range(n): if i<val: mx+=a[i] return mn,mx 0 45mzzbhoest5k5060ff1se8zbxbntzof9sjy5d1e19 hours ago class Solution{public: vector<int> candyStore(int candies[], int N, int K) { // Write Your Code here int mincost=0,maxcost=0; int mx=N-1, mi=0; sort(candies,candies+N); for(int i=0,j=N-1;i<=mx && j>=mi;i++,j--){ mincost+=candies[i]; maxcost+=candies[j]; mx -=K; mi +=K; } return {mincost,maxcost}; }}; +1 gourangp2923 hours ago vector<int> candyStore(int candies[], int N, int K) { // Write Your Code here int minamt=0; int maxamt=0; sort(candies,candies+N); int x=0; for(int i=0; i<N-x; i++) { minamt+=candies[i]; x = x+K; } int y=0; for(int i=N-1; i>=y; i--) { maxamt+=candies[i]; y = y+K; } return {minamt,maxamt}; } 0 praveenkumar122 days ago May be it's a good approach. But Looking for more optimal! public: vector<int> candyStore(int candies[], int N, int K) { // Write Your Code here vector<int>ret; sort(candies,candies+N); int remains = N-1; int i=0; int min=0; while(i<=remains){ min+=candies[i]; remains-=K; i++; } ret.push_back(min); reverse(candies,candies+N); remains = N-1; int j=0; int max=0; while(j<=remains){ max+=candies[j]; remains-=K; j++; } ret.push_back(max); return ret; } +1 yashchawla1162 days ago Simple To Understand And Easy To Implement. https://yashboss116.blogspot.com/2022/04/shop-in-candy-store-geeks-for-geeks.html Approaches Explained And Complexities Mentioned. 0 jaishp32 days ago vector<int> candyStore(int candies[], int N, int K) { // Write Your Code here sort(candies,candies+N); int t1=0,t2=0,i=0,min=0,max=0; while(N>t1){ min+=candies[i]; i++; t1+=(K+1); } i=N-1; while(N>t2){ max+=candies[i]; i--; t2+=(K+1); } return{min,max}; } 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": 913, "s": 238, "text": "In a candy store, there are N different types of candies available and the prices of all the N different types of candies are provided to you.\nYou are now provided with an attractive offer.\nYou can buy a single candy from the store and get at most K other candies ( all are different types ) for free.\nNow you have to answer two questions. Firstly, you have to find what is the minimum amount of money you have to spend to buy all the N different candies. Secondly, you have to find what is the maximum amount of money you have to spend to buy all the N different candies.\nIn both the cases you must utilize the offer i.e. you buy one candy and get K other candies for free." }, { "code": null, "e": 924, "s": 913, "text": "Example 1:" }, { "code": null, "e": 1406, "s": 924, "text": "Input:\nN = 4\nK = 2\ncandies[] = {3 2 1 4}\n\nOutput:\n3 7\n\nExplanation:\nAs according to the offer if you buy \none candy you can take at most two \nmore for free. So in the first case, \nyou buy the candy which costs 1 and \ntakes candies worth 3 and 4 for free, \nalso you buy candy worth 2 as well.\nSo min cost : 1+2 =3.\nIn the second case, you can buy the \ncandy which costs 4 and takes candies \nworth 1 and 2 for free, also you need \nto buy candy worth 3 as well. \nSo max cost : 3+4 =7." }, { "code": null, "e": 1417, "s": 1406, "text": "Example 2:" }, { "code": null, "e": 1662, "s": 1417, "text": "Input: \nN = 5\nK = 4\ncandies[] = {3 2 1 4 5}\n\nOutput: \n1 5\n\nExplanation:\nFor minimimum cost buy the candy with\nthe cost 1 and get all the other candies\nfor free.\nFor maximum cost buy the candy with\nthe cost 5 and get all other candies\nfor free.\n" }, { "code": null, "e": 2024, "s": 1662, "text": "Your Task: \nYou don't need to read input or print anything. Your task is to complete the function candyStore() which takes the array candies[], its size N and an integer K as input parameters and returns the minimum amount and maximum amount of money to buy all candies according to the offer.\n\nExpected Time Complexity: O(NLogN)\nExpected Auxiliary Space: O(1)" }, { "code": null, "e": 2095, "s": 2024, "text": "\nConstraints:\n1 <= N <= 100000\n 0 <= K <= N-1\n1 <= candies[i] <= 10000" }, { "code": null, "e": 2097, "s": 2095, "text": "0" }, { "code": null, "e": 2122, "s": 2097, "text": "vikingwarriorin 11 hours" }, { "code": null, "e": 2135, "s": 2122, "text": "Python Code:" }, { "code": null, "e": 2411, "s": 2137, "text": "def candyStore(self,candies,N,K):\n \n candies = sorted(candies)\n countOfPurchase = (N//(K+1))\n if N % (K+1) != 0:\n countOfPurchase += 1\n \n \n return sum(candies[:countOfPurchase]), sum(candies[-countOfPurchase:])" }, { "code": null, "e": 2413, "s": 2411, "text": "0" }, { "code": null, "e": 2427, "s": 2413, "text": "vikingwarrior" }, { "code": null, "e": 2453, "s": 2427, "text": "This comment was deleted." }, { "code": null, "e": 2455, "s": 2453, "text": "0" }, { "code": null, "e": 2478, "s": 2455, "text": "chiyan sethuin 7 hours" }, { "code": null, "e": 2663, "s": 2478, "text": "import math\n\nclass Solution:\n def candyStore(self, candies, n, k):\n candies.sort()\n cnt = math.ceil(n / (k + 1))\n return sum(candies[:cnt]), sum(candies[-cnt:])" }, { "code": null, "e": 2665, "s": 2663, "text": "0" }, { "code": null, "e": 2692, "s": 2665, "text": "sikkusaurav12315 hours ago" }, { "code": null, "e": 3399, "s": 2692, "text": "public: vector<int> candyStore(int candies[], int N, int K) { // Write Your Code here sort(candies,candies+N); int dif_can=0; int price=0; vector<int>v; for(int i=0;i<N;i++) { price=price+candies[i]; dif_can=dif_can+K+1; if(dif_can>=N) { v.push_back(price); break; } } reverse(candies,candies+N); dif_can=0; price=0; for(int i=0;i<N;i++) { price=price+candies[i]; dif_can=dif_can+K+1; if(dif_can>=N) { v.push_back(price); break; } } return v; }" }, { "code": null, "e": 3403, "s": 3401, "text": "0" }, { "code": null, "e": 3433, "s": 3403, "text": "subrotomukherjee816 hours ago" }, { "code": null, "e": 3769, "s": 3433, "text": "def candyStore(self, a,n,k):\n # code here\n mn,mx=0,0\n a.sort()\n val=n//(k+1)\n if n%(k+1)!=0:\n val+=1\n for i in range(0,n):\n if i<val:\n mn+=a[i]\n a=a[::-1]\n for i in range(n):\n if i<val:\n mx+=a[i]\n return mn,mx" }, { "code": null, "e": 3771, "s": 3769, "text": "0" }, { "code": null, "e": 3824, "s": 3771, "text": "45mzzbhoest5k5060ff1se8zbxbntzof9sjy5d1e19 hours ago" }, { "code": null, "e": 4221, "s": 3824, "text": "class Solution{public: vector<int> candyStore(int candies[], int N, int K) { // Write Your Code here int mincost=0,maxcost=0; int mx=N-1, mi=0; sort(candies,candies+N); for(int i=0,j=N-1;i<=mx && j>=mi;i++,j--){ mincost+=candies[i]; maxcost+=candies[j]; mx -=K; mi +=K; } return {mincost,maxcost}; }};" }, { "code": null, "e": 4224, "s": 4221, "text": "+1" }, { "code": null, "e": 4247, "s": 4224, "text": "gourangp2923 hours ago" }, { "code": null, "e": 4661, "s": 4247, "text": "vector<int> candyStore(int candies[], int N, int K) { // Write Your Code here int minamt=0; int maxamt=0; sort(candies,candies+N); int x=0; for(int i=0; i<N-x; i++) { minamt+=candies[i]; x = x+K; } int y=0; for(int i=N-1; i>=y; i--) { maxamt+=candies[i]; y = y+K; } return {minamt,maxamt}; }" }, { "code": null, "e": 4663, "s": 4661, "text": "0" }, { "code": null, "e": 4688, "s": 4663, "text": "praveenkumar122 days ago" }, { "code": null, "e": 4717, "s": 4688, "text": "May be it's a good approach." }, { "code": null, "e": 4747, "s": 4717, "text": "But Looking for more optimal!" }, { "code": null, "e": 5387, "s": 4747, "text": "public:\n vector<int> candyStore(int candies[], int N, int K)\n {\n // Write Your Code here\n vector<int>ret;\n sort(candies,candies+N);\n int remains = N-1;\n int i=0;\n int min=0;\n while(i<=remains){\n min+=candies[i];\n remains-=K;\n i++;\n }\n ret.push_back(min);\n \n reverse(candies,candies+N);\n \n remains = N-1;\n int j=0;\n int max=0;\n while(j<=remains){\n max+=candies[j];\n remains-=K;\n j++;\n }\n ret.push_back(max);\n \n return ret;\n }" }, { "code": null, "e": 5390, "s": 5387, "text": "+1" }, { "code": null, "e": 5414, "s": 5390, "text": "yashchawla1162 days ago" }, { "code": null, "e": 5458, "s": 5414, "text": "Simple To Understand And Easy To Implement." }, { "code": null, "e": 5542, "s": 5460, "text": "https://yashboss116.blogspot.com/2022/04/shop-in-candy-store-geeks-for-geeks.html" }, { "code": null, "e": 5593, "s": 5544, "text": "Approaches Explained And Complexities Mentioned." }, { "code": null, "e": 5599, "s": 5597, "text": "0" }, { "code": null, "e": 5617, "s": 5599, "text": "jaishp32 days ago" }, { "code": null, "e": 5991, "s": 5617, "text": "vector<int> candyStore(int candies[], int N, int K) { // Write Your Code here sort(candies,candies+N); int t1=0,t2=0,i=0,min=0,max=0; while(N>t1){ min+=candies[i]; i++; t1+=(K+1); } i=N-1; while(N>t2){ max+=candies[i]; i--; t2+=(K+1); } return{min,max}; }" }, { "code": null, "e": 6137, "s": 5991, "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": 6173, "s": 6137, "text": " Login to access your submissions. " }, { "code": null, "e": 6183, "s": 6173, "text": "\nProblem\n" }, { "code": null, "e": 6193, "s": 6183, "text": "\nContest\n" }, { "code": null, "e": 6256, "s": 6193, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 6404, "s": 6256, "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": 6612, "s": 6404, "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": 6718, "s": 6612, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Cutting a Rod | DP-13 - GeeksforGeeks
28 Mar, 2022 Given a rod of length n inches and an array of prices that includes prices of all pieces of size smaller than n. Determine the maximum value obtainable by cutting up the rod and selling the pieces. For example, if the length of the rod is 8 and the values of different pieces are given as the following, then the maximum obtainable value is 22 (by cutting in two pieces of lengths 2 and 6) length | 1 2 3 4 5 6 7 8 -------------------------------------------- price | 1 5 8 9 10 17 17 20 And if the prices are as following, then the maximum obtainable value is 24 (by cutting in eight pieces of length 1) length | 1 2 3 4 5 6 7 8 -------------------------------------------- price | 3 5 8 9 10 17 17 20 A naive solution to this problem is to generate all configurations of different pieces and find the highest-priced configuration. This solution is exponential in terms of time complexity. Let us see how this problem possesses both important properties of a Dynamic Programming (DP) Problem and can efficiently be solved using Dynamic Programming.1) Optimal Substructure: We can get the best price by making a cut at different positions and comparing the values obtained after a cut. We can recursively call the same function for a piece obtained after a cut.Let cutRod(n) be the required (best possible price) value for a rod of length n. cutRod(n) can be written as follows.cutRod(n) = max(price[i] + cutRod(n-i-1)) for all i in {0, 1 .. n-1}2) Overlapping Subproblems The following is a simple recursive implementation of the Rod Cutting problem. The implementation simply follows the recursive structure mentioned above. Maximum Obtainable Value is 22 Considering the above implementation, the following is the recursion tree for a Rod of length 4. cR() ---> cutRod() cR(4) / / / / cR(3) cR(2) cR(1) cR(0) / | / | / | / | cR(2) cR(1) cR(0) cR(1) cR(0) cR(0) / | | / | | cR(1) cR(0) cR(0) cR(0) / / CR(0) In the above partial recursion tree, cR(2) is solved twice. We can see that there are many subproblems that are solved again and again. Since the same subproblems are called again, this problem has the Overlapping Subproblems property. So the Rod Cutting problem has both properties (see this and this) of a dynamic programming problem. Like other typical Dynamic Programming(DP) problems, recomputations of the same subproblems can be avoided by constructing a temporary array val[] in a bottom-up manner. C++ C Java Python3 C# PHP Javascript // A Dynamic Programming solution for Rod cutting problem#include<iostream>#include <bits/stdc++.h>#include<math.h>using namespace std; // A utility function to get the maximum of two integersint max(int a, int b) { return (a > b)? a : b;} /* Returns the best obtainable price for a rod of length n and price[] as prices of different pieces */int cutRod(int price[], int n){ int val[n+1]; val[0] = 0; int i, j; // Build the table val[] in bottom up manner and return the last entry // from the table for (i = 1; i<=n; i++) { int max_val = INT_MIN; for (j = 0; j < i; j++) max_val = max(max_val, price[j] + val[i-j-1]); val[i] = max_val; } return val[n];} /* Driver program to test above functions */int main(){ int arr[] = {1, 5, 8, 9, 10, 17, 17, 20}; int size = sizeof(arr)/sizeof(arr[0]); cout <<"Maximum Obtainable Value is "<<cutRod(arr, size); getchar(); return 0;} // This code is contributed by shivanisinghss2110 // A Dynamic Programming solution for Rod cutting problem#include<stdio.h>#include<limits.h> // A utility function to get the maximum of two integersint max(int a, int b) { return (a > b)? a : b;} /* Returns the best obtainable price for a rod of length n and price[] as prices of different pieces */int cutRod(int price[], int n){ int val[n+1]; val[0] = 0; int i, j; // Build the table val[] in bottom up manner and return the last entry // from the table for (i = 1; i<=n; i++) { int max_val = INT_MIN; for (j = 0; j < i; j++) max_val = max(max_val, price[j] + val[i-j-1]); val[i] = max_val; } return val[n];} /* Driver program to test above functions */int main(){ int arr[] = {1, 5, 8, 9, 10, 17, 17, 20}; int size = sizeof(arr)/sizeof(arr[0]); printf("Maximum Obtainable Value is %d", cutRod(arr, size)); getchar(); return 0;} // A Dynamic Programming solution for Rod cutting problemclass RodCutting{ /* Returns the best obtainable price for a rod of length n and price[] as prices of different pieces */ static int cutRod(int price[],int n) { int val[] = new int[n+1]; val[0] = 0; // Build the table val[] in bottom up manner and return // the last entry from the table for (int i = 1; i<=n; i++) { int max_val = Integer.MIN_VALUE; for (int j = 0; j < i; j++) max_val = Math.max(max_val, price[j] + val[i-j-1]); val[i] = max_val; } return val[n]; } /* Driver program to test above functions */ public static void main(String args[]) { int arr[] = new int[] {1, 5, 8, 9, 10, 17, 17, 20}; int size = arr.length; System.out.println("Maximum Obtainable Value is " + cutRod(arr, size)); }}/* This code is contributed by Rajat Mishra */ # A Dynamic Programming solution for Rod cutting problemINT_MIN = -32767 # Returns the best obtainable price for a rod of length n and# price[] as prices of different piecesdef cutRod(price, n): val = [0 for x in range(n+1)] val[0] = 0 # Build the table val[] in bottom up manner and return # the last entry from the table for i in range(1, n+1): max_val = INT_MIN for j in range(i): max_val = max(max_val, price[j] + val[i-j-1]) val[i] = max_val return val[n] # Driver program to test above functionsarr = [1, 5, 8, 9, 10, 17, 17, 20]size = len(arr)print("Maximum Obtainable Value is " + str(cutRod(arr, size))) # This code is contributed by Bhavya Jain // A Dynamic Programming solution// for Rod cutting problemusing System;class GFG { /* Returns the best obtainable price for a rod of length n and price[] as prices of different pieces */ static int cutRod(int []price,int n) { int []val = new int[n + 1]; val[0] = 0; // Build the table val[] in // bottom up manner and return // the last entry from the table for (int i = 1; i<=n; i++) { int max_val = int.MinValue; for (int j = 0; j < i; j++) max_val = Math.Max(max_val, price[j] + val[i - j - 1]); val[i] = max_val; } return val[n]; } // Driver Code public static void Main() { int []arr = new int[] {1, 5, 8, 9, 10, 17, 17, 20}; int size = arr.Length; Console.WriteLine("Maximum Obtainable Value is " + cutRod(arr, size)); }} // This code is contributed by Sam007 <?php// A Dynamic Programming solution for// Rod cutting problem /* Returns the best obtainable pricefor a rod of length n and price[] asprices of different pieces */function cutRod( $price, $n){ $val = array(); $val[0] = 0; $i; $j; // Build the table val[] in bottom // up manner and return the last // entry from the table for ($i = 1; $i <= $n; $i++) { $max_val = PHP_INT_MIN; for ($j = 0; $j < $i; $j++) $max_val = max($max_val, $price[$j] + $val[$i-$j-1]); $val[$i] = $max_val; } return $val[$n];} // Driver program to test above functions$arr = array(1, 5, 8, 9, 10, 17, 17, 20);$size = count($arr);echo "Maximum Obtainable Value is ", cutRod($arr, $size); // This code is contributed by anuj_67.?> <script> // A Dynamic Programming solution // for Rod cutting problem /* Returns the best obtainable price for a rod of length n and price[] as prices of different pieces */ function cutRod(price, n) { let val = new Array(n + 1); val[0] = 0; // Build the table val[] in // bottom up manner and return // the last entry from the table for (let i = 1; i<=n; i++) { let max_val = Number.MIN_VALUE; for (let j = 0; j < i; j++) max_val = Math.max(max_val, price[j] + val[i - j - 1]); val[i] = max_val; } return val[n]; } let arr = [1, 5, 8, 9, 10, 17, 17, 20]; let size = arr.length; document.write("Maximum Obtainable Value is " + cutRod(arr, size) + "n");</script> Maximum Obtainable Value is 22 The Time Complexity of the above implementation is O(n^2), which is much better than the worst-case time complexity of Naive Recursive implementation. 3) Using the idea of Unbounded Knapsack. This problem is very similar to the Unbounded Knapsack Problem, where there are multiple occurrences of the same item. Here the pieces of the rod. Now I will create an analogy between Unbounded Knapsack and the Rod Cutting Problem. C++ C Java Python3 C# Javascript // CPP program for above approach#include <iostream>using namespace std; // Global Array for// the purpose of memoization.int t[9][9]; // A recursive program, using ,// memoization, to implement the// rod cutting problem(Top-Down).int un_kp(int price[], int length[], int Max_len, int n){ // The maximum price will be zero, // when either the length of the rod // is zero or price is zero. if (n == 0 || Max_len == 0) { return 0; } // If the length of the rod is less // than the maximum length, Max_lene will // consider it.Now depending // upon the profit, // either Max_lene we will take // it or discard it. if (length[n - 1] <= Max_len) { t[n][Max_len] = max(price[n - 1] + un_kp(price, length, Max_len - length[n - 1], n), un_kp(price, length, Max_len, n - 1)); } // If the length of the rod is // greater than the permitted size, // Max_len we will not consider it. else { t[n][Max_len] = un_kp(price, length, Max_len, n - 1); } // Max_lene Max_lenill return the maximum // value obtained, Max_lenhich is present // at the nth roMax_len and Max_length column. return t[n][Max_len];} /* Driver program totest above functions */int main(){ int price[] = { 1, 5, 8, 9, 10, 17, 17, 20 }; int n = sizeof(price) / sizeof(price[0]); int length[n]; for (int i = 0; i < n; i++) { length[i] = i + 1; } int Max_len = n; // Function Call cout << "Maximum obtained value is " << un_kp(price, length, n, Max_len) << endl;} // C program for above approach#include <stdio.h>#include <stdlib.h> int max(int a, int b){ return (a > b) ? a : b;} // Global Array for the// purpose of memoization.int t[9][9]; // A recursive program, using ,// memoization, to implement the// rod cutting problem(Top-Down).int un_kp(int price[], int length[], int Max_len, int n){ // The maximum price will be zero, // when either the length of the rod // is zero or price is zero. if (n == 0 || Max_len == 0) { return 0; } // If the length of the rod is less // than the maximum length, Max_lene // will consider it.Now depending // upon the profit, // either Max_lene we will take it // or discard it. if (length[n - 1] <= Max_len) { t[n][Max_len] = max(price[n - 1] + un_kp(price, length, Max_len - length[n - 1], n), un_kp(price, length, Max_len, n - 1)); } // If the length of the rod is greater // than the permitted size, Max_len // we will not consider it. else { t[n][Max_len] = un_kp(price, length, Max_len, n - 1); } // Max_lene Max_lenill return // the maximum value obtained, // Max_lenhich is present at the // nth roMax_len and Max_length column. return t[n][Max_len];} /* Driver program to test above functions */int main(){ int price[] = { 1, 5, 8, 9, 10, 17, 17, 20 }; int n = sizeof(price) / sizeof(price[0]); int length[n]; for (int i = 0; i < n; i++) { length[i] = i + 1; } int Max_len = n; // Function Call printf("Maximum obtained value is %d \n", un_kp(price, length, n, Max_len));} // Java program for above approachimport java.io.*; class GFG { // Global Array for // the purpose of memoization. static int t[][] = new int[9][9]; // A recursive program, using , // memoization, to implement the // rod cutting problem(Top-Down). public static int un_kp(int price[], int length[], int Max_len, int n) { // The maximum price will be zero, // when either the length of the rod // is zero or price is zero. if (n == 0 || Max_len == 0) { return 0; } // If the length of the rod is less // than the maximum length, Max_lene will // consider it.Now depending // upon the profit, // either Max_lene we will take // it or discard it. if (length[n - 1] <= Max_len) { t[n][Max_len] = Math.max( price[n - 1] + un_kp(price, length, Max_len - length[n - 1], n), un_kp(price, length, Max_len, n - 1)); } // If the length of the rod is // greater than the permitted size, // Max_len we will not consider it. else { t[n][Max_len] = un_kp(price, length, Max_len, n - 1); } // Max_lene Max_lenill return the maximum // value obtained, Max_lenhich is present // at the nth roMax_len and Max_length column. return t[n][Max_len]; } public static void main(String[] args) { int price[] = new int[] { 1, 5, 8, 9, 10, 17, 17, 20 }; int n = price.length; int length[] = new int[n]; for (int i = 0; i < n; i++) { length[i] = i + 1; } int Max_len = n; System.out.println( "Maximum obtained value is " + un_kp(price, length, n, Max_len)); }} // This code is contributed by rajsanghavi9. # Python program for above approach # Global Array for# the purpose of memoization.t = [[0 for i in range(9)] for j in range(9)] # A recursive program, using ,# memoization, to implement the# rod cutting problem(Top-Down).def un_kp(price, length, Max_len, n): # The maximum price will be zero, # when either the length of the rod # is zero or price is zero. if (n == 0 or Max_len == 0): return 0; # If the length of the rod is less # than the maximum length, Max_lene will # consider it.Now depending # upon the profit, # either Max_lene we will take # it or discard it. if (length[n - 1] <= Max_len): t[n][Max_len] = max(price[n - 1] + un_kp(price, length, Max_len - length[n - 1], n), un_kp(price, length, Max_len, n - 1)); # If the length of the rod is # greater than the permitted size, # Max_len we will not consider it. else: t[n][Max_len] = un_kp(price, length, Max_len, n - 1); # Max_lene Max_lenill return the maximum # value obtained, Max_lenhich is present # at the nth roMax_len and Max_length column. return t[n][Max_len]; if __name__ == '__main__': price = [1, 5, 8, 9, 10, 17, 17, 20 ]; n =len(price); length = [0]*n; for i in range(n): length[i] = i + 1; Max_len = n; print("Maximum obtained value is " ,un_kp(price, length, n, Max_len)); # This code is contributed by gauravrajput1 // C# program for above approachusing System;public class GFG { // Global Array for // the purpose of memoization. static int [,]t = new int[9,9]; // A recursive program, using , // memoization, to implement the // rod cutting problem(Top-Down). public static int un_kp(int []price, int []length, int Max_len, int n) { // The maximum price will be zero, // when either the length of the rod // is zero or price is zero. if (n == 0 || Max_len == 0) { return 0; } // If the length of the rod is less // than the maximum length, Max_lene will // consider it.Now depending // upon the profit, // either Max_lene we will take // it or discard it. if (length[n - 1] <= Max_len) { t[n,Max_len] = Math.Max(price[n - 1] + un_kp(price, length, Max_len - length[n - 1], n), un_kp(price, length, Max_len, n - 1)); } // If the length of the rod is // greater than the permitted size, // Max_len we will not consider it. else { t[n,Max_len] = un_kp(price, length, Max_len, n - 1); } // Max_lene Max_lenill return the maximum // value obtained, Max_lenhich is present // at the nth roMax_len and Max_length column. return t[n,Max_len]; } // Driver code public static void Main(String[] args) { int []price = new int[] { 1, 5, 8, 9, 10, 17, 17, 20 }; int n = price.Length; int []length = new int[n]; for (int i = 0; i < n; i++) { length[i] = i + 1; } int Max_len = n; Console.WriteLine("Maximum obtained value is " + un_kp(price, length, n, Max_len)); }} // This code is contributed by gauravrajput1. <script> // Javascript program for above approach // Global Array for// the purpose of memoization.let t = new Array(9);for (var i = 0; i < t.length; i++) { t[i] = new Array(2);} // A recursive program, using ,// memoization, to implement the// rod cutting problem(Top-Down).function un_kp(price, length, Max_len, n){ // The maximum price will be zero, // when either the length of the rod // is zero or price is zero. if (n == 0 || Max_len == 0) { return 0; } // If the length of the rod is less // than the maximum length, Max_lene will // consider it.Now depending // upon the profit, // either Max_lene we will take // it or discard it. if (length[n - 1] <= Max_len) { t[n][Max_len] = Math.max(price[n - 1] + un_kp(price, length, Max_len - length[n - 1], n), un_kp(price, length, Max_len, n - 1)); } // If the length of the rod is // greater than the permitted size, // Max_len we will not consider it. else { t[n][Max_len] = un_kp(price, length, Max_len, n - 1); } // Max_lene Max_lenill return the maximum // value obtained, Max_lenhich is present // at the nth roMax_len and Max_length column. return t[n][Max_len];} // Driver code let price = [ 1, 5, 8, 9, 10, 17, 17, 20 ]; let n = price.length; let length = Array(n).fill(0); for (let i = 0; i < n; i++) { length[i] = i + 1; } let Max_len = n; // Function Call document.write("Maximum obtained value is " + un_kp(price, length, n, Max_len)); </script> Maximum obtained value is 22 YouTubeGeeksforGeeks501K subscribersCutting a rod problem | 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 / 9:02•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=oqdttaJ_C6o" 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. Sam007 vt_m aniketmaurya duttabhishek0 decode2207 suresh07 sweetyty target_2 abhinavgargchand pra8eek shivanisinghss2110 rajsanghavi9 GauravRajput1 amartyaghoshgfg sumitgumber28 Dynamic Programming Dynamic Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Bellman–Ford Algorithm | DP-23 Floyd Warshall Algorithm | DP-16 Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Longest Palindromic Substring | Set 1 Matrix Chain Multiplication | DP-8 Subset Sum Problem | DP-25 Overlapping Subproblems Property in Dynamic Programming | DP-1 Sieve of Eratosthenes Edit Distance | DP-5 Minimum number of jumps to reach end
[ { "code": null, "e": 24534, "s": 24506, "text": "\n28 Mar, 2022" }, { "code": null, "e": 24925, "s": 24534, "text": "Given a rod of length n inches and an array of prices that includes prices of all pieces of size smaller than n. Determine the maximum value obtainable by cutting up the rod and selling the pieces. For example, if the length of the rod is 8 and the values of different pieces are given as the following, then the maximum obtainable value is 22 (by cutting in two pieces of lengths 2 and 6) " }, { "code": null, "e": 25054, "s": 24925, "text": "length | 1 2 3 4 5 6 7 8 \n--------------------------------------------\nprice | 1 5 8 9 10 17 17 20" }, { "code": null, "e": 25172, "s": 25054, "text": "And if the prices are as following, then the maximum obtainable value is 24 (by cutting in eight pieces of length 1) " }, { "code": null, "e": 25301, "s": 25172, "text": "length | 1 2 3 4 5 6 7 8 \n--------------------------------------------\nprice | 3 5 8 9 10 17 17 20" }, { "code": null, "e": 26151, "s": 25301, "text": "A naive solution to this problem is to generate all configurations of different pieces and find the highest-priced configuration. This solution is exponential in terms of time complexity. Let us see how this problem possesses both important properties of a Dynamic Programming (DP) Problem and can efficiently be solved using Dynamic Programming.1) Optimal Substructure: We can get the best price by making a cut at different positions and comparing the values obtained after a cut. We can recursively call the same function for a piece obtained after a cut.Let cutRod(n) be the required (best possible price) value for a rod of length n. cutRod(n) can be written as follows.cutRod(n) = max(price[i] + cutRod(n-i-1)) for all i in {0, 1 .. n-1}2) Overlapping Subproblems The following is a simple recursive implementation of the Rod Cutting problem. " }, { "code": null, "e": 26228, "s": 26151, "text": "The implementation simply follows the recursive structure mentioned above. " }, { "code": null, "e": 26259, "s": 26228, "text": "Maximum Obtainable Value is 22" }, { "code": null, "e": 26358, "s": 26259, "text": " Considering the above implementation, the following is the recursion tree for a Rod of length 4. " }, { "code": null, "e": 26765, "s": 26358, "text": "cR() ---> cutRod() \n\n cR(4)\n / / \n / / \n cR(3) cR(2) cR(1) cR(0)\n / | / |\n / | / | \n cR(2) cR(1) cR(0) cR(1) cR(0) cR(0)\n / | |\n / | | \n cR(1) cR(0) cR(0) cR(0)\n /\n /\nCR(0)" }, { "code": null, "e": 27273, "s": 26765, "text": "In the above partial recursion tree, cR(2) is solved twice. We can see that there are many subproblems that are solved again and again. Since the same subproblems are called again, this problem has the Overlapping Subproblems property. So the Rod Cutting problem has both properties (see this and this) of a dynamic programming problem. Like other typical Dynamic Programming(DP) problems, recomputations of the same subproblems can be avoided by constructing a temporary array val[] in a bottom-up manner. " }, { "code": null, "e": 27277, "s": 27273, "text": "C++" }, { "code": null, "e": 27279, "s": 27277, "text": "C" }, { "code": null, "e": 27284, "s": 27279, "text": "Java" }, { "code": null, "e": 27292, "s": 27284, "text": "Python3" }, { "code": null, "e": 27295, "s": 27292, "text": "C#" }, { "code": null, "e": 27299, "s": 27295, "text": "PHP" }, { "code": null, "e": 27310, "s": 27299, "text": "Javascript" }, { "code": "// A Dynamic Programming solution for Rod cutting problem#include<iostream>#include <bits/stdc++.h>#include<math.h>using namespace std; // A utility function to get the maximum of two integersint max(int a, int b) { return (a > b)? a : b;} /* Returns the best obtainable price for a rod of length n and price[] as prices of different pieces */int cutRod(int price[], int n){ int val[n+1]; val[0] = 0; int i, j; // Build the table val[] in bottom up manner and return the last entry // from the table for (i = 1; i<=n; i++) { int max_val = INT_MIN; for (j = 0; j < i; j++) max_val = max(max_val, price[j] + val[i-j-1]); val[i] = max_val; } return val[n];} /* Driver program to test above functions */int main(){ int arr[] = {1, 5, 8, 9, 10, 17, 17, 20}; int size = sizeof(arr)/sizeof(arr[0]); cout <<\"Maximum Obtainable Value is \"<<cutRod(arr, size); getchar(); return 0;} // This code is contributed by shivanisinghss2110", "e": 28295, "s": 27310, "text": null }, { "code": "// A Dynamic Programming solution for Rod cutting problem#include<stdio.h>#include<limits.h> // A utility function to get the maximum of two integersint max(int a, int b) { return (a > b)? a : b;} /* Returns the best obtainable price for a rod of length n and price[] as prices of different pieces */int cutRod(int price[], int n){ int val[n+1]; val[0] = 0; int i, j; // Build the table val[] in bottom up manner and return the last entry // from the table for (i = 1; i<=n; i++) { int max_val = INT_MIN; for (j = 0; j < i; j++) max_val = max(max_val, price[j] + val[i-j-1]); val[i] = max_val; } return val[n];} /* Driver program to test above functions */int main(){ int arr[] = {1, 5, 8, 9, 10, 17, 17, 20}; int size = sizeof(arr)/sizeof(arr[0]); printf(\"Maximum Obtainable Value is %d\", cutRod(arr, size)); getchar(); return 0;}", "e": 29190, "s": 28295, "text": null }, { "code": "// A Dynamic Programming solution for Rod cutting problemclass RodCutting{ /* Returns the best obtainable price for a rod of length n and price[] as prices of different pieces */ static int cutRod(int price[],int n) { int val[] = new int[n+1]; val[0] = 0; // Build the table val[] in bottom up manner and return // the last entry from the table for (int i = 1; i<=n; i++) { int max_val = Integer.MIN_VALUE; for (int j = 0; j < i; j++) max_val = Math.max(max_val, price[j] + val[i-j-1]); val[i] = max_val; } return val[n]; } /* Driver program to test above functions */ public static void main(String args[]) { int arr[] = new int[] {1, 5, 8, 9, 10, 17, 17, 20}; int size = arr.length; System.out.println(\"Maximum Obtainable Value is \" + cutRod(arr, size)); }}/* This code is contributed by Rajat Mishra */", "e": 30215, "s": 29190, "text": null }, { "code": "# A Dynamic Programming solution for Rod cutting problemINT_MIN = -32767 # Returns the best obtainable price for a rod of length n and# price[] as prices of different piecesdef cutRod(price, n): val = [0 for x in range(n+1)] val[0] = 0 # Build the table val[] in bottom up manner and return # the last entry from the table for i in range(1, n+1): max_val = INT_MIN for j in range(i): max_val = max(max_val, price[j] + val[i-j-1]) val[i] = max_val return val[n] # Driver program to test above functionsarr = [1, 5, 8, 9, 10, 17, 17, 20]size = len(arr)print(\"Maximum Obtainable Value is \" + str(cutRod(arr, size))) # This code is contributed by Bhavya Jain", "e": 30923, "s": 30215, "text": null }, { "code": "// A Dynamic Programming solution// for Rod cutting problemusing System;class GFG { /* Returns the best obtainable price for a rod of length n and price[] as prices of different pieces */ static int cutRod(int []price,int n) { int []val = new int[n + 1]; val[0] = 0; // Build the table val[] in // bottom up manner and return // the last entry from the table for (int i = 1; i<=n; i++) { int max_val = int.MinValue; for (int j = 0; j < i; j++) max_val = Math.Max(max_val, price[j] + val[i - j - 1]); val[i] = max_val; } return val[n]; } // Driver Code public static void Main() { int []arr = new int[] {1, 5, 8, 9, 10, 17, 17, 20}; int size = arr.Length; Console.WriteLine(\"Maximum Obtainable Value is \" + cutRod(arr, size)); }} // This code is contributed by Sam007", "e": 31945, "s": 30923, "text": null }, { "code": "<?php// A Dynamic Programming solution for// Rod cutting problem /* Returns the best obtainable pricefor a rod of length n and price[] asprices of different pieces */function cutRod( $price, $n){ $val = array(); $val[0] = 0; $i; $j; // Build the table val[] in bottom // up manner and return the last // entry from the table for ($i = 1; $i <= $n; $i++) { $max_val = PHP_INT_MIN; for ($j = 0; $j < $i; $j++) $max_val = max($max_val, $price[$j] + $val[$i-$j-1]); $val[$i] = $max_val; } return $val[$n];} // Driver program to test above functions$arr = array(1, 5, 8, 9, 10, 17, 17, 20);$size = count($arr);echo \"Maximum Obtainable Value is \", cutRod($arr, $size); // This code is contributed by anuj_67.?>", "e": 32768, "s": 31945, "text": null }, { "code": "<script> // A Dynamic Programming solution // for Rod cutting problem /* Returns the best obtainable price for a rod of length n and price[] as prices of different pieces */ function cutRod(price, n) { let val = new Array(n + 1); val[0] = 0; // Build the table val[] in // bottom up manner and return // the last entry from the table for (let i = 1; i<=n; i++) { let max_val = Number.MIN_VALUE; for (let j = 0; j < i; j++) max_val = Math.max(max_val, price[j] + val[i - j - 1]); val[i] = max_val; } return val[n]; } let arr = [1, 5, 8, 9, 10, 17, 17, 20]; let size = arr.length; document.write(\"Maximum Obtainable Value is \" + cutRod(arr, size) + \"n\");</script>", "e": 33600, "s": 32768, "text": null }, { "code": null, "e": 33631, "s": 33600, "text": "Maximum Obtainable Value is 22" }, { "code": null, "e": 33782, "s": 33631, "text": "The Time Complexity of the above implementation is O(n^2), which is much better than the worst-case time complexity of Naive Recursive implementation." }, { "code": null, "e": 33823, "s": 33782, "text": "3) Using the idea of Unbounded Knapsack." }, { "code": null, "e": 33970, "s": 33823, "text": "This problem is very similar to the Unbounded Knapsack Problem, where there are multiple occurrences of the same item. Here the pieces of the rod." }, { "code": null, "e": 34056, "s": 33970, "text": "Now I will create an analogy between Unbounded Knapsack and the Rod Cutting Problem. " }, { "code": null, "e": 34060, "s": 34056, "text": "C++" }, { "code": null, "e": 34062, "s": 34060, "text": "C" }, { "code": null, "e": 34067, "s": 34062, "text": "Java" }, { "code": null, "e": 34075, "s": 34067, "text": "Python3" }, { "code": null, "e": 34078, "s": 34075, "text": "C#" }, { "code": null, "e": 34089, "s": 34078, "text": "Javascript" }, { "code": "// CPP program for above approach#include <iostream>using namespace std; // Global Array for// the purpose of memoization.int t[9][9]; // A recursive program, using ,// memoization, to implement the// rod cutting problem(Top-Down).int un_kp(int price[], int length[], int Max_len, int n){ // The maximum price will be zero, // when either the length of the rod // is zero or price is zero. if (n == 0 || Max_len == 0) { return 0; } // If the length of the rod is less // than the maximum length, Max_lene will // consider it.Now depending // upon the profit, // either Max_lene we will take // it or discard it. if (length[n - 1] <= Max_len) { t[n][Max_len] = max(price[n - 1] + un_kp(price, length, Max_len - length[n - 1], n), un_kp(price, length, Max_len, n - 1)); } // If the length of the rod is // greater than the permitted size, // Max_len we will not consider it. else { t[n][Max_len] = un_kp(price, length, Max_len, n - 1); } // Max_lene Max_lenill return the maximum // value obtained, Max_lenhich is present // at the nth roMax_len and Max_length column. return t[n][Max_len];} /* Driver program totest above functions */int main(){ int price[] = { 1, 5, 8, 9, 10, 17, 17, 20 }; int n = sizeof(price) / sizeof(price[0]); int length[n]; for (int i = 0; i < n; i++) { length[i] = i + 1; } int Max_len = n; // Function Call cout << \"Maximum obtained value is \" << un_kp(price, length, n, Max_len) << endl;}", "e": 35782, "s": 34089, "text": null }, { "code": "// C program for above approach#include <stdio.h>#include <stdlib.h> int max(int a, int b){ return (a > b) ? a : b;} // Global Array for the// purpose of memoization.int t[9][9]; // A recursive program, using ,// memoization, to implement the// rod cutting problem(Top-Down).int un_kp(int price[], int length[], int Max_len, int n){ // The maximum price will be zero, // when either the length of the rod // is zero or price is zero. if (n == 0 || Max_len == 0) { return 0; } // If the length of the rod is less // than the maximum length, Max_lene // will consider it.Now depending // upon the profit, // either Max_lene we will take it // or discard it. if (length[n - 1] <= Max_len) { t[n][Max_len] = max(price[n - 1] + un_kp(price, length, Max_len - length[n - 1], n), un_kp(price, length, Max_len, n - 1)); } // If the length of the rod is greater // than the permitted size, Max_len // we will not consider it. else { t[n][Max_len] = un_kp(price, length, Max_len, n - 1); } // Max_lene Max_lenill return // the maximum value obtained, // Max_lenhich is present at the // nth roMax_len and Max_length column. return t[n][Max_len];} /* Driver program to test above functions */int main(){ int price[] = { 1, 5, 8, 9, 10, 17, 17, 20 }; int n = sizeof(price) / sizeof(price[0]); int length[n]; for (int i = 0; i < n; i++) { length[i] = i + 1; } int Max_len = n; // Function Call printf(\"Maximum obtained value is %d \\n\", un_kp(price, length, n, Max_len));}", "e": 37530, "s": 35782, "text": null }, { "code": "// Java program for above approachimport java.io.*; class GFG { // Global Array for // the purpose of memoization. static int t[][] = new int[9][9]; // A recursive program, using , // memoization, to implement the // rod cutting problem(Top-Down). public static int un_kp(int price[], int length[], int Max_len, int n) { // The maximum price will be zero, // when either the length of the rod // is zero or price is zero. if (n == 0 || Max_len == 0) { return 0; } // If the length of the rod is less // than the maximum length, Max_lene will // consider it.Now depending // upon the profit, // either Max_lene we will take // it or discard it. if (length[n - 1] <= Max_len) { t[n][Max_len] = Math.max( price[n - 1] + un_kp(price, length, Max_len - length[n - 1], n), un_kp(price, length, Max_len, n - 1)); } // If the length of the rod is // greater than the permitted size, // Max_len we will not consider it. else { t[n][Max_len] = un_kp(price, length, Max_len, n - 1); } // Max_lene Max_lenill return the maximum // value obtained, Max_lenhich is present // at the nth roMax_len and Max_length column. return t[n][Max_len]; } public static void main(String[] args) { int price[] = new int[] { 1, 5, 8, 9, 10, 17, 17, 20 }; int n = price.length; int length[] = new int[n]; for (int i = 0; i < n; i++) { length[i] = i + 1; } int Max_len = n; System.out.println( \"Maximum obtained value is \" + un_kp(price, length, n, Max_len)); }} // This code is contributed by rajsanghavi9.", "e": 39451, "s": 37530, "text": null }, { "code": "# Python program for above approach # Global Array for# the purpose of memoization.t = [[0 for i in range(9)] for j in range(9)] # A recursive program, using ,# memoization, to implement the# rod cutting problem(Top-Down).def un_kp(price, length, Max_len, n): # The maximum price will be zero, # when either the length of the rod # is zero or price is zero. if (n == 0 or Max_len == 0): return 0; # If the length of the rod is less # than the maximum length, Max_lene will # consider it.Now depending # upon the profit, # either Max_lene we will take # it or discard it. if (length[n - 1] <= Max_len): t[n][Max_len] = max(price[n - 1] + un_kp(price, length, Max_len - length[n - 1], n), un_kp(price, length, Max_len, n - 1)); # If the length of the rod is # greater than the permitted size, # Max_len we will not consider it. else: t[n][Max_len] = un_kp(price, length, Max_len, n - 1); # Max_lene Max_lenill return the maximum # value obtained, Max_lenhich is present # at the nth roMax_len and Max_length column. return t[n][Max_len]; if __name__ == '__main__': price = [1, 5, 8, 9, 10, 17, 17, 20 ]; n =len(price); length = [0]*n; for i in range(n): length[i] = i + 1; Max_len = n; print(\"Maximum obtained value is \" ,un_kp(price, length, n, Max_len)); # This code is contributed by gauravrajput1", "e": 40894, "s": 39451, "text": null }, { "code": "// C# program for above approachusing System;public class GFG { // Global Array for // the purpose of memoization. static int [,]t = new int[9,9]; // A recursive program, using , // memoization, to implement the // rod cutting problem(Top-Down). public static int un_kp(int []price, int []length, int Max_len, int n) { // The maximum price will be zero, // when either the length of the rod // is zero or price is zero. if (n == 0 || Max_len == 0) { return 0; } // If the length of the rod is less // than the maximum length, Max_lene will // consider it.Now depending // upon the profit, // either Max_lene we will take // it or discard it. if (length[n - 1] <= Max_len) { t[n,Max_len] = Math.Max(price[n - 1] + un_kp(price, length, Max_len - length[n - 1], n), un_kp(price, length, Max_len, n - 1)); } // If the length of the rod is // greater than the permitted size, // Max_len we will not consider it. else { t[n,Max_len] = un_kp(price, length, Max_len, n - 1); } // Max_lene Max_lenill return the maximum // value obtained, Max_lenhich is present // at the nth roMax_len and Max_length column. return t[n,Max_len]; } // Driver code public static void Main(String[] args) { int []price = new int[] { 1, 5, 8, 9, 10, 17, 17, 20 }; int n = price.Length; int []length = new int[n]; for (int i = 0; i < n; i++) { length[i] = i + 1; } int Max_len = n; Console.WriteLine(\"Maximum obtained value is \" + un_kp(price, length, n, Max_len)); }} // This code is contributed by gauravrajput1.", "e": 42534, "s": 40894, "text": null }, { "code": "<script> // Javascript program for above approach // Global Array for// the purpose of memoization.let t = new Array(9);for (var i = 0; i < t.length; i++) { t[i] = new Array(2);} // A recursive program, using ,// memoization, to implement the// rod cutting problem(Top-Down).function un_kp(price, length, Max_len, n){ // The maximum price will be zero, // when either the length of the rod // is zero or price is zero. if (n == 0 || Max_len == 0) { return 0; } // If the length of the rod is less // than the maximum length, Max_lene will // consider it.Now depending // upon the profit, // either Max_lene we will take // it or discard it. if (length[n - 1] <= Max_len) { t[n][Max_len] = Math.max(price[n - 1] + un_kp(price, length, Max_len - length[n - 1], n), un_kp(price, length, Max_len, n - 1)); } // If the length of the rod is // greater than the permitted size, // Max_len we will not consider it. else { t[n][Max_len] = un_kp(price, length, Max_len, n - 1); } // Max_lene Max_lenill return the maximum // value obtained, Max_lenhich is present // at the nth roMax_len and Max_length column. return t[n][Max_len];} // Driver code let price = [ 1, 5, 8, 9, 10, 17, 17, 20 ]; let n = price.length; let length = Array(n).fill(0); for (let i = 0; i < n; i++) { length[i] = i + 1; } let Max_len = n; // Function Call document.write(\"Maximum obtained value is \" + un_kp(price, length, n, Max_len)); </script>", "e": 44220, "s": 42534, "text": null }, { "code": null, "e": 44250, "s": 44220, "text": "Maximum obtained value is 22" }, { "code": null, "e": 45070, "s": 44250, "text": "YouTubeGeeksforGeeks501K subscribersCutting a rod problem | 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 / 9:02•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=oqdttaJ_C6o\" 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": 45196, "s": 45070, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 45203, "s": 45196, "text": "Sam007" }, { "code": null, "e": 45208, "s": 45203, "text": "vt_m" }, { "code": null, "e": 45221, "s": 45208, "text": "aniketmaurya" }, { "code": null, "e": 45235, "s": 45221, "text": "duttabhishek0" }, { "code": null, "e": 45246, "s": 45235, "text": "decode2207" }, { "code": null, "e": 45255, "s": 45246, "text": "suresh07" }, { "code": null, "e": 45264, "s": 45255, "text": "sweetyty" }, { "code": null, "e": 45273, "s": 45264, "text": "target_2" }, { "code": null, "e": 45290, "s": 45273, "text": "abhinavgargchand" }, { "code": null, "e": 45298, "s": 45290, "text": "pra8eek" }, { "code": null, "e": 45317, "s": 45298, "text": "shivanisinghss2110" }, { "code": null, "e": 45330, "s": 45317, "text": "rajsanghavi9" }, { "code": null, "e": 45344, "s": 45330, "text": "GauravRajput1" }, { "code": null, "e": 45360, "s": 45344, "text": "amartyaghoshgfg" }, { "code": null, "e": 45374, "s": 45360, "text": "sumitgumber28" }, { "code": null, "e": 45394, "s": 45374, "text": "Dynamic Programming" }, { "code": null, "e": 45414, "s": 45394, "text": "Dynamic Programming" }, { "code": null, "e": 45512, "s": 45414, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 45543, "s": 45512, "text": "Bellman–Ford Algorithm | DP-23" }, { "code": null, "e": 45576, "s": 45543, "text": "Floyd Warshall Algorithm | DP-16" }, { "code": null, "e": 45644, "s": 45576, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" }, { "code": null, "e": 45682, "s": 45644, "text": "Longest Palindromic Substring | Set 1" }, { "code": null, "e": 45717, "s": 45682, "text": "Matrix Chain Multiplication | DP-8" }, { "code": null, "e": 45744, "s": 45717, "text": "Subset Sum Problem | DP-25" }, { "code": null, "e": 45807, "s": 45744, "text": "Overlapping Subproblems Property in Dynamic Programming | DP-1" }, { "code": null, "e": 45829, "s": 45807, "text": "Sieve of Eratosthenes" }, { "code": null, "e": 45850, "s": 45829, "text": "Edit Distance | DP-5" } ]
FileInputStream finalize() Method in Java with Examples - GeeksforGeeks
01 Dec, 2021 Java.io.FileInputStream.finalize() method is a part of Java.io.FileInputStream class. It ensures that the close method of the fileInputStream is called whenever no more references of fileInputStream exist. finalize() method is annotated @Deprecated. finalize() method is used to perform a cleanup act when no more references exist. finalize() method might throw IOException. finalize() method is protected, which means different packages subclass cannot access them. FileInputStream.finalize() is available in java.io.* package. Syntax: protected void finalize​() throws IOException Return Type: finalize() method has a void return type that means this method does not return anything. Exception: finalize() method might throw IOException if any Input/output exception raises. Step 1– First, we must create a class that extends FileInputStream and passes on fileName to its parent class. public class GFG extends FileInputStream { public GFG() { super(fileName); } } Step 2– Create an instance of the class that we created in Step 1 GFG gfg=new GFG(); Step 3– invoke the finalize() method gfg.finalize(); The below program will illustrate the use of the Java.io.FileInputStream.finalize() method- Example: Java // Java Program to illustrate the use of the// Java.io.FileInputStream.finalize() method import java.io.*;import java.io.FileInputStream;import java.io.IOException; public class GFG extends FileInputStream { // parameterized constructor public GFG(String fileName) throws Exception { super(fileName); } public static void main(String[] args) { try { // create instance of GFG class that // extends FileInputStream. // user should change name of the file GFG gfg = new GFG("C://geeksforgeeks//tmp.txt"); // reading bytes from file System.out.println( "Content read from the file before finalize method is called :"); for (int i = 0; i <= 13; i++) System.out.print((char)gfg.read()); // finalize() method is called. // method will perform the cleanup act // if no reference is available gfg.finalize(); // reading bytes again from file System.out.println( "Content read from the file after finalize method is called :"); for (int i = 13; i < 47; i++) System.out.print((char)gfg.read()); } catch (Throwable t) { System.out.println("Some exception"); } }} Output- Content read from the file before finalize method is called : GeeksForGeeks Content read from the file after finalize method is called : is the best website for programmer From the output, it is clear that we can read from the file before and even after invoking the finalize() method. Since finalize() method performs the cleanup act when only no reference exists. tmp.txt Note: The programs might not run in an online IDE. please use an offline IDE and change the Name of the file according to your need. Java-FileInputStream Picked Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Different ways of Reading a text file in Java Constructors in Java Stream In Java Exceptions in Java Generics in Java Functional Interfaces in Java Comparator Interface in Java with Examples HashMap get() Method in Java Strings in Java Introduction to Java
[ { "code": null, "e": 23974, "s": 23946, "text": "\n01 Dec, 2021" }, { "code": null, "e": 24181, "s": 23974, "text": "Java.io.FileInputStream.finalize() method is a part of Java.io.FileInputStream class. It ensures that the close method of the fileInputStream is called whenever no more references of fileInputStream exist." }, { "code": null, "e": 24225, "s": 24181, "text": "finalize() method is annotated @Deprecated." }, { "code": null, "e": 24307, "s": 24225, "text": "finalize() method is used to perform a cleanup act when no more references exist." }, { "code": null, "e": 24350, "s": 24307, "text": "finalize() method might throw IOException." }, { "code": null, "e": 24442, "s": 24350, "text": "finalize() method is protected, which means different packages subclass cannot access them." }, { "code": null, "e": 24504, "s": 24442, "text": "FileInputStream.finalize() is available in java.io.* package." }, { "code": null, "e": 24512, "s": 24504, "text": "Syntax:" }, { "code": null, "e": 24558, "s": 24512, "text": "protected void finalize​() throws IOException" }, { "code": null, "e": 24661, "s": 24558, "text": "Return Type: finalize() method has a void return type that means this method does not return anything." }, { "code": null, "e": 24752, "s": 24661, "text": "Exception: finalize() method might throw IOException if any Input/output exception raises." }, { "code": null, "e": 24863, "s": 24752, "text": "Step 1– First, we must create a class that extends FileInputStream and passes on fileName to its parent class." }, { "code": null, "e": 24962, "s": 24863, "text": "public class GFG extends FileInputStream\n{\n public GFG()\n {\n super(fileName);\n }\n}" }, { "code": null, "e": 25028, "s": 24962, "text": "Step 2– Create an instance of the class that we created in Step 1" }, { "code": null, "e": 25047, "s": 25028, "text": "GFG gfg=new GFG();" }, { "code": null, "e": 25084, "s": 25047, "text": "Step 3– invoke the finalize() method" }, { "code": null, "e": 25100, "s": 25084, "text": "gfg.finalize();" }, { "code": null, "e": 25192, "s": 25100, "text": "The below program will illustrate the use of the Java.io.FileInputStream.finalize() method-" }, { "code": null, "e": 25201, "s": 25192, "text": "Example:" }, { "code": null, "e": 25206, "s": 25201, "text": "Java" }, { "code": "// Java Program to illustrate the use of the// Java.io.FileInputStream.finalize() method import java.io.*;import java.io.FileInputStream;import java.io.IOException; public class GFG extends FileInputStream { // parameterized constructor public GFG(String fileName) throws Exception { super(fileName); } public static void main(String[] args) { try { // create instance of GFG class that // extends FileInputStream. // user should change name of the file GFG gfg = new GFG(\"C://geeksforgeeks//tmp.txt\"); // reading bytes from file System.out.println( \"Content read from the file before finalize method is called :\"); for (int i = 0; i <= 13; i++) System.out.print((char)gfg.read()); // finalize() method is called. // method will perform the cleanup act // if no reference is available gfg.finalize(); // reading bytes again from file System.out.println( \"Content read from the file after finalize method is called :\"); for (int i = 13; i < 47; i++) System.out.print((char)gfg.read()); } catch (Throwable t) { System.out.println(\"Some exception\"); } }}", "e": 26577, "s": 25206, "text": null }, { "code": null, "e": 26585, "s": 26577, "text": "Output-" }, { "code": null, "e": 26757, "s": 26585, "text": "Content read from the file before finalize method is called :\nGeeksForGeeks\nContent read from the file after finalize method is called :\nis the best website for programmer" }, { "code": null, "e": 26951, "s": 26757, "text": "From the output, it is clear that we can read from the file before and even after invoking the finalize() method. Since finalize() method performs the cleanup act when only no reference exists." }, { "code": null, "e": 26959, "s": 26951, "text": "tmp.txt" }, { "code": null, "e": 27092, "s": 26959, "text": "Note: The programs might not run in an online IDE. please use an offline IDE and change the Name of the file according to your need." }, { "code": null, "e": 27113, "s": 27092, "text": "Java-FileInputStream" }, { "code": null, "e": 27120, "s": 27113, "text": "Picked" }, { "code": null, "e": 27125, "s": 27120, "text": "Java" }, { "code": null, "e": 27130, "s": 27125, "text": "Java" }, { "code": null, "e": 27228, "s": 27130, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27274, "s": 27228, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 27295, "s": 27274, "text": "Constructors in Java" }, { "code": null, "e": 27310, "s": 27295, "text": "Stream In Java" }, { "code": null, "e": 27329, "s": 27310, "text": "Exceptions in Java" }, { "code": null, "e": 27346, "s": 27329, "text": "Generics in Java" }, { "code": null, "e": 27376, "s": 27346, "text": "Functional Interfaces in Java" }, { "code": null, "e": 27419, "s": 27376, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 27448, "s": 27419, "text": "HashMap get() Method in Java" }, { "code": null, "e": 27464, "s": 27448, "text": "Strings in Java" } ]
Count permutations of given array that generates the same Binary Search Tree (BST) - GeeksforGeeks
18 Aug, 2021 Given an array, arr[] of size N consisting of elements from the range [1, N], that represents the order, in which the elements are inserted into a Binary Search Tree, the task is to count the number of ways to rearrange the given array to get the same BST. Examples: Input: arr[ ] ={3, 4, 5, 1, 2}Output: 6Explanation :The permutations of the array which represent the same BST are:{{3, 4, 5, 1, 2}, {3, 1, 2, 4, 5}, {3, 1, 4, 2, 5}, {3, 1, 4, 5, 2}, {3, 4, 1, 2, 5}, {3, 4, 1, 5, 2}}. Therefore, the output is 6. Input: arr[ ] ={2, 1, 6, 5, 4, 3}Output: 5 Approach: The idea is to first fix the root node and then recursively count the number of ways to rearrange the elements of the left subtree and the elements of the right subtree in such a way that the relative order within the elements of the left subtree and right subtree must be same. Here is the recurrence relation: countWays(arr) = countWays(left) * countWays(right) * combinations(N, X).left: Contains all the elements in the left subtree(Elements which are lesser than the root) right: Contains all the elements in the right subtree(Elements which are greater than the root) N = Total number of elements in arr[] X = Total number of elements in left subtree. Follow the steps below to solve the problem: Fix the root node of BST, and store the elements of the left subtree(Elements which are lesser than arr[0]), say ctLeft[], and store the elements of the right subtree(Elements which are greater than arr[0]), say ctRight[].To generate identical BST, maintain the relative order within the elements of left subtree and the right subtree.Calculate the number of ways to rearrange the array to generate BST using the above-mentioned recurrence relation. Fix the root node of BST, and store the elements of the left subtree(Elements which are lesser than arr[0]), say ctLeft[], and store the elements of the right subtree(Elements which are greater than arr[0]), say ctRight[]. To generate identical BST, maintain the relative order within the elements of left subtree and the right subtree. Calculate the number of ways to rearrange the array to generate BST using the above-mentioned recurrence relation. C++ Java Python3 C# Javascript // C++ program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to precompute the// factorial of 1 to Nvoid calculateFact(int fact[], int N){ fact[0] = 1; for (long long int i = 1; i < N; i++) { fact[i] = fact[i - 1] * i; }} // Function to get the value of nCrint nCr(int fact[], int N, int R){ if (R > N) return 0; // nCr= fact(n)/(fact(r)*fact(n-r)) int res = fact[N] / fact[R]; res /= fact[N - R]; return res;} // Function to count the number of ways// to rearrange the array to obtain same BSTint countWays(vector<int>& arr, int fact[]){ // Store the size of the array int N = arr.size(); // Base case if (N <= 2) { return 1; } // Store the elements of the // left subtree of BST vector<int> leftSubTree; // Store the elements of the // right subtree of BST vector<int> rightSubTree; // Store the root node int root = arr[0]; for (int i = 1; i < N; i++) { // Push all the elements // of the left subtree if (arr[i] < root) { leftSubTree.push_back( arr[i]); } // Push all the elements // of the right subtree else { rightSubTree.push_back( arr[i]); } } // Store the size of leftSubTree int N1 = leftSubTree.size(); // Store the size of rightSubTree int N2 = rightSubTree.size(); // Recurrence relation int countLeft = countWays(leftSubTree, fact); int countRight = countWays(rightSubTree, fact); return nCr(fact, N - 1, N1) * countLeft * countRight;} // Driver Codeint main(){ vector<int> arr; arr = { 3, 4, 5, 1, 2 }; // Store the size of arr int N = arr.size(); // Store the factorial up to N int fact[N]; // Precompute the factorial up to N calculateFact(fact, N); cout << countWays(arr, fact); return 0;} // Java program to implement// the above approachimport java.util.*; class GFG{ // Function to precompute the// factorial of 1 to Nstatic void calculateFact(int fact[], int N){ fact[0] = 1; for(int i = 1; i < N; i++) { fact[i] = fact[i - 1] * i; }} // Function to get the value of nCrstatic int nCr(int fact[], int N, int R){ if (R > N) return 0; // nCr= fact(n)/(fact(r)*fact(n-r)) int res = fact[N] / fact[R]; res /= fact[N - R]; return res;} // Function to count the number of ways// to rearrange the array to obtain same BSTstatic int countWays(Vector<Integer> arr, int fact[]){ // Store the size of the array int N = arr.size(); // Base case if (N <= 2) { return 1; } // Store the elements of the // left subtree of BST Vector<Integer> leftSubTree = new Vector<Integer>(); // Store the elements of the // right subtree of BST Vector<Integer> rightSubTree = new Vector<Integer>(); // Store the root node int root = arr.get(0); for(int i = 1; i < N; i++) { // Push all the elements // of the left subtree if (arr.get(i) < root) { leftSubTree.add(arr.get(i)); } // Push all the elements // of the right subtree else { rightSubTree.add(arr.get(i)); } } // Store the size of leftSubTree int N1 = leftSubTree.size(); // Store the size of rightSubTree int N2 = rightSubTree.size(); // Recurrence relation int countLeft = countWays(leftSubTree, fact); int countRight = countWays(rightSubTree, fact); return nCr(fact, N - 1, N1) * countLeft * countRight;} // Driver Codepublic static void main(String[] args){ int []a = { 3, 4, 5, 1, 2 }; Vector<Integer> arr = new Vector<Integer>(); for(int i : a) arr.add(i); // Store the size of arr int N = a.length; // Store the factorial up to N int []fact = new int[N]; // Precompute the factorial up to N calculateFact(fact, N); System.out.print(countWays(arr, fact));}} // This code is contributed by Amit Katiyar # Python3 program to implement# the above approach # Function to precompute the# factorial of 1 to Ndef calculateFact(fact: list, N: int) -> None: fact[0] = 1 for i in range(1, N): fact[i] = fact[i - 1] * i # Function to get the value of nCrdef nCr(fact: list, N: int, R: int) -> int: if (R > N): return 0 # nCr= fact(n)/(fact(r)*fact(n-r)) res = fact[N] // fact[R] res //= fact[N - R] return res # Function to count the number of ways# to rearrange the array to obtain same BSTdef countWays(arr: list, fact: list) -> int: # Store the size of the array N = len(arr) # Base case if (N <= 2): return 1 # Store the elements of the # left subtree of BST leftSubTree = [] # Store the elements of the # right subtree of BST rightSubTree = [] # Store the root node root = arr[0] for i in range(1, N): # Push all the elements # of the left subtree if (arr[i] < root): leftSubTree.append(arr[i]) # Push all the elements # of the right subtree else: rightSubTree.append(arr[i]) # Store the size of leftSubTree N1 = len(leftSubTree) # Store the size of rightSubTree N2 = len(rightSubTree) # Recurrence relation countLeft = countWays(leftSubTree, fact) countRight = countWays(rightSubTree, fact) return (nCr(fact, N - 1, N1) * countLeft * countRight) # Driver Codeif __name__ == '__main__': arr = [ 3, 4, 5, 1, 2 ] # Store the size of arr N = len(arr) # Store the factorial up to N fact = [0] * N # Precompute the factorial up to N calculateFact(fact, N) print(countWays(arr, fact)) # This code is contributed by sanjeev2552 // C# program to implement// the above approachusing System;using System.Collections.Generic; class GFG{ // Function to precompute the// factorial of 1 to Nstatic void calculateFact(int []fact, int N){ fact[0] = 1; for(int i = 1; i < N; i++) { fact[i] = fact[i - 1] * i; }} // Function to get the value of nCrstatic int nCr(int []fact, int N, int R){ if (R > N) return 0; // nCr= fact(n)/(fact(r)*fact(n-r)) int res = fact[N] / fact[R]; res /= fact[N - R]; return res;} // Function to count the number of ways// to rearrange the array to obtain same BSTstatic int countWays(List<int> arr, int []fact){ // Store the size of the array int N = arr.Count; // Base case if (N <= 2) { return 1; } // Store the elements of the // left subtree of BST List<int> leftSubTree = new List<int>(); // Store the elements of the // right subtree of BST List<int> rightSubTree = new List<int>(); // Store the root node int root = arr[0]; for(int i = 1; i < N; i++) { // Push all the elements // of the left subtree if (arr[i] < root) { leftSubTree.Add(arr[i]); } // Push all the elements // of the right subtree else { rightSubTree.Add(arr[i]); } } // Store the size of leftSubTree int N1 = leftSubTree.Count; // Store the size of rightSubTree int N2 = rightSubTree.Count; // Recurrence relation int countLeft = countWays(leftSubTree, fact); int countRight = countWays(rightSubTree, fact); return nCr(fact, N - 1, N1) * countLeft * countRight;} // Driver Codepublic static void Main(String[] args){ int []a = { 3, 4, 5, 1, 2 }; List<int> arr = new List<int>(); foreach(int i in a) arr.Add(i); // Store the size of arr int N = a.Length; // Store the factorial up to N int []fact = new int[N]; // Precompute the factorial up to N calculateFact(fact, N); Console.Write(countWays(arr, fact));}} // This code is contributed by Amit Katiyar <script> // JavaScript program to implement// the above approach // Function to precompute the// factorial of 1 to Nfunction calculateFact(fact, N){ fact[0] = 1; for (var i = 1; i < N; i++) { fact[i] = fact[i - 1] * i; }} // Function to get the value of nCrfunction nCr(fact, N, R){ if (R > N) return 0; // nCr= fact(n)/(fact(r)*fact(n-r)) var res = parseInt(fact[N] / fact[R]); res = parseInt(res / fact[N - R]); return res;} // Function to count the number of ways// to rearrange the array to obtain same BSTfunction countWays(arr, fact){ // Store the size of the array var N = arr.length; // Base case if (N <= 2) { return 1; } // Store the elements of the // left subtree of BST var leftSubTree = []; // Store the elements of the // right subtree of BST var rightSubTree = []; // Store the root node var root = arr[0]; for (var i = 1; i < N; i++) { // Push all the elements // of the left subtree if (arr[i] < root) { leftSubTree.push( arr[i]); } // Push all the elements // of the right subtree else { rightSubTree.push( arr[i]); } } // Store the size of leftSubTree var N1 = leftSubTree.length; // Store the size of rightSubTree var N2 = rightSubTree.length; // Recurrence relation var countLeft = countWays(leftSubTree, fact); var countRight = countWays(rightSubTree, fact); return nCr(fact, N - 1, N1) * countLeft * countRight;} // Driver Code var arr = [];arr = [3, 4, 5, 1, 2]; // Store the size of arrvar N = arr.length; // Store the factorial up to Nvar fact = Array(N); // Precompute the factorial up to NcalculateFact(fact, N);document.write( countWays(arr, fact)); </script> 6 Time Complexity: O(N2)Auxiliary Space: O(N) amit143katiyar sanjeev2552 rutvik_56 kushjmehta binomial coefficient factorial Permutation and Combination Arrays Binary Search Tree Combinatorial Mathematical Recursion Tree Arrays Mathematical Recursion Combinatorial Binary Search Tree Tree factorial 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 Multidimensional Arrays in Java Introduction to Arrays Linear Search Binary Search Tree | Set 1 (Search and Insertion) AVL Tree | Set 1 (Insertion) Binary Search Tree | Set 2 (Delete) A program to check if a binary tree is BST or not Sorted Array to Balanced BST
[ { "code": null, "e": 24990, "s": 24962, "text": "\n18 Aug, 2021" }, { "code": null, "e": 25247, "s": 24990, "text": "Given an array, arr[] of size N consisting of elements from the range [1, N], that represents the order, in which the elements are inserted into a Binary Search Tree, the task is to count the number of ways to rearrange the given array to get the same BST." }, { "code": null, "e": 25257, "s": 25247, "text": "Examples:" }, { "code": null, "e": 25504, "s": 25257, "text": "Input: arr[ ] ={3, 4, 5, 1, 2}Output: 6Explanation :The permutations of the array which represent the same BST are:{{3, 4, 5, 1, 2}, {3, 1, 2, 4, 5}, {3, 1, 4, 2, 5}, {3, 1, 4, 5, 2}, {3, 4, 1, 2, 5}, {3, 4, 1, 5, 2}}. Therefore, the output is 6." }, { "code": null, "e": 25547, "s": 25504, "text": "Input: arr[ ] ={2, 1, 6, 5, 4, 3}Output: 5" }, { "code": null, "e": 25869, "s": 25547, "text": "Approach: The idea is to first fix the root node and then recursively count the number of ways to rearrange the elements of the left subtree and the elements of the right subtree in such a way that the relative order within the elements of the left subtree and right subtree must be same. Here is the recurrence relation:" }, { "code": null, "e": 26215, "s": 25869, "text": "countWays(arr) = countWays(left) * countWays(right) * combinations(N, X).left: Contains all the elements in the left subtree(Elements which are lesser than the root) right: Contains all the elements in the right subtree(Elements which are greater than the root) N = Total number of elements in arr[] X = Total number of elements in left subtree." }, { "code": null, "e": 26260, "s": 26215, "text": "Follow the steps below to solve the problem:" }, { "code": null, "e": 26710, "s": 26260, "text": "Fix the root node of BST, and store the elements of the left subtree(Elements which are lesser than arr[0]), say ctLeft[], and store the elements of the right subtree(Elements which are greater than arr[0]), say ctRight[].To generate identical BST, maintain the relative order within the elements of left subtree and the right subtree.Calculate the number of ways to rearrange the array to generate BST using the above-mentioned recurrence relation." }, { "code": null, "e": 26933, "s": 26710, "text": "Fix the root node of BST, and store the elements of the left subtree(Elements which are lesser than arr[0]), say ctLeft[], and store the elements of the right subtree(Elements which are greater than arr[0]), say ctRight[]." }, { "code": null, "e": 27047, "s": 26933, "text": "To generate identical BST, maintain the relative order within the elements of left subtree and the right subtree." }, { "code": null, "e": 27162, "s": 27047, "text": "Calculate the number of ways to rearrange the array to generate BST using the above-mentioned recurrence relation." }, { "code": null, "e": 27166, "s": 27162, "text": "C++" }, { "code": null, "e": 27171, "s": 27166, "text": "Java" }, { "code": null, "e": 27179, "s": 27171, "text": "Python3" }, { "code": null, "e": 27182, "s": 27179, "text": "C#" }, { "code": null, "e": 27193, "s": 27182, "text": "Javascript" }, { "code": "// C++ program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to precompute the// factorial of 1 to Nvoid calculateFact(int fact[], int N){ fact[0] = 1; for (long long int i = 1; i < N; i++) { fact[i] = fact[i - 1] * i; }} // Function to get the value of nCrint nCr(int fact[], int N, int R){ if (R > N) return 0; // nCr= fact(n)/(fact(r)*fact(n-r)) int res = fact[N] / fact[R]; res /= fact[N - R]; return res;} // Function to count the number of ways// to rearrange the array to obtain same BSTint countWays(vector<int>& arr, int fact[]){ // Store the size of the array int N = arr.size(); // Base case if (N <= 2) { return 1; } // Store the elements of the // left subtree of BST vector<int> leftSubTree; // Store the elements of the // right subtree of BST vector<int> rightSubTree; // Store the root node int root = arr[0]; for (int i = 1; i < N; i++) { // Push all the elements // of the left subtree if (arr[i] < root) { leftSubTree.push_back( arr[i]); } // Push all the elements // of the right subtree else { rightSubTree.push_back( arr[i]); } } // Store the size of leftSubTree int N1 = leftSubTree.size(); // Store the size of rightSubTree int N2 = rightSubTree.size(); // Recurrence relation int countLeft = countWays(leftSubTree, fact); int countRight = countWays(rightSubTree, fact); return nCr(fact, N - 1, N1) * countLeft * countRight;} // Driver Codeint main(){ vector<int> arr; arr = { 3, 4, 5, 1, 2 }; // Store the size of arr int N = arr.size(); // Store the factorial up to N int fact[N]; // Precompute the factorial up to N calculateFact(fact, N); cout << countWays(arr, fact); return 0;}", "e": 29180, "s": 27193, "text": null }, { "code": "// Java program to implement// the above approachimport java.util.*; class GFG{ // Function to precompute the// factorial of 1 to Nstatic void calculateFact(int fact[], int N){ fact[0] = 1; for(int i = 1; i < N; i++) { fact[i] = fact[i - 1] * i; }} // Function to get the value of nCrstatic int nCr(int fact[], int N, int R){ if (R > N) return 0; // nCr= fact(n)/(fact(r)*fact(n-r)) int res = fact[N] / fact[R]; res /= fact[N - R]; return res;} // Function to count the number of ways// to rearrange the array to obtain same BSTstatic int countWays(Vector<Integer> arr, int fact[]){ // Store the size of the array int N = arr.size(); // Base case if (N <= 2) { return 1; } // Store the elements of the // left subtree of BST Vector<Integer> leftSubTree = new Vector<Integer>(); // Store the elements of the // right subtree of BST Vector<Integer> rightSubTree = new Vector<Integer>(); // Store the root node int root = arr.get(0); for(int i = 1; i < N; i++) { // Push all the elements // of the left subtree if (arr.get(i) < root) { leftSubTree.add(arr.get(i)); } // Push all the elements // of the right subtree else { rightSubTree.add(arr.get(i)); } } // Store the size of leftSubTree int N1 = leftSubTree.size(); // Store the size of rightSubTree int N2 = rightSubTree.size(); // Recurrence relation int countLeft = countWays(leftSubTree, fact); int countRight = countWays(rightSubTree, fact); return nCr(fact, N - 1, N1) * countLeft * countRight;} // Driver Codepublic static void main(String[] args){ int []a = { 3, 4, 5, 1, 2 }; Vector<Integer> arr = new Vector<Integer>(); for(int i : a) arr.add(i); // Store the size of arr int N = a.length; // Store the factorial up to N int []fact = new int[N]; // Precompute the factorial up to N calculateFact(fact, N); System.out.print(countWays(arr, fact));}} // This code is contributed by Amit Katiyar", "e": 31418, "s": 29180, "text": null }, { "code": "# Python3 program to implement# the above approach # Function to precompute the# factorial of 1 to Ndef calculateFact(fact: list, N: int) -> None: fact[0] = 1 for i in range(1, N): fact[i] = fact[i - 1] * i # Function to get the value of nCrdef nCr(fact: list, N: int, R: int) -> int: if (R > N): return 0 # nCr= fact(n)/(fact(r)*fact(n-r)) res = fact[N] // fact[R] res //= fact[N - R] return res # Function to count the number of ways# to rearrange the array to obtain same BSTdef countWays(arr: list, fact: list) -> int: # Store the size of the array N = len(arr) # Base case if (N <= 2): return 1 # Store the elements of the # left subtree of BST leftSubTree = [] # Store the elements of the # right subtree of BST rightSubTree = [] # Store the root node root = arr[0] for i in range(1, N): # Push all the elements # of the left subtree if (arr[i] < root): leftSubTree.append(arr[i]) # Push all the elements # of the right subtree else: rightSubTree.append(arr[i]) # Store the size of leftSubTree N1 = len(leftSubTree) # Store the size of rightSubTree N2 = len(rightSubTree) # Recurrence relation countLeft = countWays(leftSubTree, fact) countRight = countWays(rightSubTree, fact) return (nCr(fact, N - 1, N1) * countLeft * countRight) # Driver Codeif __name__ == '__main__': arr = [ 3, 4, 5, 1, 2 ] # Store the size of arr N = len(arr) # Store the factorial up to N fact = [0] * N # Precompute the factorial up to N calculateFact(fact, N) print(countWays(arr, fact)) # This code is contributed by sanjeev2552", "e": 33160, "s": 31418, "text": null }, { "code": "// C# program to implement// the above approachusing System;using System.Collections.Generic; class GFG{ // Function to precompute the// factorial of 1 to Nstatic void calculateFact(int []fact, int N){ fact[0] = 1; for(int i = 1; i < N; i++) { fact[i] = fact[i - 1] * i; }} // Function to get the value of nCrstatic int nCr(int []fact, int N, int R){ if (R > N) return 0; // nCr= fact(n)/(fact(r)*fact(n-r)) int res = fact[N] / fact[R]; res /= fact[N - R]; return res;} // Function to count the number of ways// to rearrange the array to obtain same BSTstatic int countWays(List<int> arr, int []fact){ // Store the size of the array int N = arr.Count; // Base case if (N <= 2) { return 1; } // Store the elements of the // left subtree of BST List<int> leftSubTree = new List<int>(); // Store the elements of the // right subtree of BST List<int> rightSubTree = new List<int>(); // Store the root node int root = arr[0]; for(int i = 1; i < N; i++) { // Push all the elements // of the left subtree if (arr[i] < root) { leftSubTree.Add(arr[i]); } // Push all the elements // of the right subtree else { rightSubTree.Add(arr[i]); } } // Store the size of leftSubTree int N1 = leftSubTree.Count; // Store the size of rightSubTree int N2 = rightSubTree.Count; // Recurrence relation int countLeft = countWays(leftSubTree, fact); int countRight = countWays(rightSubTree, fact); return nCr(fact, N - 1, N1) * countLeft * countRight;} // Driver Codepublic static void Main(String[] args){ int []a = { 3, 4, 5, 1, 2 }; List<int> arr = new List<int>(); foreach(int i in a) arr.Add(i); // Store the size of arr int N = a.Length; // Store the factorial up to N int []fact = new int[N]; // Precompute the factorial up to N calculateFact(fact, N); Console.Write(countWays(arr, fact));}} // This code is contributed by Amit Katiyar", "e": 35364, "s": 33160, "text": null }, { "code": "<script> // JavaScript program to implement// the above approach // Function to precompute the// factorial of 1 to Nfunction calculateFact(fact, N){ fact[0] = 1; for (var i = 1; i < N; i++) { fact[i] = fact[i - 1] * i; }} // Function to get the value of nCrfunction nCr(fact, N, R){ if (R > N) return 0; // nCr= fact(n)/(fact(r)*fact(n-r)) var res = parseInt(fact[N] / fact[R]); res = parseInt(res / fact[N - R]); return res;} // Function to count the number of ways// to rearrange the array to obtain same BSTfunction countWays(arr, fact){ // Store the size of the array var N = arr.length; // Base case if (N <= 2) { return 1; } // Store the elements of the // left subtree of BST var leftSubTree = []; // Store the elements of the // right subtree of BST var rightSubTree = []; // Store the root node var root = arr[0]; for (var i = 1; i < N; i++) { // Push all the elements // of the left subtree if (arr[i] < root) { leftSubTree.push( arr[i]); } // Push all the elements // of the right subtree else { rightSubTree.push( arr[i]); } } // Store the size of leftSubTree var N1 = leftSubTree.length; // Store the size of rightSubTree var N2 = rightSubTree.length; // Recurrence relation var countLeft = countWays(leftSubTree, fact); var countRight = countWays(rightSubTree, fact); return nCr(fact, N - 1, N1) * countLeft * countRight;} // Driver Code var arr = [];arr = [3, 4, 5, 1, 2]; // Store the size of arrvar N = arr.length; // Store the factorial up to Nvar fact = Array(N); // Precompute the factorial up to NcalculateFact(fact, N);document.write( countWays(arr, fact)); </script>", "e": 37251, "s": 35364, "text": null }, { "code": null, "e": 37253, "s": 37251, "text": "6" }, { "code": null, "e": 37297, "s": 37253, "text": "Time Complexity: O(N2)Auxiliary Space: O(N)" }, { "code": null, "e": 37312, "s": 37297, "text": "amit143katiyar" }, { "code": null, "e": 37324, "s": 37312, "text": "sanjeev2552" }, { "code": null, "e": 37334, "s": 37324, "text": "rutvik_56" }, { "code": null, "e": 37345, "s": 37334, "text": "kushjmehta" }, { "code": null, "e": 37366, "s": 37345, "text": "binomial coefficient" }, { "code": null, "e": 37376, "s": 37366, "text": "factorial" }, { "code": null, "e": 37404, "s": 37376, "text": "Permutation and Combination" }, { "code": null, "e": 37411, "s": 37404, "text": "Arrays" }, { "code": null, "e": 37430, "s": 37411, "text": "Binary Search Tree" }, { "code": null, "e": 37444, "s": 37430, "text": "Combinatorial" }, { "code": null, "e": 37457, "s": 37444, "text": "Mathematical" }, { "code": null, "e": 37467, "s": 37457, "text": "Recursion" }, { "code": null, "e": 37472, "s": 37467, "text": "Tree" }, { "code": null, "e": 37479, "s": 37472, "text": "Arrays" }, { "code": null, "e": 37492, "s": 37479, "text": "Mathematical" }, { "code": null, "e": 37502, "s": 37492, "text": "Recursion" }, { "code": null, "e": 37516, "s": 37502, "text": "Combinatorial" }, { "code": null, "e": 37535, "s": 37516, "text": "Binary Search Tree" }, { "code": null, "e": 37540, "s": 37535, "text": "Tree" }, { "code": null, "e": 37550, "s": 37540, "text": "factorial" }, { "code": null, "e": 37648, "s": 37550, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37657, "s": 37648, "text": "Comments" }, { "code": null, "e": 37670, "s": 37657, "text": "Old Comments" }, { "code": null, "e": 37718, "s": 37670, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 37762, "s": 37718, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 37794, "s": 37762, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 37817, "s": 37794, "text": "Introduction to Arrays" }, { "code": null, "e": 37831, "s": 37817, "text": "Linear Search" }, { "code": null, "e": 37881, "s": 37831, "text": "Binary Search Tree | Set 1 (Search and Insertion)" }, { "code": null, "e": 37910, "s": 37881, "text": "AVL Tree | Set 1 (Insertion)" }, { "code": null, "e": 37946, "s": 37910, "text": "Binary Search Tree | Set 2 (Delete)" }, { "code": null, "e": 37996, "s": 37946, "text": "A program to check if a binary tree is BST or not" } ]
How to generate Narrowband and Wideband FM signal using GNU-Octave? - GeeksforGeeks
09 Jul, 2021 In this article, we are going to discuss how to generate the Narrowband and Wideband FM signal using MATLAB. Frequency Modulation popularly known as FM is a kind of analog modulation technique in which the frequency of the high-frequency carrier signal is varied according to the amplitude of the modulating (message) signal while the amplitude and the phase of the carrier signal remain constant or unchanged. where; fm = FM signal, Ac = Amplitude of carrier signal, fc = Carrier Frequency, fm = Modulating Frequency, t = time, & b = Frequency modulation index. FM signals are classified into two broad categories depending upon the value of the frequency modulation index (b): Narrowband FM Wideband FM In general, the FM signals which have their frequency modulation index (b<1) less than unity are called Narrowband FM signals. Usually, narrowband FM signals are used in low-cost two-way radio communication systems like a walkie-talkie. To generate the narrowband FM signal, we will be using the standard equation of the FM signal and pass the value of the frequency modulation index (b) less than unity. Example: Matlab % MATLAB code to generate the narrowband FM signalclc; % Clears the Command Windowclear all; % Clears the Workspaceclose all; % Closes all the Windows opened by the program % Time sampling where Step Size = 0.001t = 0:0.001:1;fm = 20; % frequency of the Message signalfc = 250; % frequency of the Carrier signal % Take the user input for the Frequency Modulation Index (b)% (b) must be less than 1b = input("Enter the value of b (<1): "); % Define the Message signal% here its a Sine wavemsg = sin(2*pi*fm*t); % Define the Carrier signal% here it is a Cosine wavecrr = cos(2*pi*fc*t); % Narrowband FM Signal generationnb_fm = cos((2*pi*fc*t)+(b*sin(2*pi*fm*t))); % Plot all the three signalsfigure('Name','Narrowband FM Signal Generation'); % Message Signalsubplot(3,1,1);plot(t, msg, 'b', 'Linewidth', 1.5);title('Message signal');xlabel('Time')ylabel('Amplitude')grid on; % Carrier Signalsubplot(3,1,2);plot(t, crr, 'r', 'Linewidth', 1.5);title('Carrier signal');xlabel('Time')ylabel('Amplitude')grid on; % Narrowband FM Signalsubplot(3,1,3);plot(t, nb_fm, 'g', 'Linewidth', 1.5);title('Narrowband FM signal');xlabel('Time')ylabel('Amplitude')grid on; Output: Enter the value of b (<1): 0.55 Output: Narrowband FM Signal Generation Unlike the narrowband FM signals, wideband FM signals are the FM signals whose frequency modulation index (b>1) is greater than unity. Normally, wideband signals are used for high-quality broadcast transmission. To generate the wideband FM signal, we will be using the standard equation of the FM signal and pass the value of the frequency modulation index (b) greater than unity. Example: Matlab % MATLAB code to generate the wideband FM signalclc; % Clears the Command Windowclear all; % Clears the Workspaceclose all; % Closes all the Windows opened by the program % Time sampling where Step Size = 0.001t = 0:0.001:1; fm = 20; % frequency of the Message signalfc = 250; % frequency of the Carrier signal % Take the user input for the Frequency Modulation Index (b)% (b) must be greater than 1b = input("Enter the value of b (>1): "); % Define the Message signal% here its a Sine wavemsg = sin(2*pi*fm*t); % Define the Carrier signal% here it is a Cosine wavecrr = cos(2*pi*fc*t); % Wideband FM Signal generationwb_fm = cos((2*pi*fc*t)+(b*sin(2*pi*fm*t))); % Plot all the three signalsfigure('Name','Wideband FM Signal Generation'); % Message Signalsubplot(3,1,1);plot(t, msg, 'b', 'Linewidth', 1.5);title('Message signal');xlabel('Time')ylabel('Amplitude')grid on; % Carrier Signalsubplot(3,1,2);plot(t, crr, 'r', 'Linewidth', 1.5);title('Carrier signal');xlabel('Time')ylabel('Amplitude')grid on; % Wideband FM Signalsubplot(3,1,3);plot(t, wb_fm, 'g', 'Linewidth', 1.5);title('Wideband FM signal');xlabel('Time')ylabel('Amplitude')grid on; Output: Enter the value of b (>1): 2.5 Output: Wideband FM Signal Generation MATLAB MATLAB-programs MATLAB Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Remove Noise from Digital Image in Frequency Domain Using MATLAB? MRI Image Segmentation in MATLAB How to Solve Histogram Equalization Numerical Problem in MATLAB? How to Normalize a Histogram in MATLAB? Laplace Transform in MATLAB Laplacian of Gaussian Filter in MATLAB Forward and Inverse Fourier Transform of an Image in MATLAB Adaptive Histogram Equalization in Image Processing Using MATLAB How to Remove Salt and Pepper Noise from Image Using MATLAB? Boundary Extraction of image using MATLAB
[ { "code": null, "e": 24255, "s": 24227, "text": "\n09 Jul, 2021" }, { "code": null, "e": 24365, "s": 24255, "text": "In this article, we are going to discuss how to generate the Narrowband and Wideband FM signal using MATLAB." }, { "code": null, "e": 24667, "s": 24365, "text": "Frequency Modulation popularly known as FM is a kind of analog modulation technique in which the frequency of the high-frequency carrier signal is varied according to the amplitude of the modulating (message) signal while the amplitude and the phase of the carrier signal remain constant or unchanged." }, { "code": null, "e": 24692, "s": 24667, "text": "where; fm = FM signal, " }, { "code": null, "e": 24727, "s": 24692, "text": "Ac = Amplitude of carrier signal, " }, { "code": null, "e": 24751, "s": 24727, "text": "fc = Carrier Frequency," }, { "code": null, "e": 24779, "s": 24751, "text": " fm = Modulating Frequency," }, { "code": null, "e": 24825, "s": 24779, "text": " t = time, & b = Frequency modulation index." }, { "code": null, "e": 24941, "s": 24825, "text": "FM signals are classified into two broad categories depending upon the value of the frequency modulation index (b):" }, { "code": null, "e": 24955, "s": 24941, "text": "Narrowband FM" }, { "code": null, "e": 24967, "s": 24955, "text": "Wideband FM" }, { "code": null, "e": 25204, "s": 24967, "text": "In general, the FM signals which have their frequency modulation index (b<1) less than unity are called Narrowband FM signals. Usually, narrowband FM signals are used in low-cost two-way radio communication systems like a walkie-talkie." }, { "code": null, "e": 25373, "s": 25204, "text": "To generate the narrowband FM signal, we will be using the standard equation of the FM signal and pass the value of the frequency modulation index (b) less than unity. " }, { "code": null, "e": 25382, "s": 25373, "text": "Example:" }, { "code": null, "e": 25389, "s": 25382, "text": "Matlab" }, { "code": "% MATLAB code to generate the narrowband FM signalclc; % Clears the Command Windowclear all; % Clears the Workspaceclose all; % Closes all the Windows opened by the program % Time sampling where Step Size = 0.001t = 0:0.001:1;fm = 20; % frequency of the Message signalfc = 250; % frequency of the Carrier signal % Take the user input for the Frequency Modulation Index (b)% (b) must be less than 1b = input(\"Enter the value of b (<1): \"); % Define the Message signal% here its a Sine wavemsg = sin(2*pi*fm*t); % Define the Carrier signal% here it is a Cosine wavecrr = cos(2*pi*fc*t); % Narrowband FM Signal generationnb_fm = cos((2*pi*fc*t)+(b*sin(2*pi*fm*t))); % Plot all the three signalsfigure('Name','Narrowband FM Signal Generation'); % Message Signalsubplot(3,1,1);plot(t, msg, 'b', 'Linewidth', 1.5);title('Message signal');xlabel('Time')ylabel('Amplitude')grid on; % Carrier Signalsubplot(3,1,2);plot(t, crr, 'r', 'Linewidth', 1.5);title('Carrier signal');xlabel('Time')ylabel('Amplitude')grid on; % Narrowband FM Signalsubplot(3,1,3);plot(t, nb_fm, 'g', 'Linewidth', 1.5);title('Narrowband FM signal');xlabel('Time')ylabel('Amplitude')grid on;", "e": 26559, "s": 25389, "text": null }, { "code": null, "e": 26567, "s": 26559, "text": "Output:" }, { "code": null, "e": 26599, "s": 26567, "text": "Enter the value of b (<1): 0.55" }, { "code": null, "e": 26639, "s": 26599, "text": "Output: Narrowband FM Signal Generation" }, { "code": null, "e": 26851, "s": 26639, "text": "Unlike the narrowband FM signals, wideband FM signals are the FM signals whose frequency modulation index (b>1) is greater than unity. Normally, wideband signals are used for high-quality broadcast transmission." }, { "code": null, "e": 27021, "s": 26851, "text": "To generate the wideband FM signal, we will be using the standard equation of the FM signal and pass the value of the frequency modulation index (b) greater than unity. " }, { "code": null, "e": 27030, "s": 27021, "text": "Example:" }, { "code": null, "e": 27037, "s": 27030, "text": "Matlab" }, { "code": "% MATLAB code to generate the wideband FM signalclc; % Clears the Command Windowclear all; % Clears the Workspaceclose all; % Closes all the Windows opened by the program % Time sampling where Step Size = 0.001t = 0:0.001:1; fm = 20; % frequency of the Message signalfc = 250; % frequency of the Carrier signal % Take the user input for the Frequency Modulation Index (b)% (b) must be greater than 1b = input(\"Enter the value of b (>1): \"); % Define the Message signal% here its a Sine wavemsg = sin(2*pi*fm*t); % Define the Carrier signal% here it is a Cosine wavecrr = cos(2*pi*fc*t); % Wideband FM Signal generationwb_fm = cos((2*pi*fc*t)+(b*sin(2*pi*fm*t))); % Plot all the three signalsfigure('Name','Wideband FM Signal Generation'); % Message Signalsubplot(3,1,1);plot(t, msg, 'b', 'Linewidth', 1.5);title('Message signal');xlabel('Time')ylabel('Amplitude')grid on; % Carrier Signalsubplot(3,1,2);plot(t, crr, 'r', 'Linewidth', 1.5);title('Carrier signal');xlabel('Time')ylabel('Amplitude')grid on; % Wideband FM Signalsubplot(3,1,3);plot(t, wb_fm, 'g', 'Linewidth', 1.5);title('Wideband FM signal');xlabel('Time')ylabel('Amplitude')grid on;", "e": 28202, "s": 27037, "text": null }, { "code": null, "e": 28210, "s": 28202, "text": "Output:" }, { "code": null, "e": 28241, "s": 28210, "text": "Enter the value of b (>1): 2.5" }, { "code": null, "e": 28279, "s": 28241, "text": "Output: Wideband FM Signal Generation" }, { "code": null, "e": 28286, "s": 28279, "text": "MATLAB" }, { "code": null, "e": 28302, "s": 28286, "text": "MATLAB-programs" }, { "code": null, "e": 28309, "s": 28302, "text": "MATLAB" }, { "code": null, "e": 28407, "s": 28309, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28416, "s": 28407, "text": "Comments" }, { "code": null, "e": 28429, "s": 28416, "text": "Old Comments" }, { "code": null, "e": 28502, "s": 28429, "text": "How to Remove Noise from Digital Image in Frequency Domain Using MATLAB?" }, { "code": null, "e": 28535, "s": 28502, "text": "MRI Image Segmentation in MATLAB" }, { "code": null, "e": 28600, "s": 28535, "text": "How to Solve Histogram Equalization Numerical Problem in MATLAB?" }, { "code": null, "e": 28640, "s": 28600, "text": "How to Normalize a Histogram in MATLAB?" }, { "code": null, "e": 28668, "s": 28640, "text": "Laplace Transform in MATLAB" }, { "code": null, "e": 28707, "s": 28668, "text": "Laplacian of Gaussian Filter in MATLAB" }, { "code": null, "e": 28767, "s": 28707, "text": "Forward and Inverse Fourier Transform of an Image in MATLAB" }, { "code": null, "e": 28832, "s": 28767, "text": "Adaptive Histogram Equalization in Image Processing Using MATLAB" }, { "code": null, "e": 28893, "s": 28832, "text": "How to Remove Salt and Pepper Noise from Image Using MATLAB?" } ]
Transpose a matrix in C#
Transpose of a matrix flips the matrix over its diagonal and this brings the row elements on the column and column elements on the row. For example − Matrix before Transpose: 123 456 789 Matrix after Transpose: 147 258 369 Let us see an example in C# to achieve transpose of a matrix − using System; public class Demo { public static void Main() { int i, j, m, n; int[, ] arr1 = new int[30, 30]; int[, ] arr2 = new int[30, 30]; Console.Write("\nEnter the number of rows and columns of the matrix :\n"); Console.Write("Rows entered = "); m = Convert.ToInt32(Console.ReadLine()); Console.Write("Columns entered = "); n = Convert.ToInt32(Console.ReadLine()); Console.Write("Set elements in the matrix...\n"); for (i = 0; i < m; i++) { for (j = 0; j < n; j++) { Console.Write("\n [{0}],[{1}] : ", i, j); arr1[i, j] = Convert.ToInt32(Console.ReadLine()); } } Console.Write("\n\nMatrix before Transpose:\n"); for (i = 0; i < m; i++) { Console.Write("\n"); for (j = 0; j < n; j++) Console.Write("{0}\t", arr1[i, j]); } for (i = 0; i < m; i++) { for (j = 0; j < n; j++) { arr2[j, i] = arr1[i, j]; } } Console.Write("\n\nMatrix after Transpose: "); for (i = 0; i < m; i++) { Console.Write("\n"); for (j = 0; j < n; j++) { Console.Write("{0}\t", arr2[i, j]); } } Console.Write("\n\n"); } } The following result will be produced on running the above program. Here, values from the user are to be entered for number of rows and columns, and the elements of the matrix − Enter the number of rows and columns of the matrix :3 3 Rows entered = 3 Columns entered 3 Set elements in the matrix... [0],[0] : 1 [0],[1] : 2 [0],[2] : 3 [1],[0] : 4 [1],[1] : 5 [1],[2] : 6 [2],[0] : 7 [2],[1] : 8 [2],[2] : 9 Matrix before Transpose: 123 456 789 Matrix after Transpose: 147 258 369
[ { "code": null, "e": 1198, "s": 1062, "text": "Transpose of a matrix flips the matrix over its diagonal and this brings the row elements on the column and column elements on the row." }, { "code": null, "e": 1212, "s": 1198, "text": "For example −" }, { "code": null, "e": 1287, "s": 1212, "text": "Matrix before Transpose:\n\n123\n456\n789\n\nMatrix after Transpose:\n147\n258\n369" }, { "code": null, "e": 1350, "s": 1287, "text": "Let us see an example in C# to achieve transpose of a matrix −" }, { "code": null, "e": 2615, "s": 1350, "text": "using System;\npublic class Demo {\n public static void Main() {\n int i, j, m, n;\n int[, ] arr1 = new int[30, 30];\n int[, ] arr2 = new int[30, 30];\n\n Console.Write(\"\\nEnter the number of rows and columns of the matrix :\\n\");\n Console.Write(\"Rows entered = \");\n m = Convert.ToInt32(Console.ReadLine());\n\n Console.Write(\"Columns entered = \");\n n = Convert.ToInt32(Console.ReadLine());\n\n Console.Write(\"Set elements in the matrix...\\n\");\n for (i = 0; i < m; i++) {\n for (j = 0; j < n; j++) {\n Console.Write(\"\\n [{0}],[{1}] : \", i, j);\n arr1[i, j] = Convert.ToInt32(Console.ReadLine());\n }\n }\n\n Console.Write(\"\\n\\nMatrix before Transpose:\\n\");\n for (i = 0; i < m; i++) {\n Console.Write(\"\\n\");\n for (j = 0; j < n; j++)\n Console.Write(\"{0}\\t\", arr1[i, j]);\n }\n\n for (i = 0; i < m; i++) {\n for (j = 0; j < n; j++) {\n\n arr2[j, i] = arr1[i, j];\n }\n }\n\n Console.Write(\"\\n\\nMatrix after Transpose: \");\n for (i = 0; i < m; i++) {\n Console.Write(\"\\n\");\n for (j = 0; j < n; j++) {\n Console.Write(\"{0}\\t\", arr2[i, j]);\n }\n }\n Console.Write(\"\\n\\n\");\n }\n}" }, { "code": null, "e": 2793, "s": 2615, "text": "The following result will be produced on running the above program. Here, values from the user are to be entered for number of rows and columns, and the elements of the matrix −" }, { "code": null, "e": 3099, "s": 2793, "text": "Enter the number of rows and columns of the matrix :3 3\nRows entered = 3\nColumns entered 3\nSet elements in the matrix...\n\n[0],[0] : 1\n[0],[1] : 2\n[0],[2] : 3\n[1],[0] : 4\n[1],[1] : 5\n[1],[2] : 6\n[2],[0] : 7\n[2],[1] : 8\n[2],[2] : 9\n\nMatrix before Transpose:\n\n123\n456\n789\n\nMatrix after Transpose:\n147\n258\n369" } ]
Productionize a Machine Learning Model with a Django API | by GreekDataGuy | Towards Data Science
Previously, I wrote a tutorial on productionizing an ML model with flask. Flask is lighter weight, but if we needed more functionality, django comes with that included. I built an API that makes a prediction via sklearn model. Below is my step-by-step code. This tutorial contains 3 parts:1. Training the ML model2. Building the django application3. Testing the API This first part can be done in a jupyter notebook. This is not a tutorial on machine learning. So we’ll train a model on fictional data. That said, it will function like any other sklearn model you could train. Our model will detect if an animal is a dog, based on the noise the animal makes. Create fictional data! Within each inner list, the 1st index is the sound of an animal, the 2nd index is a boolean label indicating if the animal is a dog. data = [ ['woof', 1], ['bark', 1], ['ruff', 1], ['bowwow', 1], ['roar', 0], ['bah', 0], ['meow', 0], ['ribbit', 0], ['moo', 0], ['yip', 0], ['pika', 0]] Convert above into lists of features and labels. X = []y = []for i in data: X.append( i[0] ) y.append( i[1] ) Fit a vectorizer and transform the features. from sklearn.feature_extraction.text import CountVectorizervectorizer = CountVectorizer()X_vectorized = vectorizer.fit_transform(X) Train a linear regression. from sklearn.linear_model import LinearRegressionimport numpy as npregressor = LinearRegression()regressor.fit(X_vectorized, y) Now test it out on a few examples. test_feature = vectorizer.transform(['woof'])prediction = regressor.predict(test_feature)print(prediction)test_feature = vectorizer.transform(['ribbit'])prediction = regressor.predict(test_feature)print(prediction)test_feature = vectorizer.transform(['meoww'])prediction = regressor.predict(test_feature)print(prediction)#=> [1.]#=> [0.]#=> [0.36363636] Perfect. Pickle our models into a byte stream so we can store them in the app. import picklepickl = { 'vectorizer': vectorizer, 'regressor': regressor}pickle.dump( pickl, open( 'models' + ".p", "wb" ) ) Open the command line to the directory where you store your django projects. Create a directory for this application and cd into it. mkdir DjangoMLAPI && cd DjangoMLAPI Create a virtual environment and install the required packages. python3 -m venv envsource env/bin/activatepip install django djangorestframework sklearn numpy Now create a django project, the directory containing all the code we’re working on. This would also include database configuration and application settings if we needed them. While a “project” actually represents the application we’re building, django uses the term “app” to refer to a package in a project. Our main package will be called api. django-admin startproject api This generates a bunch of boilerplate code required to power our project. It will look like the file tree on the left. The outer /api is just a folder that contains all our project code. The inner /api is the main python package for our project. Next, we’ll generate an “app” inside our project. This will power the machine learning behind our API. We’ll name this predictor. cd apipython manage.py startapp predictor The full directory will now look like the file tree on the left. What we added here is a folder called /predictor with a number of files inside. Several of these files aren’t even needed for our use case. We’ll get back to deleting them at the end of the tutorial. apps.py is where we’ll define our config class. This is code that will only run once (instead of on every request) so we’ll eventually place the code to load our models there. views.py will contain code that runs on every request. So we put vectorization and regression logic there. Now let’s add this app to toINSTALLED_APPS. Open /api/api/settings.py and add 'predictor' to INSTALLED_APPS. It should look like below. INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'predictor'] Now create a folder called /models inside /predictor. Move your trained pickled models into this directory. Note that in a real production environment, I’d decouple this from the app (possibly with S3) so we don’t need to re-deploy the app every time we update the model. But here we’ll just include the model in the app. Add this line to settings as well. We’ll use this to load our model. MODELS = os.path.join(BASE_DIR, 'predictor/models') Now write the code that loads our models when the application starts. Inside /api/predictor/apps.py use this code. from django.apps import AppConfigfrom django.conf import settingsimport osimport pickleclass PredictorConfig(AppConfig): # create path to models path = os.path.join(settings.MODELS, 'models.p') # load models into separate variables # these will be accessible via this class with open(path, 'rb') as pickled: data = pickle.load(pickled) regressor = data['regressor'] vectorizer = data['vectorizer'] Now create a view that supports our regression logic. Open /api/predictor/views.py and update with this code. from django.shortcuts import renderfrom .apps import PredictorConfigfrom django.http import JsonResponsefrom rest_framework.views import APIViewclass call_model(APIView): def get(self,request): if request.method == 'GET': # get sound from request sound = request.GET.get('sound') # vectorize sound vector = PredictorConfig.vectorizer.transform([sound]) # predict based on vector prediction = PredictorConfig.regressor.predict(vector)[0] # build response response = {'dog': prediction} # return response return JsonResponse(response) Set up routing, mapping URLs to views in /api/api/urls.py . from django.urls import pathfrom predictor import viewsurlpatterns = [ path('classify/', views.call_model.as_view())] You can delete the following files because we don’t need them. api/predictor/tests.pyapi/predictor/models.pyapi/predictor/admin.py Now start the server. python manage.py runserver And make a couple curl requests to test it out. You could also directly input the URLs into the browser. curl -X GET http://127.0.0.1:8000/classify/?sound=meow#=> {"dog": 0.0}curl -X GET http://127.0.0.1:8000/classify/?sound=woof#=> {"dog": 1.0} Easy peazy! It’s working! A number close to 1 indicates it’s a dog and a number close to 0 indicates it’s not a dog. There we have it. A django API that loads and runs a trained machine learning model!
[ { "code": null, "e": 246, "s": 172, "text": "Previously, I wrote a tutorial on productionizing an ML model with flask." }, { "code": null, "e": 341, "s": 246, "text": "Flask is lighter weight, but if we needed more functionality, django comes with that included." }, { "code": null, "e": 430, "s": 341, "text": "I built an API that makes a prediction via sklearn model. Below is my step-by-step code." }, { "code": null, "e": 538, "s": 430, "text": "This tutorial contains 3 parts:1. Training the ML model2. Building the django application3. Testing the API" }, { "code": null, "e": 589, "s": 538, "text": "This first part can be done in a jupyter notebook." }, { "code": null, "e": 749, "s": 589, "text": "This is not a tutorial on machine learning. So we’ll train a model on fictional data. That said, it will function like any other sklearn model you could train." }, { "code": null, "e": 831, "s": 749, "text": "Our model will detect if an animal is a dog, based on the noise the animal makes." }, { "code": null, "e": 987, "s": 831, "text": "Create fictional data! Within each inner list, the 1st index is the sound of an animal, the 2nd index is a boolean label indicating if the animal is a dog." }, { "code": null, "e": 1173, "s": 987, "text": "data = [ ['woof', 1], ['bark', 1], ['ruff', 1], ['bowwow', 1], ['roar', 0], ['bah', 0], ['meow', 0], ['ribbit', 0], ['moo', 0], ['yip', 0], ['pika', 0]]" }, { "code": null, "e": 1222, "s": 1173, "text": "Convert above into lists of features and labels." }, { "code": null, "e": 1289, "s": 1222, "text": "X = []y = []for i in data: X.append( i[0] ) y.append( i[1] )" }, { "code": null, "e": 1334, "s": 1289, "text": "Fit a vectorizer and transform the features." }, { "code": null, "e": 1466, "s": 1334, "text": "from sklearn.feature_extraction.text import CountVectorizervectorizer = CountVectorizer()X_vectorized = vectorizer.fit_transform(X)" }, { "code": null, "e": 1493, "s": 1466, "text": "Train a linear regression." }, { "code": null, "e": 1621, "s": 1493, "text": "from sklearn.linear_model import LinearRegressionimport numpy as npregressor = LinearRegression()regressor.fit(X_vectorized, y)" }, { "code": null, "e": 1656, "s": 1621, "text": "Now test it out on a few examples." }, { "code": null, "e": 2010, "s": 1656, "text": "test_feature = vectorizer.transform(['woof'])prediction = regressor.predict(test_feature)print(prediction)test_feature = vectorizer.transform(['ribbit'])prediction = regressor.predict(test_feature)print(prediction)test_feature = vectorizer.transform(['meoww'])prediction = regressor.predict(test_feature)print(prediction)#=> [1.]#=> [0.]#=> [0.36363636]" }, { "code": null, "e": 2019, "s": 2010, "text": "Perfect." }, { "code": null, "e": 2089, "s": 2019, "text": "Pickle our models into a byte stream so we can store them in the app." }, { "code": null, "e": 2219, "s": 2089, "text": "import picklepickl = { 'vectorizer': vectorizer, 'regressor': regressor}pickle.dump( pickl, open( 'models' + \".p\", \"wb\" ) )" }, { "code": null, "e": 2352, "s": 2219, "text": "Open the command line to the directory where you store your django projects. Create a directory for this application and cd into it." }, { "code": null, "e": 2388, "s": 2352, "text": "mkdir DjangoMLAPI && cd DjangoMLAPI" }, { "code": null, "e": 2452, "s": 2388, "text": "Create a virtual environment and install the required packages." }, { "code": null, "e": 2547, "s": 2452, "text": "python3 -m venv envsource env/bin/activatepip install django djangorestframework sklearn numpy" }, { "code": null, "e": 2723, "s": 2547, "text": "Now create a django project, the directory containing all the code we’re working on. This would also include database configuration and application settings if we needed them." }, { "code": null, "e": 2893, "s": 2723, "text": "While a “project” actually represents the application we’re building, django uses the term “app” to refer to a package in a project. Our main package will be called api." }, { "code": null, "e": 2923, "s": 2893, "text": "django-admin startproject api" }, { "code": null, "e": 3042, "s": 2923, "text": "This generates a bunch of boilerplate code required to power our project. It will look like the file tree on the left." }, { "code": null, "e": 3110, "s": 3042, "text": "The outer /api is just a folder that contains all our project code." }, { "code": null, "e": 3169, "s": 3110, "text": "The inner /api is the main python package for our project." }, { "code": null, "e": 3272, "s": 3169, "text": "Next, we’ll generate an “app” inside our project. This will power the machine learning behind our API." }, { "code": null, "e": 3299, "s": 3272, "text": "We’ll name this predictor." }, { "code": null, "e": 3341, "s": 3299, "text": "cd apipython manage.py startapp predictor" }, { "code": null, "e": 3406, "s": 3341, "text": "The full directory will now look like the file tree on the left." }, { "code": null, "e": 3486, "s": 3406, "text": "What we added here is a folder called /predictor with a number of files inside." }, { "code": null, "e": 3606, "s": 3486, "text": "Several of these files aren’t even needed for our use case. We’ll get back to deleting them at the end of the tutorial." }, { "code": null, "e": 3782, "s": 3606, "text": "apps.py is where we’ll define our config class. This is code that will only run once (instead of on every request) so we’ll eventually place the code to load our models there." }, { "code": null, "e": 3889, "s": 3782, "text": "views.py will contain code that runs on every request. So we put vectorization and regression logic there." }, { "code": null, "e": 4025, "s": 3889, "text": "Now let’s add this app to toINSTALLED_APPS. Open /api/api/settings.py and add 'predictor' to INSTALLED_APPS. It should look like below." }, { "code": null, "e": 4240, "s": 4025, "text": "INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'predictor']" }, { "code": null, "e": 4348, "s": 4240, "text": "Now create a folder called /models inside /predictor. Move your trained pickled models into this directory." }, { "code": null, "e": 4562, "s": 4348, "text": "Note that in a real production environment, I’d decouple this from the app (possibly with S3) so we don’t need to re-deploy the app every time we update the model. But here we’ll just include the model in the app." }, { "code": null, "e": 4631, "s": 4562, "text": "Add this line to settings as well. We’ll use this to load our model." }, { "code": null, "e": 4683, "s": 4631, "text": "MODELS = os.path.join(BASE_DIR, 'predictor/models')" }, { "code": null, "e": 4798, "s": 4683, "text": "Now write the code that loads our models when the application starts. Inside /api/predictor/apps.py use this code." }, { "code": null, "e": 5224, "s": 4798, "text": "from django.apps import AppConfigfrom django.conf import settingsimport osimport pickleclass PredictorConfig(AppConfig): # create path to models path = os.path.join(settings.MODELS, 'models.p') # load models into separate variables # these will be accessible via this class with open(path, 'rb') as pickled: data = pickle.load(pickled) regressor = data['regressor'] vectorizer = data['vectorizer']" }, { "code": null, "e": 5334, "s": 5224, "text": "Now create a view that supports our regression logic. Open /api/predictor/views.py and update with this code." }, { "code": null, "e": 5990, "s": 5334, "text": "from django.shortcuts import renderfrom .apps import PredictorConfigfrom django.http import JsonResponsefrom rest_framework.views import APIViewclass call_model(APIView): def get(self,request): if request.method == 'GET': # get sound from request sound = request.GET.get('sound') # vectorize sound vector = PredictorConfig.vectorizer.transform([sound]) # predict based on vector prediction = PredictorConfig.regressor.predict(vector)[0] # build response response = {'dog': prediction} # return response return JsonResponse(response)" }, { "code": null, "e": 6050, "s": 5990, "text": "Set up routing, mapping URLs to views in /api/api/urls.py ." }, { "code": null, "e": 6171, "s": 6050, "text": "from django.urls import pathfrom predictor import viewsurlpatterns = [ path('classify/', views.call_model.as_view())]" }, { "code": null, "e": 6234, "s": 6171, "text": "You can delete the following files because we don’t need them." }, { "code": null, "e": 6302, "s": 6234, "text": "api/predictor/tests.pyapi/predictor/models.pyapi/predictor/admin.py" }, { "code": null, "e": 6324, "s": 6302, "text": "Now start the server." }, { "code": null, "e": 6351, "s": 6324, "text": "python manage.py runserver" }, { "code": null, "e": 6456, "s": 6351, "text": "And make a couple curl requests to test it out. You could also directly input the URLs into the browser." }, { "code": null, "e": 6597, "s": 6456, "text": "curl -X GET http://127.0.0.1:8000/classify/?sound=meow#=> {\"dog\": 0.0}curl -X GET http://127.0.0.1:8000/classify/?sound=woof#=> {\"dog\": 1.0}" }, { "code": null, "e": 6714, "s": 6597, "text": "Easy peazy! It’s working! A number close to 1 indicates it’s a dog and a number close to 0 indicates it’s not a dog." } ]
C++ Numeric Library - accumulate
It returns the result of accumulating all the values in the range [first,last) to init. Following is the declaration for std::accumulate. template <class InputIterator, class T> T accumulate (InputIterator first, InputIterator last, T init); template <class InputIterator, class T, class BinaryOperation> T accumulate (InputIterator first, InputIterator last, T init, BinaryOperation binary_op); template <class InputIterator, class T> T accumulate (InputIterator first, InputIterator last, T init); template <class InputIterator, class T, class BinaryOperation> T accumulate (InputIterator first, InputIterator last, T init, BinaryOperation binary_op); first, last − It iterators to the initial and final positions in a sequence. first, last − It iterators to the initial and final positions in a sequence. init − It is an initial value for the accumulator. init − It is an initial value for the accumulator. binary_op − It is binary operation. binary_op − It is binary operation. It returns the result of accumulating all the values in the range [first,last) to init. It throws if any of binary_op, the assignments or an operation on an iterator throws. The locale object is modified. In below example for std::accumulate. #include <iostream> #include <functional> #include <numeric> int myfunction (int x, int y) {return x+2*y;} struct myclass { int operator()(int x, int y) {return x+3*y;} } myobject; int main () { int init = 100; int numbers[] = {5,10,20}; std::cout << "using default accumulate: "; std::cout << std::accumulate(numbers,numbers+3,init); std::cout << '\n'; std::cout << "using functional's minus: "; std::cout << std::accumulate (numbers, numbers+3, init, std::minus<int>()); std::cout << '\n'; std::cout << "using custom function: "; std::cout << std::accumulate (numbers, numbers+3, init, myfunction); std::cout << '\n'; std::cout << "using custom object: "; std::cout << std::accumulate (numbers, numbers+3, init, myobject); std::cout << '\n'; return 0; } The output should be like this − using default accumulate: 135 using functional's minus: 65 using custom function: 170 using custom object: 205 Print Add Notes Bookmark this page
[ { "code": null, "e": 2691, "s": 2603, "text": "It returns the result of accumulating all the values in the range [first,last) to init." }, { "code": null, "e": 2741, "s": 2691, "text": "Following is the declaration for std::accumulate." }, { "code": null, "e": 3024, "s": 2741, "text": "\t\ntemplate <class InputIterator, class T>\n T accumulate (InputIterator first, InputIterator last, T init);\ntemplate <class InputIterator, class T, class BinaryOperation>\n T accumulate (InputIterator first, InputIterator last, T init,\n BinaryOperation binary_op);" }, { "code": null, "e": 3305, "s": 3024, "text": "template <class InputIterator, class T>\n T accumulate (InputIterator first, InputIterator last, T init);\ntemplate <class InputIterator, class T, class BinaryOperation>\n T accumulate (InputIterator first, InputIterator last, T init,\n BinaryOperation binary_op);" }, { "code": null, "e": 3382, "s": 3305, "text": "first, last − It iterators to the initial and final positions in a sequence." }, { "code": null, "e": 3459, "s": 3382, "text": "first, last − It iterators to the initial and final positions in a sequence." }, { "code": null, "e": 3510, "s": 3459, "text": "init − It is an initial value for the accumulator." }, { "code": null, "e": 3561, "s": 3510, "text": "init − It is an initial value for the accumulator." }, { "code": null, "e": 3597, "s": 3561, "text": "binary_op − It is binary operation." }, { "code": null, "e": 3633, "s": 3597, "text": "binary_op − It is binary operation." }, { "code": null, "e": 3721, "s": 3633, "text": "It returns the result of accumulating all the values in the range [first,last) to init." }, { "code": null, "e": 3807, "s": 3721, "text": "It throws if any of binary_op, the assignments or an operation on an iterator throws." }, { "code": null, "e": 3838, "s": 3807, "text": "The locale object is modified." }, { "code": null, "e": 3876, "s": 3838, "text": "In below example for std::accumulate." }, { "code": null, "e": 4696, "s": 3876, "text": "#include <iostream> \n#include <functional> \n#include <numeric> \n\nint myfunction (int x, int y) {return x+2*y;}\nstruct myclass {\n int operator()(int x, int y) {return x+3*y;}\n} myobject;\n\nint main () {\nint init = 100;\n int numbers[] = {5,10,20};\n\n std::cout << \"using default accumulate: \";\n std::cout << std::accumulate(numbers,numbers+3,init);\n std::cout << '\\n';\n\n std::cout << \"using functional's minus: \";\n std::cout << std::accumulate (numbers, numbers+3, init, std::minus<int>());\n std::cout << '\\n';\n\n std::cout << \"using custom function: \";\n std::cout << std::accumulate (numbers, numbers+3, init, myfunction);\n std::cout << '\\n';\n\n std::cout << \"using custom object: \";\n std::cout << std::accumulate (numbers, numbers+3, init, myobject);\n std::cout << '\\n';\n\n return 0;\n}" }, { "code": null, "e": 4729, "s": 4696, "text": "The output should be like this −" }, { "code": null, "e": 4841, "s": 4729, "text": "using default accumulate: 135\nusing functional's minus: 65\nusing custom function: 170\nusing custom object: 205\n" }, { "code": null, "e": 4848, "s": 4841, "text": " Print" }, { "code": null, "e": 4859, "s": 4848, "text": " Add Notes" } ]
GATE | GATE-CS-2003 | Question 20 - GeeksforGeeks
28 Jun, 2021 Consider the following three claims 1. (n + k)m = Θ(nm), where k and m are constants 2. 2n + 1 = O(2n) 3. 22n + 1 = O(2n) Which of these claims are correct ? (A) 1 and 2(B) 1 and 3(C) 2 and 3(D) 1, 2, and 3Answer: (A)Explanation: (n + k)m and Θ(nm) are asymptotically same as theta notation can always be written by taking the leading order term in a polynomial expression. 2n + 1 and O(2n) are also asymptotically same as 2n + 1 can be written as 2 * 2n and constant multiplication/addition doesn’t matter in theta notation. 22n + 1 and O(2n) are not same as constant is in power. See Asymptotic Notations for more details. Quiz of this Question GATE-CS-2003 GATE-GATE-CS-2003 GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments GATE | GATE-CS-2016 (Set 2) | Question 48 GATE | GATE-CS-2014-(Set-1) | Question 30 GATE | GATE-CS-2001 | Question 23 GATE | GATE-CS-2015 (Set 1) | Question 65 GATE | GATE CS 2010 | Question 45 GATE | GATE-CS-2015 (Set 3) | Question 65 GATE | GATE-CS-2014-(Set-1) | Question 65 C++ Program to count Vowels in a string using Pointer GATE | GATE-CS-2004 | Question 3 GATE | GATE-CS-2015 (Set 1) | Question 42
[ { "code": null, "e": 24043, "s": 24015, "text": "\n28 Jun, 2021" }, { "code": null, "e": 24079, "s": 24043, "text": "Consider the following three claims" }, { "code": null, "e": 24166, "s": 24079, "text": "1. (n + k)m = Θ(nm), where k and m are constants\n2. 2n + 1 = O(2n)\n3. 22n + 1 = O(2n) " }, { "code": null, "e": 24202, "s": 24166, "text": "Which of these claims are correct ?" }, { "code": null, "e": 24418, "s": 24202, "text": "(A) 1 and 2(B) 1 and 3(C) 2 and 3(D) 1, 2, and 3Answer: (A)Explanation: (n + k)m and Θ(nm) are asymptotically same as theta notation can always be written by taking the leading order term in a polynomial expression." }, { "code": null, "e": 24570, "s": 24418, "text": "2n + 1 and O(2n) are also asymptotically same as 2n + 1 can be written as 2 * 2n and constant multiplication/addition doesn’t matter in theta notation." }, { "code": null, "e": 24626, "s": 24570, "text": "22n + 1 and O(2n) are not same as constant is in power." }, { "code": null, "e": 24669, "s": 24626, "text": "See Asymptotic Notations for more details." }, { "code": null, "e": 24691, "s": 24669, "text": "Quiz of this Question" }, { "code": null, "e": 24704, "s": 24691, "text": "GATE-CS-2003" }, { "code": null, "e": 24722, "s": 24704, "text": "GATE-GATE-CS-2003" }, { "code": null, "e": 24727, "s": 24722, "text": "GATE" }, { "code": null, "e": 24825, "s": 24727, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 24834, "s": 24825, "text": "Comments" }, { "code": null, "e": 24847, "s": 24834, "text": "Old Comments" }, { "code": null, "e": 24889, "s": 24847, "text": "GATE | GATE-CS-2016 (Set 2) | Question 48" }, { "code": null, "e": 24931, "s": 24889, "text": "GATE | GATE-CS-2014-(Set-1) | Question 30" }, { "code": null, "e": 24965, "s": 24931, "text": "GATE | GATE-CS-2001 | Question 23" }, { "code": null, "e": 25007, "s": 24965, "text": "GATE | GATE-CS-2015 (Set 1) | Question 65" }, { "code": null, "e": 25041, "s": 25007, "text": "GATE | GATE CS 2010 | Question 45" }, { "code": null, "e": 25083, "s": 25041, "text": "GATE | GATE-CS-2015 (Set 3) | Question 65" }, { "code": null, "e": 25125, "s": 25083, "text": "GATE | GATE-CS-2014-(Set-1) | Question 65" }, { "code": null, "e": 25179, "s": 25125, "text": "C++ Program to count Vowels in a string using Pointer" }, { "code": null, "e": 25212, "s": 25179, "text": "GATE | GATE-CS-2004 | Question 3" } ]
MySQL trigger to insert row into another table?
Let us first create a table. The CREATE command is used to create a table. mysql> create table Table1 -> ( -> id int, -> name varchar(100) -> ); Query OK, 0 rows affected (0.62 sec) Let us now create another table. mysql> create table Table2 -> ( -> id int, -> name varchar(100) -> ); Query OK, 0 rows affected (0.49 sec) Now, the following is how you can create a trigger. mysql> delimiter # mysql> create trigger Table1Trigger after insert on Table1 -> for each row -> begin -> insert into Table2(id, name) values (new.id, new.name); -> end# Query OK, 0 rows affected (0.29 sec) mysql> delimiter ; To create a trigger, we need to change the delimiter. Inserting the row into Table1 activates the trigger and inserts the records into Table2. To insert record in Table1. mysql> insert into Table1 values(1,'John'),(2,'Smith'),(3,'Carol'); Query OK, 3 rows affected (0.28 sec) Records: 3 Duplicates: 0 Warnings: 0 To check if the records are inserted in both tables or not. mysql> select *from Table1; Here is the output that shows record inserted successfully in Table1. +------+-------+ | id | name | +------+-------+ | 1 | John | | 2 | Smith | | 3 | Carol | +------+-------+ 3 rows in set (0.00 sec) To check for second table. mysql> select *from Table2; The following is the output that shows record inserted successfully in Table2. +------+-------+ | id | name | +------+-------+ | 1 | John | | 2 | Smith | | 3 | Carol | +------+-------+ 3 rows in set (0.00 sec)
[ { "code": null, "e": 1137, "s": 1062, "text": "Let us first create a table. The CREATE command is used to create a table." }, { "code": null, "e": 1256, "s": 1137, "text": "mysql> create table Table1\n -> (\n -> id int,\n -> name varchar(100)\n -> );\nQuery OK, 0 rows affected (0.62 sec)" }, { "code": null, "e": 1289, "s": 1256, "text": "Let us now create another table." }, { "code": null, "e": 1408, "s": 1289, "text": "mysql> create table Table2\n -> (\n -> id int,\n -> name varchar(100)\n -> );\nQuery OK, 0 rows affected (0.49 sec)" }, { "code": null, "e": 1460, "s": 1408, "text": "Now, the following is how you can create a trigger." }, { "code": null, "e": 1700, "s": 1460, "text": "mysql> delimiter #\nmysql> create trigger Table1Trigger after insert on Table1\n -> for each row\n -> begin\n -> insert into Table2(id, name) values (new.id, new.name);\n -> end#\nQuery OK, 0 rows affected (0.29 sec)\n\nmysql> delimiter ;" }, { "code": null, "e": 1754, "s": 1700, "text": "To create a trigger, we need to change the delimiter." }, { "code": null, "e": 1871, "s": 1754, "text": "Inserting the row into Table1 activates the trigger and inserts the records into Table2. To insert record in Table1." }, { "code": null, "e": 2015, "s": 1871, "text": "mysql> insert into Table1 values(1,'John'),(2,'Smith'),(3,'Carol');\nQuery OK, 3 rows affected (0.28 sec)\nRecords: 3 Duplicates: 0 Warnings: 0" }, { "code": null, "e": 2075, "s": 2015, "text": "To check if the records are inserted in both tables or not." }, { "code": null, "e": 2103, "s": 2075, "text": "mysql> select *from Table1;" }, { "code": null, "e": 2173, "s": 2103, "text": "Here is the output that shows record inserted successfully in Table1." }, { "code": null, "e": 2318, "s": 2173, "text": "+------+-------+\n| id | name |\n+------+-------+\n| 1 | John |\n| 2 | Smith |\n| 3 | Carol |\n+------+-------+\n3 rows in set (0.00 sec)\n" }, { "code": null, "e": 2345, "s": 2318, "text": "To check for second table." }, { "code": null, "e": 2374, "s": 2345, "text": "mysql> select *from Table2;" }, { "code": null, "e": 2453, "s": 2374, "text": "The following is the output that shows record inserted successfully in Table2." }, { "code": null, "e": 2598, "s": 2453, "text": "+------+-------+\n| id | name |\n+------+-------+\n| 1 | John |\n| 2 | Smith |\n| 3 | Carol |\n+------+-------+\n3 rows in set (0.00 sec)\n" } ]
HashMap clone() Method in Java
01 Nov, 2021 Let us do clear out the foundation concept of shallow copy and deep copy in java. Shallow repetition is quicker. However, it’s “lazy” it handles pointers and references. Rather than creating a contemporary copy of the particular knowledge the pointer points to, it simply copies over the pointer price. So, each the first and therefore the copy can have pointers that reference constant underlying knowledge. On another side, deep copy or deep repetition truly clones the underlying data. It is not shared between the first and therefore the copy. The java.util.HashMap.clone() method is present inside java.util package which typically is used to return a shallow copy of the mentioned hash map. It just creates a copy of the map. Syntax: Hash_Map.clone() Parameters: The method does not take any parameters. Return Value: The method just returns a copy of the HashMap. Example 1: Java // Java Program to Illustrate the clone() Method by// Mapping String Values to Integer Keys // Importing utility classesimport java.util.*; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Creating an empty HashMap HashMap<Integer, String> hash_map = new HashMap<Integer, String>(); // Mapping string values to int keys // Using put() method // Custom input values passed as arguments hash_map.put(10, "Geeks"); hash_map.put(15, "4"); hash_map.put(20, "Geeks"); hash_map.put(25, "Welcomes"); hash_map.put(30, "You"); // Print and display the HashMap System.out.println("Initial Mappings are: " + hash_map); // Print and display the cloned HashMap // using clone() method System.out.println("The cloned map look like this: " + hash_map.clone()); }} Initial Mappings are: {20=Geeks, 25=Welcomes, 10=Geeks, 30=You, 15=4} The cloned map look like this: {25=Welcomes, 10=Geeks, 20=Geeks, 30=You, 15=4} Example 2: Java // Java code to illustrate the clone() method by// Mapping Integer Values to String Keys // Importing utility classesimport java.util.*; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Creating an empty HashMap // Declaring objects of type integer and string HashMap<String, Integer> hash_map = new HashMap<String, Integer>(); // Mapping int values to string keys // using put() method hash_map.put("Geeks", 10); hash_map.put("4", 15); hash_map.put("Geeks", 20); hash_map.put("Welcomes", 25); hash_map.put("You", 30); // Print and display the HashMap System.out.println("Initial Mappings are: " + hash_map); // Print and display the cloned HashMap // using clone() method System.out.println("The cloned map look like this: " + hash_map.clone()); }} Initial Mappings are: {4=15, Geeks=20, You=30, Welcomes=25} The cloned map look like this: {Geeks=20, 4=15, You=30, Welcomes=25} Note: The same operation can be performed with any type of mappings with variation and combination of different data types. clone() method does the shallow copy. But here the values in the original and cloned hashmap will not affect each other because primitive data type is used. khatritaukir ankit12433 Java - util package Java-Collections Java-Functions Java-HashMap Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n01 Nov, 2021" }, { "code": null, "e": 601, "s": 53, "text": "Let us do clear out the foundation concept of shallow copy and deep copy in java. Shallow repetition is quicker. However, it’s “lazy” it handles pointers and references. Rather than creating a contemporary copy of the particular knowledge the pointer points to, it simply copies over the pointer price. So, each the first and therefore the copy can have pointers that reference constant underlying knowledge. On another side, deep copy or deep repetition truly clones the underlying data. It is not shared between the first and therefore the copy." }, { "code": null, "e": 785, "s": 601, "text": "The java.util.HashMap.clone() method is present inside java.util package which typically is used to return a shallow copy of the mentioned hash map. It just creates a copy of the map." }, { "code": null, "e": 794, "s": 785, "text": "Syntax: " }, { "code": null, "e": 811, "s": 794, "text": "Hash_Map.clone()" }, { "code": null, "e": 864, "s": 811, "text": "Parameters: The method does not take any parameters." }, { "code": null, "e": 926, "s": 864, "text": "Return Value: The method just returns a copy of the HashMap. " }, { "code": null, "e": 937, "s": 926, "text": "Example 1:" }, { "code": null, "e": 942, "s": 937, "text": "Java" }, { "code": "// Java Program to Illustrate the clone() Method by// Mapping String Values to Integer Keys // Importing utility classesimport java.util.*; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Creating an empty HashMap HashMap<Integer, String> hash_map = new HashMap<Integer, String>(); // Mapping string values to int keys // Using put() method // Custom input values passed as arguments hash_map.put(10, \"Geeks\"); hash_map.put(15, \"4\"); hash_map.put(20, \"Geeks\"); hash_map.put(25, \"Welcomes\"); hash_map.put(30, \"You\"); // Print and display the HashMap System.out.println(\"Initial Mappings are: \" + hash_map); // Print and display the cloned HashMap // using clone() method System.out.println(\"The cloned map look like this: \" + hash_map.clone()); }}", "e": 1933, "s": 942, "text": null }, { "code": null, "e": 2082, "s": 1933, "text": "Initial Mappings are: {20=Geeks, 25=Welcomes, 10=Geeks, 30=You, 15=4}\nThe cloned map look like this: {25=Welcomes, 10=Geeks, 20=Geeks, 30=You, 15=4}" }, { "code": null, "e": 2096, "s": 2084, "text": "Example 2:" }, { "code": null, "e": 2101, "s": 2096, "text": "Java" }, { "code": "// Java code to illustrate the clone() method by// Mapping Integer Values to String Keys // Importing utility classesimport java.util.*; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Creating an empty HashMap // Declaring objects of type integer and string HashMap<String, Integer> hash_map = new HashMap<String, Integer>(); // Mapping int values to string keys // using put() method hash_map.put(\"Geeks\", 10); hash_map.put(\"4\", 15); hash_map.put(\"Geeks\", 20); hash_map.put(\"Welcomes\", 25); hash_map.put(\"You\", 30); // Print and display the HashMap System.out.println(\"Initial Mappings are: \" + hash_map); // Print and display the cloned HashMap // using clone() method System.out.println(\"The cloned map look like this: \" + hash_map.clone()); }}", "e": 3090, "s": 2101, "text": null }, { "code": null, "e": 3219, "s": 3090, "text": "Initial Mappings are: {4=15, Geeks=20, You=30, Welcomes=25}\nThe cloned map look like this: {Geeks=20, 4=15, You=30, Welcomes=25}" }, { "code": null, "e": 3228, "s": 3221, "text": "Note: " }, { "code": null, "e": 3346, "s": 3228, "text": "The same operation can be performed with any type of mappings with variation and combination of different data types." }, { "code": null, "e": 3503, "s": 3346, "text": "clone() method does the shallow copy. But here the values in the original and cloned hashmap will not affect each other because primitive data type is used." }, { "code": null, "e": 3516, "s": 3503, "text": "khatritaukir" }, { "code": null, "e": 3527, "s": 3516, "text": "ankit12433" }, { "code": null, "e": 3547, "s": 3527, "text": "Java - util package" }, { "code": null, "e": 3564, "s": 3547, "text": "Java-Collections" }, { "code": null, "e": 3579, "s": 3564, "text": "Java-Functions" }, { "code": null, "e": 3592, "s": 3579, "text": "Java-HashMap" }, { "code": null, "e": 3597, "s": 3592, "text": "Java" }, { "code": null, "e": 3602, "s": 3597, "text": "Java" }, { "code": null, "e": 3619, "s": 3602, "text": "Java-Collections" } ]
Print the following pyramid pattern
29 Apr, 2021 Given a positive integer n. The problem is to print the pyramid pattern as described in the examples below. Examples: Input : n = 4 Output : 1 3*2 4*5*6 10*9*8*7 Input : n = 5 Output : 1 3*2 4*5*6 10*9*8*7 11*12*13*14*15 Source: Amdocs Interview Experience | Set 1 Approach: For odd number row, values are being displayed in increasing order and for even number row, values are being displayed in decreasing order. The only other trick is to how to iterate the loops. Algorithm: printPattern(int n) Declare j, k Initialize k = 0 for i = 1 to n if i%2 != 0 for j = k+1, j < k+i, j++ print j and "*" print j and new line k = ++j else k = k+i-1 for j = k, j > k-i+1, j-- print j and "*"; print j and new line C++ Java Python3 C# PHP Javascript // C++ implementation to print the following// pyramid pattern#include <bits/stdc++.h>using namespace std; // function to print the following pyramid patternvoid printPattern(int n){ int j, k = 0; // loop to decide the row number for (int i=1; i<=n; i++) { // if row number is odd if (i%2 != 0) { // print numbers with the '*' sign in // increasing order for (j=k+1; j<k+i; j++) cout << j << "*"; cout << j++ << endl; // update value of 'k' k = j; } // if row number is even else { // update value of 'k' k = k+i-1; // print numbers with the '*' in // decreasing order for (j=k; j>k-i+1; j--) cout << j << "*"; cout << j << endl; } }} // Driver program to test aboveint main(){ int n = 5; printPattern(n); return 0;} // Java implementation to print the// following pyramid patternpublic class Pyramid_Pattern { // function to print the following pyramid // pattern static void printPattern(int n) { int j, k = 0; // loop to decide the row number for (int i = 1; i <= n; i++) { // if row number is odd if (i % 2 != 0) { // print numbers with the '*' // sign in increasing order for (j = k + 1; j < k + i; j++) System.out.print(j + "*"); System.out.println(j++); // update value of 'k' k = j; } // if row number is even else { // update value of 'k' k = k + i - 1; // print numbers with the '*' in // decreasing order for (j = k; j > k - i + 1; j--) System.out.print(j + "*"); System.out.println(j); } } } // Driver program to test abovepublic static void main(String args[]) { int n = 5; printPattern(n); }}// This code is contributed by Sumit Ghosh # Python3 implementation to print the# following pyramid pattern # function to print the# following pyramid patterndef printPattern(n) : j, k = 0, 0 # loop to decide the row number for i in range(1, n + 1) : # if row number is odd if i % 2 != 0 : # print numbers with # the '*' sign in # increasing order for j in range(k + 1, k + i) : print(str(j) + "*", end = "") j = k + i print(j) j += 1 # update value of 'k' k = j # if row number is even else : # update value of 'k' k = k + i - 1 # print numbers with the # '*' in decreasing order for j in range(k, k - i + 1, -1) : print(str(j) + "*", end = "") j = k - i + 1 print(j) # Driver Codeif __name__ == "__main__" : n = 5 # function calling printPattern(n) # This code is contributed# by ANKITRAI1 // C# implementation to print the// following pyramid patternusing System;public class Pyramid_Pattern { // function to print the following pyramid // pattern static void printPattern(int n) { int j, k = 0; // loop to decide the row number for (int i = 1; i <= n; i++) { // if row number is odd if (i % 2 != 0) { // print numbers with the '*' // sign in increasing order for (j = k + 1; j < k + i; j++) Console.Write(j + "*"); Console.WriteLine(j++); // update value of 'k' k = j; } // if row number is even else { // update value of 'k' k = k + i - 1; // print numbers with the '*' in // decreasing order for (j = k; j > k - i + 1; j--) Console.Write(j + "*"); Console.WriteLine(j); } } } // Driver program to test abovepublic static void Main() { int n = 5; printPattern(n); }}// This code is contributed by vt_m. <?php// PHP implementation to print the// following pyramid pattern // function to print the following// pyramid patternfunction printPattern($n){ $k = 0; // loop to decide // the row number for ($i = 1; $i <= $n; $i++) { // if row number is odd if ($i % 2 != 0) { // print numbers with the '*' // sign in increasing order for ($j = $k + 1; $j < $k + $i; $j++) echo $j. "*"; echo $j++ ."\n"; // update value of 'k' $k = $j; } // if row number is even else { // update value of 'k' $k = $k + $i - 1; // print numbers with the // '*' in decreasing order for ($j = $k; $j > $k - $i + 1; $j--) echo $j . "*"; echo $j ."\n" ; } }} // Driver Code $n = 5; printPattern($n); // This code is contributed by Sam007?> <script> // JavaScript implementation to print the// following pyramid pattern // Function to print the following// pyramid patternfunction printPattern(n){ var j, k = 0; // Loop to decide the row number for(var i = 1; i <= n; i++) { // If row number is odd if (i % 2 != 0) { // Print numbers with the '*' // sign in increasing order for(j = k + 1; j < k + i; j++) document.write(j + "* "); document.write(j++ + "<br>"); // Update value of 'k' k = j; } // If row number is even else { // Update value of 'k' k = k + i - 1; // Print numbers with the '*' in // decreasing order for(j = k; j > k - i + 1; j--) document.write(j + "*"); document.write(j + "<br>"); } }} // Driver codevar n = 5; printPattern(n); // This code is contributed by akshitsaxenaa09 </script> Output: 1 3*2 4*5*6 10*9*8*7 11*12*13*14*15 Time Complexity: O((n * (n + 1)) / 2)This article is contributed by Ayush Jauhari. 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. Sam007 ankthon akshitsaxenaa09 Amdocs pattern-printing School Programming Amdocs pattern-printing Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction To PYTHON Interfaces in Java Operator Overloading in C++ Types of Operating Systems Polymorphism in C++ Constructors in Java Exceptions in Java Different Methods to Reverse a String in C++ Python program to check if a string is palindrome or not Friend class and function in C++
[ { "code": null, "e": 54, "s": 26, "text": "\n29 Apr, 2021" }, { "code": null, "e": 162, "s": 54, "text": "Given a positive integer n. The problem is to print the pyramid pattern as described in the examples below." }, { "code": null, "e": 173, "s": 162, "text": "Examples: " }, { "code": null, "e": 278, "s": 173, "text": "Input : n = 4\nOutput : \n1\n3*2\n4*5*6\n10*9*8*7\n\nInput : n = 5\nOutput :\n1\n3*2\n4*5*6\n10*9*8*7\n11*12*13*14*15" }, { "code": null, "e": 323, "s": 278, "text": "Source: Amdocs Interview Experience | Set 1 " }, { "code": null, "e": 526, "s": 323, "text": "Approach: For odd number row, values are being displayed in increasing order and for even number row, values are being displayed in decreasing order. The only other trick is to how to iterate the loops." }, { "code": null, "e": 538, "s": 526, "text": "Algorithm: " }, { "code": null, "e": 856, "s": 538, "text": "printPattern(int n)\n Declare j, k\n Initialize k = 0\n\n for i = 1 to n\n\n if i%2 != 0\n for j = k+1, j < k+i, j++\n print j and \"*\"\n print j and new line \n k = ++j\n\n else\n k = k+i-1\n for j = k, j > k-i+1, j--\n print j and \"*\";\n print j and new line" }, { "code": null, "e": 860, "s": 856, "text": "C++" }, { "code": null, "e": 865, "s": 860, "text": "Java" }, { "code": null, "e": 873, "s": 865, "text": "Python3" }, { "code": null, "e": 876, "s": 873, "text": "C#" }, { "code": null, "e": 880, "s": 876, "text": "PHP" }, { "code": null, "e": 891, "s": 880, "text": "Javascript" }, { "code": "// C++ implementation to print the following// pyramid pattern#include <bits/stdc++.h>using namespace std; // function to print the following pyramid patternvoid printPattern(int n){ int j, k = 0; // loop to decide the row number for (int i=1; i<=n; i++) { // if row number is odd if (i%2 != 0) { // print numbers with the '*' sign in // increasing order for (j=k+1; j<k+i; j++) cout << j << \"*\"; cout << j++ << endl; // update value of 'k' k = j; } // if row number is even else { // update value of 'k' k = k+i-1; // print numbers with the '*' in // decreasing order for (j=k; j>k-i+1; j--) cout << j << \"*\"; cout << j << endl; } }} // Driver program to test aboveint main(){ int n = 5; printPattern(n); return 0;}", "e": 1902, "s": 891, "text": null }, { "code": "// Java implementation to print the// following pyramid patternpublic class Pyramid_Pattern { // function to print the following pyramid // pattern static void printPattern(int n) { int j, k = 0; // loop to decide the row number for (int i = 1; i <= n; i++) { // if row number is odd if (i % 2 != 0) { // print numbers with the '*' // sign in increasing order for (j = k + 1; j < k + i; j++) System.out.print(j + \"*\"); System.out.println(j++); // update value of 'k' k = j; } // if row number is even else { // update value of 'k' k = k + i - 1; // print numbers with the '*' in // decreasing order for (j = k; j > k - i + 1; j--) System.out.print(j + \"*\"); System.out.println(j); } } } // Driver program to test abovepublic static void main(String args[]) { int n = 5; printPattern(n); }}// This code is contributed by Sumit Ghosh", "e": 3133, "s": 1902, "text": null }, { "code": "# Python3 implementation to print the# following pyramid pattern # function to print the# following pyramid patterndef printPattern(n) : j, k = 0, 0 # loop to decide the row number for i in range(1, n + 1) : # if row number is odd if i % 2 != 0 : # print numbers with # the '*' sign in # increasing order for j in range(k + 1, k + i) : print(str(j) + \"*\", end = \"\") j = k + i print(j) j += 1 # update value of 'k' k = j # if row number is even else : # update value of 'k' k = k + i - 1 # print numbers with the # '*' in decreasing order for j in range(k, k - i + 1, -1) : print(str(j) + \"*\", end = \"\") j = k - i + 1 print(j) # Driver Codeif __name__ == \"__main__\" : n = 5 # function calling printPattern(n) # This code is contributed# by ANKITRAI1", "e": 4181, "s": 3133, "text": null }, { "code": "// C# implementation to print the// following pyramid patternusing System;public class Pyramid_Pattern { // function to print the following pyramid // pattern static void printPattern(int n) { int j, k = 0; // loop to decide the row number for (int i = 1; i <= n; i++) { // if row number is odd if (i % 2 != 0) { // print numbers with the '*' // sign in increasing order for (j = k + 1; j < k + i; j++) Console.Write(j + \"*\"); Console.WriteLine(j++); // update value of 'k' k = j; } // if row number is even else { // update value of 'k' k = k + i - 1; // print numbers with the '*' in // decreasing order for (j = k; j > k - i + 1; j--) Console.Write(j + \"*\"); Console.WriteLine(j); } } } // Driver program to test abovepublic static void Main() { int n = 5; printPattern(n); }}// This code is contributed by vt_m.", "e": 5400, "s": 4181, "text": null }, { "code": "<?php// PHP implementation to print the// following pyramid pattern // function to print the following// pyramid patternfunction printPattern($n){ $k = 0; // loop to decide // the row number for ($i = 1; $i <= $n; $i++) { // if row number is odd if ($i % 2 != 0) { // print numbers with the '*' // sign in increasing order for ($j = $k + 1; $j < $k + $i; $j++) echo $j. \"*\"; echo $j++ .\"\\n\"; // update value of 'k' $k = $j; } // if row number is even else { // update value of 'k' $k = $k + $i - 1; // print numbers with the // '*' in decreasing order for ($j = $k; $j > $k - $i + 1; $j--) echo $j . \"*\"; echo $j .\"\\n\" ; } }} // Driver Code $n = 5; printPattern($n); // This code is contributed by Sam007?>", "e": 6428, "s": 5400, "text": null }, { "code": "<script> // JavaScript implementation to print the// following pyramid pattern // Function to print the following// pyramid patternfunction printPattern(n){ var j, k = 0; // Loop to decide the row number for(var i = 1; i <= n; i++) { // If row number is odd if (i % 2 != 0) { // Print numbers with the '*' // sign in increasing order for(j = k + 1; j < k + i; j++) document.write(j + \"* \"); document.write(j++ + \"<br>\"); // Update value of 'k' k = j; } // If row number is even else { // Update value of 'k' k = k + i - 1; // Print numbers with the '*' in // decreasing order for(j = k; j > k - i + 1; j--) document.write(j + \"*\"); document.write(j + \"<br>\"); } }} // Driver codevar n = 5; printPattern(n); // This code is contributed by akshitsaxenaa09 </script>", "e": 7502, "s": 6428, "text": null }, { "code": null, "e": 7511, "s": 7502, "text": "Output: " }, { "code": null, "e": 7547, "s": 7511, "text": "1\n3*2\n4*5*6\n10*9*8*7\n11*12*13*14*15" }, { "code": null, "e": 8010, "s": 7547, "text": "Time Complexity: O((n * (n + 1)) / 2)This article is contributed by Ayush Jauhari. 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": 8017, "s": 8010, "text": "Sam007" }, { "code": null, "e": 8025, "s": 8017, "text": "ankthon" }, { "code": null, "e": 8041, "s": 8025, "text": "akshitsaxenaa09" }, { "code": null, "e": 8048, "s": 8041, "text": "Amdocs" }, { "code": null, "e": 8065, "s": 8048, "text": "pattern-printing" }, { "code": null, "e": 8084, "s": 8065, "text": "School Programming" }, { "code": null, "e": 8091, "s": 8084, "text": "Amdocs" }, { "code": null, "e": 8108, "s": 8091, "text": "pattern-printing" }, { "code": null, "e": 8206, "s": 8108, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8229, "s": 8206, "text": "Introduction To PYTHON" }, { "code": null, "e": 8248, "s": 8229, "text": "Interfaces in Java" }, { "code": null, "e": 8276, "s": 8248, "text": "Operator Overloading in C++" }, { "code": null, "e": 8303, "s": 8276, "text": "Types of Operating Systems" }, { "code": null, "e": 8323, "s": 8303, "text": "Polymorphism in C++" }, { "code": null, "e": 8344, "s": 8323, "text": "Constructors in Java" }, { "code": null, "e": 8363, "s": 8344, "text": "Exceptions in Java" }, { "code": null, "e": 8408, "s": 8363, "text": "Different Methods to Reverse a String in C++" }, { "code": null, "e": 8465, "s": 8408, "text": "Python program to check if a string is palindrome or not" } ]
NPDA for accepting the language L = {anbm | n,m ≥ 1 and n ≠ m}
05 Jul, 2022 Prerequisite – Pushdown automata, Pushdown automata acceptance by final state Problem – Design a non deterministic PDA for accepting the language , i.e., L = {aab, abb, aaab, abbb, aaaab, aaabb, aabbb, abbbb ......} In each of the string, the number of a’s are followed by unequal number of b’s. Explanation –Here, we need to maintain the order of a’s and b’s. That is, all the a’s are coming first and then all the b’s are coming. Thus, we need a stack along with the state diagram. The count of a’s and b’s is maintained by the stack. We will take 2 stack alphabets: = { a, z } Where, = set of all the stack alphabetz = stack start symbol Approach used in the construction of PDA –As we want to design a NPDA, thus every time ‘a’ comes before ‘b’. When ‘a’ comes then push it in stack and if again ‘a’ comes then also push it. After that, when ‘b’ comes then pop one ‘a’ from the stack each time. So, at the end if the stack becomes empty and b is coming or string is end and stack is not empty then we can say that the string is accepted by the PDA. Stack transition functions – (q0, a, z) (q0, az) (q0, a, a) (q0, aa) (q0, b, a) (q1, ) (q1, b, a) (q1, ) (q1, , a) (qf, a) (q1, b, z) (qf, z) Where, q0 = Initial stateqf = Final state = indicates pop operation State Transition Diagram – So, this is our required non deterministic PDA for accepting the language . mitalibhola94 GATE CS Theory of Computation & Automata Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Normal Forms in DBMS Page Replacement Algorithms in Operating Systems Inter Process Communication (IPC) Introduction of Operating System - Set 1 Differences between TCP and UDP Difference between DFA and NFA Turing Machine in TOC Chomsky Hierarchy in Theory of Computation Boyer-Moore Majority Voting Algorithm Regular Expressions, Regular Grammar and Regular Languages
[ { "code": null, "e": 54, "s": 26, "text": "\n05 Jul, 2022" }, { "code": null, "e": 132, "s": 54, "text": "Prerequisite – Pushdown automata, Pushdown automata acceptance by final state" }, { "code": null, "e": 208, "s": 132, "text": "Problem – Design a non deterministic PDA for accepting the language , i.e.," }, { "code": null, "e": 271, "s": 208, "text": "L = {aab, abb, aaab, abbb, aaaab, aaabb, aabbb, abbbb ......} " }, { "code": null, "e": 351, "s": 271, "text": "In each of the string, the number of a’s are followed by unequal number of b’s." }, { "code": null, "e": 624, "s": 351, "text": "Explanation –Here, we need to maintain the order of a’s and b’s. That is, all the a’s are coming first and then all the b’s are coming. Thus, we need a stack along with the state diagram. The count of a’s and b’s is maintained by the stack. We will take 2 stack alphabets:" }, { "code": null, "e": 636, "s": 624, "text": " = { a, z }" }, { "code": null, "e": 643, "s": 636, "text": "Where," }, { "code": null, "e": 698, "s": 643, "text": " = set of all the stack alphabetz = stack start symbol" }, { "code": null, "e": 1110, "s": 698, "text": "Approach used in the construction of PDA –As we want to design a NPDA, thus every time ‘a’ comes before ‘b’. When ‘a’ comes then push it in stack and if again ‘a’ comes then also push it. After that, when ‘b’ comes then pop one ‘a’ from the stack each time. So, at the end if the stack becomes empty and b is coming or string is end and stack is not empty then we can say that the string is accepted by the PDA." }, { "code": null, "e": 1139, "s": 1110, "text": "Stack transition functions –" }, { "code": null, "e": 1267, "s": 1139, "text": "(q0, a, z) (q0, az)\n(q0, a, a) (q0, aa)\n(q0, b, a) (q1, )\n(q1, b, a) (q1, )\n(q1, , a) (qf, a) \n(q1, b, z) (qf, z) \n" }, { "code": null, "e": 1335, "s": 1267, "text": "Where, q0 = Initial stateqf = Final state = indicates pop operation" }, { "code": null, "e": 1362, "s": 1335, "text": "State Transition Diagram –" }, { "code": null, "e": 1438, "s": 1362, "text": "So, this is our required non deterministic PDA for accepting the language ." }, { "code": null, "e": 1452, "s": 1438, "text": "mitalibhola94" }, { "code": null, "e": 1460, "s": 1452, "text": "GATE CS" }, { "code": null, "e": 1493, "s": 1460, "text": "Theory of Computation & Automata" }, { "code": null, "e": 1591, "s": 1493, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1612, "s": 1591, "text": "Normal Forms in DBMS" }, { "code": null, "e": 1661, "s": 1612, "text": "Page Replacement Algorithms in Operating Systems" }, { "code": null, "e": 1695, "s": 1661, "text": "Inter Process Communication (IPC)" }, { "code": null, "e": 1736, "s": 1695, "text": "Introduction of Operating System - Set 1" }, { "code": null, "e": 1768, "s": 1736, "text": "Differences between TCP and UDP" }, { "code": null, "e": 1799, "s": 1768, "text": "Difference between DFA and NFA" }, { "code": null, "e": 1821, "s": 1799, "text": "Turing Machine in TOC" }, { "code": null, "e": 1864, "s": 1821, "text": "Chomsky Hierarchy in Theory of Computation" }, { "code": null, "e": 1902, "s": 1864, "text": "Boyer-Moore Majority Voting Algorithm" } ]
Flutter – Scrollable Text
15 Jan, 2021 In this article, we are going to make a Flutter application in which we will add a Text Widget that can be scrolled horizontally or vertically. These can have a wide range of applications depending upon the needs of the users. Here we will be implementing the simplest form of scrollable text. We can make the text scrollable in flutter using these 2 widgets: Expanded Class: A widget that expands a child of a Row, Column, or Flex so that the child fills the available space. SingleChildScrollView Class: A box in which a single widget can be scrolled. We have to wrap the Text widget within SingleChildScrollView widget and further wrap the SingleChildScrollView widget within the Expanded widget like this : Expanded( child: SingleChildScrollView( scrollDirection: Axis.horizontal, child: Text( "GeeksForGeeks : Learn Anything, Anywhere", style: TextStyle( color: Colors.green, fontWeight: FontWeight.bold, fontSize: 20.0, ), ), ), ); Let’s look into some example now: Example 1: Horizontal Scrolling Follow the below steps to implement horizontal scrolling in a Text Widget: Step 1: Create a new flutter project in Android Studio. Step 2: Make the layout using widgets Go to the main.dart file and refer to the following code. Below is the code for the main.dart file. Dart import 'package:flutter/material.dart'; void main() { runApp(MaterialApp( home: Scaffold( //adding App Bar appBar: AppBar( backgroundColor: Color.fromRGBO(15, 157, 88, 1), title: Text( "GeeksForGeeks", style: TextStyle( color: Colors.white, ), ), ), body: MyApp(), ), ));} class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return Center( child: Container( // adding margin margin: const EdgeInsets.all(15.0), // adding padding padding: const EdgeInsets.all(3.0), decoration: BoxDecoration( // adding borders around the widget border: Border.all( color: Colors.blueAccent, width: 5.0, ), ), // SingleChildScrollView should be // wrapped in an Expanded Widget child: Expanded( //contains a single child which is scrollable child: SingleChildScrollView( //for horizontal scrolling scrollDirection: Axis.horizontal, child: Text( "GeeksForGeeks is a good platform to learn programming." " It is an educational website.", style: TextStyle( color: Colors.green, fontWeight: FontWeight.bold, fontSize: 20.0, letterSpacing: 3, wordSpacing: 3, ), ), ), ), ), ); }} Output: Example 2: Vertical Scrolling For vertical scrolling of the text follow Step 1 and Step 2 of the first example and change the scrolling direction to vertical as shown below: scrollDirection: Axis.vertical The main.dart file Dart import 'package:flutter/material.dart'; void main() { runApp(MaterialApp( home: Scaffold( // adding App Bar appBar: AppBar( backgroundColor: Color.fromRGBO(15, 157, 88, 1), title: Text( "GeeksForGeeks", style: TextStyle( color: Colors.white, ), ), ), body: MyApp(), ), ));} class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return Center( child: Container( // adding margin margin: const EdgeInsets.all(15.0), // adding padding padding: const EdgeInsets.all(3.0), // height should be fixed for vertical scrolling height: 80.0, decoration: BoxDecoration( // adding borders around the widget border: Border.all( color: Colors.blueAccent, width: 5.0, ), ), // SingleChildScrollView should be // wrapped in an Expanded Widget child: Expanded( // SingleChildScrollView contains a // single child which is scrollable child: SingleChildScrollView( // for Vertical scrolling scrollDirection: Axis.vertical, child: Text( "GeeksForGeeks is a good platform to learn programming." " It is an educational website.", style: TextStyle( color: Colors.green, fontWeight: FontWeight.bold, fontSize: 20.0, letterSpacing: 3, wordSpacing: 3, ), ), ), ), ), ); }} Output: android Flutter Dart Flutter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n15 Jan, 2021" }, { "code": null, "e": 348, "s": 54, "text": "In this article, we are going to make a Flutter application in which we will add a Text Widget that can be scrolled horizontally or vertically. These can have a wide range of applications depending upon the needs of the users. Here we will be implementing the simplest form of scrollable text." }, { "code": null, "e": 414, "s": 348, "text": "We can make the text scrollable in flutter using these 2 widgets:" }, { "code": null, "e": 531, "s": 414, "text": "Expanded Class: A widget that expands a child of a Row, Column, or Flex so that the child fills the available space." }, { "code": null, "e": 608, "s": 531, "text": "SingleChildScrollView Class: A box in which a single widget can be scrolled." }, { "code": null, "e": 765, "s": 608, "text": "We have to wrap the Text widget within SingleChildScrollView widget and further wrap the SingleChildScrollView widget within the Expanded widget like this :" }, { "code": null, "e": 1146, "s": 765, "text": "Expanded(\n child: SingleChildScrollView(\n scrollDirection: Axis.horizontal,\n child: Text(\n \"GeeksForGeeks : Learn Anything, Anywhere\",\n style: TextStyle(\n color: Colors.green,\n fontWeight: FontWeight.bold,\n fontSize: 20.0,\n ),\n ),\n ),\n );" }, { "code": null, "e": 1180, "s": 1146, "text": "Let’s look into some example now:" }, { "code": null, "e": 1212, "s": 1180, "text": "Example 1: Horizontal Scrolling" }, { "code": null, "e": 1287, "s": 1212, "text": "Follow the below steps to implement horizontal scrolling in a Text Widget:" }, { "code": null, "e": 1343, "s": 1287, "text": "Step 1: Create a new flutter project in Android Studio." }, { "code": null, "e": 1381, "s": 1343, "text": "Step 2: Make the layout using widgets" }, { "code": null, "e": 1481, "s": 1381, "text": "Go to the main.dart file and refer to the following code. Below is the code for the main.dart file." }, { "code": null, "e": 1486, "s": 1481, "text": "Dart" }, { "code": "import 'package:flutter/material.dart'; void main() { runApp(MaterialApp( home: Scaffold( //adding App Bar appBar: AppBar( backgroundColor: Color.fromRGBO(15, 157, 88, 1), title: Text( \"GeeksForGeeks\", style: TextStyle( color: Colors.white, ), ), ), body: MyApp(), ), ));} class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return Center( child: Container( // adding margin margin: const EdgeInsets.all(15.0), // adding padding padding: const EdgeInsets.all(3.0), decoration: BoxDecoration( // adding borders around the widget border: Border.all( color: Colors.blueAccent, width: 5.0, ), ), // SingleChildScrollView should be // wrapped in an Expanded Widget child: Expanded( //contains a single child which is scrollable child: SingleChildScrollView( //for horizontal scrolling scrollDirection: Axis.horizontal, child: Text( \"GeeksForGeeks is a good platform to learn programming.\" \" It is an educational website.\", style: TextStyle( color: Colors.green, fontWeight: FontWeight.bold, fontSize: 20.0, letterSpacing: 3, wordSpacing: 3, ), ), ), ), ), ); }}", "e": 3059, "s": 1486, "text": null }, { "code": null, "e": 3067, "s": 3059, "text": "Output:" }, { "code": null, "e": 3097, "s": 3067, "text": "Example 2: Vertical Scrolling" }, { "code": null, "e": 3241, "s": 3097, "text": "For vertical scrolling of the text follow Step 1 and Step 2 of the first example and change the scrolling direction to vertical as shown below:" }, { "code": null, "e": 3272, "s": 3241, "text": "scrollDirection: Axis.vertical" }, { "code": null, "e": 3291, "s": 3272, "text": "The main.dart file" }, { "code": null, "e": 3296, "s": 3291, "text": "Dart" }, { "code": "import 'package:flutter/material.dart'; void main() { runApp(MaterialApp( home: Scaffold( // adding App Bar appBar: AppBar( backgroundColor: Color.fromRGBO(15, 157, 88, 1), title: Text( \"GeeksForGeeks\", style: TextStyle( color: Colors.white, ), ), ), body: MyApp(), ), ));} class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return Center( child: Container( // adding margin margin: const EdgeInsets.all(15.0), // adding padding padding: const EdgeInsets.all(3.0), // height should be fixed for vertical scrolling height: 80.0, decoration: BoxDecoration( // adding borders around the widget border: Border.all( color: Colors.blueAccent, width: 5.0, ), ), // SingleChildScrollView should be // wrapped in an Expanded Widget child: Expanded( // SingleChildScrollView contains a // single child which is scrollable child: SingleChildScrollView( // for Vertical scrolling scrollDirection: Axis.vertical, child: Text( \"GeeksForGeeks is a good platform to learn programming.\" \" It is an educational website.\", style: TextStyle( color: Colors.green, fontWeight: FontWeight.bold, fontSize: 20.0, letterSpacing: 3, wordSpacing: 3, ), ), ), ), ), ); }}", "e": 5001, "s": 3296, "text": null }, { "code": null, "e": 5009, "s": 5001, "text": "Output:" }, { "code": null, "e": 5017, "s": 5009, "text": "android" }, { "code": null, "e": 5025, "s": 5017, "text": "Flutter" }, { "code": null, "e": 5030, "s": 5025, "text": "Dart" }, { "code": null, "e": 5038, "s": 5030, "text": "Flutter" } ]
Find the k most frequent words from data set in Python
10 Dec, 2017 Given the data set, we can find k number of most frequent words. The solution of this problem already present as Find the k most frequent words from a file. But we can solve this problem very efficiently in Python with the help of some high performance modules. In order to do this, we’ll use a high performance data type module, which is collections. This module got some specialized container datatypes and we will use counter class from this module.Examples : Input : "John is the son of John second. Second son of John second is William second." Output : [('second', 4), ('John', 3), ('son', 2), ('is', 2)] Explanation : 1. The string will converted into list like this : ['John', 'is', 'the', 'son', 'of', 'John', 'second', 'Second', 'son', 'of', 'John', 'second', 'is', 'William', 'second'] 2. Now 'most_common(4)' will return four most frequent words and its count in tuple. Input : "geeks for geeks is for geeks. By geeks and for the geeks." Output : [('geeks', 5), ('for', 3)] Explanation : most_common(2) will return two most frequent words and their count. Approach : Import Counter class from collections module.Split the string into list using split(), it will return the lists of words. Now pass the list to the instance of Counter classThe function 'most-common()' inside Counter will return the list of most frequent words from list and its count. Import Counter class from collections module.Split the string into list using split(), it will return the lists of words. Now pass the list to the instance of Counter classThe function 'most-common()' inside Counter will return the list of most frequent words from list and its count. Import Counter class from collections module. Split the string into list using split(), it will return the lists of words. Now pass the list to the instance of Counter class The function 'most-common()' inside Counter will return the list of most frequent words from list and its count. Below is Python implementation of above approach : # Python program to find the k most frequent words# from data setfrom collections import Counter data_set = "Welcome to the world of Geeks " \"This portal has been created to provide well written well" \"thought and well explained solutions for selected questions " \"If you like Geeks for Geeks and would like to contribute " \"here is your chance You can write article and mail your article " \" to contribute at geeksforgeeks org See your article appearing on " \"the Geeks for Geeks main page and help thousands of other Geeks. " \ # split() returns list of all the words in the stringsplit_it = data_set.split() # Pass the split_it list to instance of Counter class.Counter = Counter(split_it) # most_common() produces k frequently encountered# input values and their respective counts.most_occur = Counter.most_common(4) print(most_occur) Output : [('Geeks', 5), ('to', 4), ('and', 4), ('article', 3)] Order-Statistics python-string Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n10 Dec, 2017" }, { "code": null, "e": 117, "s": 52, "text": "Given the data set, we can find k number of most frequent words." }, { "code": null, "e": 314, "s": 117, "text": "The solution of this problem already present as Find the k most frequent words from a file. But we can solve this problem very efficiently in Python with the help of some high performance modules." }, { "code": null, "e": 515, "s": 314, "text": "In order to do this, we’ll use a high performance data type module, which is collections. This module got some specialized container datatypes and we will use counter class from this module.Examples :" }, { "code": null, "e": 1165, "s": 515, "text": "Input : \"John is the son of John second. \n Second son of John second is William second.\"\nOutput : [('second', 4), ('John', 3), ('son', 2), ('is', 2)]\n\nExplanation :\n1. The string will converted into list like this :\n ['John', 'is', 'the', 'son', 'of', 'John', \n 'second', 'Second', 'son', 'of', 'John', \n 'second', 'is', 'William', 'second']\n2. Now 'most_common(4)' will return four most \n frequent words and its count in tuple. \n\n\nInput : \"geeks for geeks is for geeks. By geeks\n and for the geeks.\"\nOutput : [('geeks', 5), ('for', 3)]\n\nExplanation :\nmost_common(2) will return two most frequent words and their count.\n" }, { "code": null, "e": 1176, "s": 1165, "text": "Approach :" }, { "code": null, "e": 1461, "s": 1176, "text": "Import Counter class from collections module.Split the string into list using split(), it will\nreturn the lists of words. Now pass the list to the instance of Counter classThe function 'most-common()' inside Counter will return\nthe list of most frequent words from list and its count." }, { "code": null, "e": 1746, "s": 1461, "text": "Import Counter class from collections module.Split the string into list using split(), it will\nreturn the lists of words. Now pass the list to the instance of Counter classThe function 'most-common()' inside Counter will return\nthe list of most frequent words from list and its count." }, { "code": null, "e": 1792, "s": 1746, "text": "Import Counter class from collections module." }, { "code": null, "e": 1870, "s": 1792, "text": "Split the string into list using split(), it will\nreturn the lists of words. " }, { "code": null, "e": 1921, "s": 1870, "text": "Now pass the list to the instance of Counter class" }, { "code": null, "e": 2034, "s": 1921, "text": "The function 'most-common()' inside Counter will return\nthe list of most frequent words from list and its count." }, { "code": null, "e": 2085, "s": 2034, "text": "Below is Python implementation of above approach :" }, { "code": "# Python program to find the k most frequent words# from data setfrom collections import Counter data_set = \"Welcome to the world of Geeks \" \\\"This portal has been created to provide well written well\" \\\"thought and well explained solutions for selected questions \" \\\"If you like Geeks for Geeks and would like to contribute \" \\\"here is your chance You can write article and mail your article \" \\\" to contribute at geeksforgeeks org See your article appearing on \" \\\"the Geeks for Geeks main page and help thousands of other Geeks. \" \\ # split() returns list of all the words in the stringsplit_it = data_set.split() # Pass the split_it list to instance of Counter class.Counter = Counter(split_it) # most_common() produces k frequently encountered# input values and their respective counts.most_occur = Counter.most_common(4) print(most_occur)", "e": 2935, "s": 2085, "text": null }, { "code": null, "e": 2944, "s": 2935, "text": "Output :" }, { "code": null, "e": 2999, "s": 2944, "text": "[('Geeks', 5), ('to', 4), ('and', 4), ('article', 3)]\n" }, { "code": null, "e": 3016, "s": 2999, "text": "Order-Statistics" }, { "code": null, "e": 3030, "s": 3016, "text": "python-string" }, { "code": null, "e": 3037, "s": 3030, "text": "Python" } ]
ML | Implement Face recognition using k-NN with scikit-learn
15 Mar, 2019 k-Nearest Neighbors: k-NN is one of the most basic classification algorithms in machine learning. It belongs to the supervised learning category of machine learning. k-NN is often used in search applications where you are looking for “similar” items. The way we measure similarity is by creating a vector representation of the items, and then compare the vectors using an appropriate distance metric (like the Euclidean distance, for example). It is generally used in data mining, pattern recognition, recommender systems and intrusion detection. Libraries used are: OpenCV2PandasNumpyScikit-learn Dataset used:We used haarcascade_frontalface_default.xml dataset which is easily available online and also you can download it from this link. Scikit-learn:scikit-learn provides a range of supervised and unsupervised learning algorithms via a consistent interface in Python.This library is built upon SciPy that must be installed on your devices in order to use scikit_learn. Face-Recognition :This includes three Python files where the first one is used to detect the face and storing it in a list format, second one is used to store the data in ‘.csv’ file format and the third one is used recognize the face. facedetect.py – # this file is used to detect face # and then store the data of the faceimport cv2import numpy as np # import the file where data is# stored in a csv file formatimport npwriter name = input("Enter your name: ") # this is used to access the web-cam# in order to capture framescap = cv2.VideoCapture(0) classifier = cv2.CascadeClassifier("../dataset/haarcascade_frontalface_default.xml") # this is class used to detect the faces as provided# with a haarcascade_frontalface_default.xml file as dataf_list = [] while True: ret, frame = cap.read() # converting the image into gray # scale as it is easy for detection gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # detect multiscale, detects the face and its coordinates faces = classifier.detectMultiScale(gray, 1.5, 5) # this is used to detect the face which # is closest to the web-cam on the first position faces = sorted(faces, key = lambda x: x[2]*x[3], reverse = True) # only the first detected face is used faces = faces[:1] # len(faces) is the number of # faces showing in a frame if len(faces) == 1: # this is removing from tuple format face = faces[0] # storing the coordinates of the # face in different variables x, y, w, h = face # this is will show the face # that is being detected im_face = frame[y:y + h, x:x + w] cv2.imshow("face", im_face) if not ret: continue cv2.imshow("full", frame) key = cv2.waitKey(1) # this will break the execution of the program # on pressing 'q' and will click the frame on pressing 'c' if key & 0xFF == ord('q'): break elif key & 0xFF == ord('c'): if len(faces) == 1: gray_face = cv2.cvtColor(im_face, cv2.COLOR_BGR2GRAY) gray_face = cv2.resize(gray_face, (100, 100)) print(len(f_list), type(gray_face), gray_face.shape) # this will append the face's coordinates in f_list f_list.append(gray_face.reshape(-1)) else: print("face not found") # this will store the data for detected # face 10 times in order to increase accuracy if len(f_list) == 10: break # declared in npwriternpwriter.write(name, np.array(f_list)) cap.release()cv2.destroyAllWindows() npwriter.py – Create/Update ‘.csv’: file import pandas as pdimport numpy as npimport os.path f_name = "face_data.csv" # storing the data into a csv filedef write(name, data): if os.path.isfile(f_name): df = pd.read_csv(f_name, index_col = 0) latest = pd.DataFrame(data, columns = map(str, range(10000))) latest["name"] = name df = pd.concat((df, latest), ignore_index = True, sort = False) else: # Providing range only because the data # here is already flattened for when # it was store in f_list df = pd.DataFrame(data, columns = map(str, range(10000))) df["name"] = name df.to_csv(f_name) recog.py – Face-recognizer # this one is used to recognize the # face after training the model with# our data stored using knnimport cv2import numpy as npimport pandas as pd from npwriter import f_namefrom sklearn.neighbors import KNeighborsClassifier # reading the datadata = pd.read_csv(f_name).values # data partitionX, Y = data[:, 1:-1], data[:, -1] print(X, Y) # Knn function calling with k = 5model = KNeighborsClassifier(n_neighbors = 5) # fdtraining of modelmodel.fit(X, Y) cap = cv2.VideoCapture(0) classifier = cv2.CascadeClassifier("../dataset/haarcascade_frontalface_default.xml") f_list = [] while True: ret, frame = cap.read() gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) faces = classifier.detectMultiScale(gray, 1.5, 5) X_test = [] # Testing data for face in faces: x, y, w, h = face im_face = gray[y:y + h, x:x + w] im_face = cv2.resize(im_face, (100, 100)) X_test.append(im_face.reshape(-1)) if len(faces)>0: response = model.predict(np.array(X_test)) # prediction of result using knn for i, face in enumerate(faces): x, y, w, h = face # drawing a rectangle on the detected face cv2.rectangle(frame, (x, y), (x + w, y + h), (255, 0, 0), 3) # adding detected/predicted name for the face cv2.putText(frame, response[i], (x-50, y-50), cv2.FONT_HERSHEY_DUPLEX, 2, (0, 255, 0), 3) cv2.imshow("full", frame) key = cv2.waitKey(1) if key & 0xFF == ord("q") : break cap.release()cv2.destroyAllWindows() Output: Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Recurrent Neural Network Support Vector Machine Algorithm ML | Monte Carlo Tree Search (MCTS) Markov Decision Process DBSCAN Clustering in ML | Density based clustering Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function Python Dictionary How to get column names in Pandas dataframe
[ { "code": null, "e": 54, "s": 26, "text": "\n15 Mar, 2019" }, { "code": null, "e": 75, "s": 54, "text": "k-Nearest Neighbors:" }, { "code": null, "e": 498, "s": 75, "text": "k-NN is one of the most basic classification algorithms in machine learning. It belongs to the supervised learning category of machine learning. k-NN is often used in search applications where you are looking for “similar” items. The way we measure similarity is by creating a vector representation of the items, and then compare the vectors using an appropriate distance metric (like the Euclidean distance, for example)." }, { "code": null, "e": 601, "s": 498, "text": "It is generally used in data mining, pattern recognition, recommender systems and intrusion detection." }, { "code": null, "e": 621, "s": 601, "text": "Libraries used are:" }, { "code": null, "e": 652, "s": 621, "text": "OpenCV2PandasNumpyScikit-learn" }, { "code": null, "e": 795, "s": 652, "text": "Dataset used:We used haarcascade_frontalface_default.xml dataset which is easily available online and also you can download it from this link." }, { "code": null, "e": 1028, "s": 795, "text": "Scikit-learn:scikit-learn provides a range of supervised and unsupervised learning algorithms via a consistent interface in Python.This library is built upon SciPy that must be installed on your devices in order to use scikit_learn." }, { "code": null, "e": 1264, "s": 1028, "text": "Face-Recognition :This includes three Python files where the first one is used to detect the face and storing it in a list format, second one is used to store the data in ‘.csv’ file format and the third one is used recognize the face." }, { "code": null, "e": 1280, "s": 1264, "text": "facedetect.py –" }, { "code": "# this file is used to detect face # and then store the data of the faceimport cv2import numpy as np # import the file where data is# stored in a csv file formatimport npwriter name = input(\"Enter your name: \") # this is used to access the web-cam# in order to capture framescap = cv2.VideoCapture(0) classifier = cv2.CascadeClassifier(\"../dataset/haarcascade_frontalface_default.xml\") # this is class used to detect the faces as provided# with a haarcascade_frontalface_default.xml file as dataf_list = [] while True: ret, frame = cap.read() # converting the image into gray # scale as it is easy for detection gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # detect multiscale, detects the face and its coordinates faces = classifier.detectMultiScale(gray, 1.5, 5) # this is used to detect the face which # is closest to the web-cam on the first position faces = sorted(faces, key = lambda x: x[2]*x[3], reverse = True) # only the first detected face is used faces = faces[:1] # len(faces) is the number of # faces showing in a frame if len(faces) == 1: # this is removing from tuple format face = faces[0] # storing the coordinates of the # face in different variables x, y, w, h = face # this is will show the face # that is being detected im_face = frame[y:y + h, x:x + w] cv2.imshow(\"face\", im_face) if not ret: continue cv2.imshow(\"full\", frame) key = cv2.waitKey(1) # this will break the execution of the program # on pressing 'q' and will click the frame on pressing 'c' if key & 0xFF == ord('q'): break elif key & 0xFF == ord('c'): if len(faces) == 1: gray_face = cv2.cvtColor(im_face, cv2.COLOR_BGR2GRAY) gray_face = cv2.resize(gray_face, (100, 100)) print(len(f_list), type(gray_face), gray_face.shape) # this will append the face's coordinates in f_list f_list.append(gray_face.reshape(-1)) else: print(\"face not found\") # this will store the data for detected # face 10 times in order to increase accuracy if len(f_list) == 10: break # declared in npwriternpwriter.write(name, np.array(f_list)) cap.release()cv2.destroyAllWindows()", "e": 3700, "s": 1280, "text": null }, { "code": null, "e": 3742, "s": 3700, "text": " npwriter.py – Create/Update ‘.csv’: file" }, { "code": "import pandas as pdimport numpy as npimport os.path f_name = \"face_data.csv\" # storing the data into a csv filedef write(name, data): if os.path.isfile(f_name): df = pd.read_csv(f_name, index_col = 0) latest = pd.DataFrame(data, columns = map(str, range(10000))) latest[\"name\"] = name df = pd.concat((df, latest), ignore_index = True, sort = False) else: # Providing range only because the data # here is already flattened for when # it was store in f_list df = pd.DataFrame(data, columns = map(str, range(10000))) df[\"name\"] = name df.to_csv(f_name)", "e": 4381, "s": 3742, "text": null }, { "code": null, "e": 4409, "s": 4381, "text": " recog.py – Face-recognizer" }, { "code": "# this one is used to recognize the # face after training the model with# our data stored using knnimport cv2import numpy as npimport pandas as pd from npwriter import f_namefrom sklearn.neighbors import KNeighborsClassifier # reading the datadata = pd.read_csv(f_name).values # data partitionX, Y = data[:, 1:-1], data[:, -1] print(X, Y) # Knn function calling with k = 5model = KNeighborsClassifier(n_neighbors = 5) # fdtraining of modelmodel.fit(X, Y) cap = cv2.VideoCapture(0) classifier = cv2.CascadeClassifier(\"../dataset/haarcascade_frontalface_default.xml\") f_list = [] while True: ret, frame = cap.read() gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) faces = classifier.detectMultiScale(gray, 1.5, 5) X_test = [] # Testing data for face in faces: x, y, w, h = face im_face = gray[y:y + h, x:x + w] im_face = cv2.resize(im_face, (100, 100)) X_test.append(im_face.reshape(-1)) if len(faces)>0: response = model.predict(np.array(X_test)) # prediction of result using knn for i, face in enumerate(faces): x, y, w, h = face # drawing a rectangle on the detected face cv2.rectangle(frame, (x, y), (x + w, y + h), (255, 0, 0), 3) # adding detected/predicted name for the face cv2.putText(frame, response[i], (x-50, y-50), cv2.FONT_HERSHEY_DUPLEX, 2, (0, 255, 0), 3) cv2.imshow(\"full\", frame) key = cv2.waitKey(1) if key & 0xFF == ord(\"q\") : break cap.release()cv2.destroyAllWindows()", "e": 6086, "s": 4409, "text": null }, { "code": null, "e": 6094, "s": 6086, "text": "Output:" }, { "code": null, "e": 6111, "s": 6094, "text": "Machine Learning" }, { "code": null, "e": 6118, "s": 6111, "text": "Python" }, { "code": null, "e": 6135, "s": 6118, "text": "Machine Learning" }, { "code": null, "e": 6233, "s": 6135, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6274, "s": 6233, "text": "Introduction to Recurrent Neural Network" }, { "code": null, "e": 6307, "s": 6274, "text": "Support Vector Machine Algorithm" }, { "code": null, "e": 6343, "s": 6307, "text": "ML | Monte Carlo Tree Search (MCTS)" }, { "code": null, "e": 6367, "s": 6343, "text": "Markov Decision Process" }, { "code": null, "e": 6418, "s": 6367, "text": "DBSCAN Clustering in ML | Density based clustering" }, { "code": null, "e": 6446, "s": 6418, "text": "Read JSON file using Python" }, { "code": null, "e": 6496, "s": 6446, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 6518, "s": 6496, "text": "Python map() function" }, { "code": null, "e": 6536, "s": 6518, "text": "Python Dictionary" } ]
numpy.sort() in Python
29 Nov, 2018 numpy.sort() : This function returns a sorted copy of an array. Parameters : arr : Array to be sorted.axis : Axis along which we need array to be started.order : This argument specifies which fields to compare first.kind : [‘quicksort’{default}, ‘mergesort’, ‘heapsort’]Sorting algorithm. Return : Sorted Array # importing librariesimport numpy as np # sort along the first axisa = np.array([[12, 15], [10, 1]])arr1 = np.sort(a, axis = 0) print ("Along first axis : \n", arr1) # sort along the last axisa = np.array([[10, 15], [12, 1]])arr2 = np.sort(a, axis = -1) print ("\nAlong first axis : \n", arr2) a = np.array([[12, 15], [10, 1]])arr1 = np.sort(a, axis = None) print ("\nAlong none axis : \n", arr1) Output : Along first axis : [[10 1] [12 15]] Along first axis : [[10 15] [ 1 12]] Along none axis : [ 1 10 12 15] Python numpy-Sorting Searching Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Python OOPs Concepts Iterate over a list in Python Introduction To PYTHON
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Nov, 2018" }, { "code": null, "e": 92, "s": 28, "text": "numpy.sort() : This function returns a sorted copy of an array." }, { "code": null, "e": 105, "s": 92, "text": "Parameters :" }, { "code": null, "e": 317, "s": 105, "text": "arr : Array to be sorted.axis : Axis along which we need array to be started.order : This argument specifies which fields to compare first.kind : [‘quicksort’{default}, ‘mergesort’, ‘heapsort’]Sorting algorithm." }, { "code": null, "e": 326, "s": 317, "text": "Return :" }, { "code": null, "e": 339, "s": 326, "text": "Sorted Array" }, { "code": "# importing librariesimport numpy as np # sort along the first axisa = np.array([[12, 15], [10, 1]])arr1 = np.sort(a, axis = 0) print (\"Along first axis : \\n\", arr1) # sort along the last axisa = np.array([[10, 15], [12, 1]])arr2 = np.sort(a, axis = -1) print (\"\\nAlong first axis : \\n\", arr2) a = np.array([[12, 15], [10, 1]])arr1 = np.sort(a, axis = None) print (\"\\nAlong none axis : \\n\", arr1)", "e": 772, "s": 339, "text": null }, { "code": null, "e": 781, "s": 772, "text": "Output :" }, { "code": null, "e": 897, "s": 781, "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": 928, "s": 897, "text": "Python numpy-Sorting Searching" }, { "code": null, "e": 941, "s": 928, "text": "Python-numpy" }, { "code": null, "e": 948, "s": 941, "text": "Python" }, { "code": null, "e": 1046, "s": 948, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1088, "s": 1046, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1110, "s": 1088, "text": "Enumerate() in Python" }, { "code": null, "e": 1145, "s": 1110, "text": "Read a file line by line in Python" }, { "code": null, "e": 1171, "s": 1145, "text": "Python String | replace()" }, { "code": null, "e": 1203, "s": 1171, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1232, "s": 1203, "text": "*args and **kwargs in Python" }, { "code": null, "e": 1259, "s": 1232, "text": "Python Classes and Objects" }, { "code": null, "e": 1280, "s": 1259, "text": "Python OOPs Concepts" }, { "code": null, "e": 1310, "s": 1280, "text": "Iterate over a list in Python" } ]
Vector removeElement() method in Java with Example
24 Dec, 2018 The java.util.Vector.removeElement() method is used to remove first occurrence of particular object. If object is not found then it returns false else it returns true.If a particular object is present inside vector and removeElement() method call on that vector element then this method reduces vector size by 1. Syntax: public boolean removeElement(Object obj) Parameters: This function accepts object as parameter which is to be removed. Return Type: On Successful of deletion this function returns True otherwise this function returns False. Exceptions:This method does not raise any exception. Below programs illustrates the Vector.removeElement() function. Program 1: // Java program to understand// about vector.removeElement() function // because vector is present in this packageimport java.util.*; // Driver Codepublic class vector_demo { // main method begins here public static void main(String[] args) { // creating vector type object Vector<Integer> v = new Vector<Integer>(); // inserting elements into the vector v.add(1); v.add(2); v.add(3); v.add(4); v.add(5); v.add(6); // printing vector before deleting element System.out.println("Before deleting"); System.out.println("Vector: " + v); System.out.println("Size: " + v.size()); System.out.println("\nAfter deleting"); // trying to deleting object 3 boolean flag = v.removeElement(3); if (flag) { System.out.println("Element '3' has been removed"); } else { System.out.println("Element '3' is not present in Vector"); } System.out.println("Vector: " + v); System.out.println("Size: " + v.size()); }} Before deleting Vector: [1, 2, 3, 4, 5, 6] Size: 6 After deleting Element '3' has been removed Vector: [1, 2, 4, 5, 6] Size: 5 Example 2: // Java program to understand// about vector.removeElement() function // because vector is present in this packageimport java.util.*; // Driver Codepublic class vector_demo { // main method begins here public static void main(String[] args) { // creating vector type object Vector<Integer> v = new Vector<Integer>(); // inserting elements into the vector v.add(1); v.add(2); v.add(3); v.add(4); v.add(5); v.add(6); // printing vector before deleting element System.out.println("Before deleting"); System.out.println("Vector: " + v); System.out.println("Size: " + v.size()); System.out.println("\nAfter deleting"); // trying to deleting object 15 boolean flag = v.removeElement(15); // since object 15 is not present flag will be false if (flag) { System.out.println("Element '15' has been removed"); } else { System.out.println("Element '15' is not present in Vector"); } System.out.println("Vector: " + v); System.out.println("Size: " + v.size()); }} Before deleting Vector: [1, 2, 3, 4, 5, 6] Size: 6 After deleting Element '15' is not present in Vector Vector: [1, 2, 3, 4, 5, 6] Size: 6 Java - util package Java-Collections Java-Functions Java-Vector Picked Java Technical Scripter Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Dec, 2018" }, { "code": null, "e": 341, "s": 28, "text": "The java.util.Vector.removeElement() method is used to remove first occurrence of particular object. If object is not found then it returns false else it returns true.If a particular object is present inside vector and removeElement() method call on that vector element then this method reduces vector size by 1." }, { "code": null, "e": 349, "s": 341, "text": "Syntax:" }, { "code": null, "e": 391, "s": 349, "text": "public boolean removeElement(Object obj)\n" }, { "code": null, "e": 469, "s": 391, "text": "Parameters: This function accepts object as parameter which is to be removed." }, { "code": null, "e": 574, "s": 469, "text": "Return Type: On Successful of deletion this function returns True otherwise this function returns False." }, { "code": null, "e": 627, "s": 574, "text": "Exceptions:This method does not raise any exception." }, { "code": null, "e": 691, "s": 627, "text": "Below programs illustrates the Vector.removeElement() function." }, { "code": null, "e": 702, "s": 691, "text": "Program 1:" }, { "code": "// Java program to understand// about vector.removeElement() function // because vector is present in this packageimport java.util.*; // Driver Codepublic class vector_demo { // main method begins here public static void main(String[] args) { // creating vector type object Vector<Integer> v = new Vector<Integer>(); // inserting elements into the vector v.add(1); v.add(2); v.add(3); v.add(4); v.add(5); v.add(6); // printing vector before deleting element System.out.println(\"Before deleting\"); System.out.println(\"Vector: \" + v); System.out.println(\"Size: \" + v.size()); System.out.println(\"\\nAfter deleting\"); // trying to deleting object 3 boolean flag = v.removeElement(3); if (flag) { System.out.println(\"Element '3' has been removed\"); } else { System.out.println(\"Element '3' is not present in Vector\"); } System.out.println(\"Vector: \" + v); System.out.println(\"Size: \" + v.size()); }}", "e": 1808, "s": 702, "text": null }, { "code": null, "e": 1937, "s": 1808, "text": "Before deleting\nVector: [1, 2, 3, 4, 5, 6]\nSize: 6\n\nAfter deleting\nElement '3' has been removed\nVector: [1, 2, 4, 5, 6]\nSize: 5\n" }, { "code": null, "e": 1948, "s": 1937, "text": "Example 2:" }, { "code": "// Java program to understand// about vector.removeElement() function // because vector is present in this packageimport java.util.*; // Driver Codepublic class vector_demo { // main method begins here public static void main(String[] args) { // creating vector type object Vector<Integer> v = new Vector<Integer>(); // inserting elements into the vector v.add(1); v.add(2); v.add(3); v.add(4); v.add(5); v.add(6); // printing vector before deleting element System.out.println(\"Before deleting\"); System.out.println(\"Vector: \" + v); System.out.println(\"Size: \" + v.size()); System.out.println(\"\\nAfter deleting\"); // trying to deleting object 15 boolean flag = v.removeElement(15); // since object 15 is not present flag will be false if (flag) { System.out.println(\"Element '15' has been removed\"); } else { System.out.println(\"Element '15' is not present in Vector\"); } System.out.println(\"Vector: \" + v); System.out.println(\"Size: \" + v.size()); }}", "e": 3107, "s": 1948, "text": null }, { "code": null, "e": 3248, "s": 3107, "text": "Before deleting\nVector: [1, 2, 3, 4, 5, 6]\nSize: 6\n\nAfter deleting\nElement '15' is not present in Vector\nVector: [1, 2, 3, 4, 5, 6]\nSize: 6\n" }, { "code": null, "e": 3268, "s": 3248, "text": "Java - util package" }, { "code": null, "e": 3285, "s": 3268, "text": "Java-Collections" }, { "code": null, "e": 3300, "s": 3285, "text": "Java-Functions" }, { "code": null, "e": 3312, "s": 3300, "text": "Java-Vector" }, { "code": null, "e": 3319, "s": 3312, "text": "Picked" }, { "code": null, "e": 3324, "s": 3319, "text": "Java" }, { "code": null, "e": 3343, "s": 3324, "text": "Technical Scripter" }, { "code": null, "e": 3348, "s": 3343, "text": "Java" }, { "code": null, "e": 3365, "s": 3348, "text": "Java-Collections" } ]
Google Kick Round-D Question (2020)
05 Dec, 2021 Isyana is given the number of visitors at her local theme park on N consecutive days. The number of visitors on the i-th day is VI. A day is record-breaking if it satisfies both of the following conditions: The number of visitors on the day is strictly larger than the number of visitors on each of the previous days.Either it is the last day, or the number of visitors on the day is strictly larger than the number of visitors on the following day. The number of visitors on the day is strictly larger than the number of visitors on each of the previous days. Either it is the last day, or the number of visitors on the day is strictly larger than the number of visitors on the following day. Note that the very first day could be a record-breaking day. Please help Isyana find out the number of record-breaking days. Input: The first line of the input gives the number of test cases, T. T test cases follow. Each test case begins with a line containing the integer N. The second line contains N integers. The i-th integer is Vi. Output: For each test case, output one line containing Case #x: y, where x is the test case number (starting from 1) and y is the number of record-breaking days. Limits Time limit: 20 seconds per test set. Memory limit: 1GB. 1 ≤ T ≤ 100. 0 ≤ Vi ≤ 2 × 105. Test set 1 1 ≤ N ≤ 1000. Test set 2 1 ≤ N ≤ 2 × 105 for at most 10 test cases. For the remaining cases, 1 ≤ N ≤ 1000. Sample Input Output 4 8 1 2 0 7 2 0 2 0 6 4 8 15 16 23 42 9 3 1 4 1 5 9 2 6 5 6 9 9 9 9 9 9 Case #1: 2 Case #2: 1 Case #3: 3 Case #4: 0 In Sample Case #1: The bold and underlined numbers in the following represent the record-breaking days: 1 2 0 7 2 0 2 0. In Sample Case #2: only the last day is a record-breaking day. In Sample Case #3: The first, the third, and the sixth days are record-breaking days. In Sample Case #4: there is no record-breaking day. C++ C# Javascript #include<iostream>using namespace std; int main(){ int n; cin>>n; int a[n]; for(int i=0;i<n;i++) { cin>>a[i]; } int count=0; for(int i=1;i<n;i++) { if(a[i]>a[i-1]&&a[i]>a[i+1]) { count++; } } cout<<count<<endl; return 0;} // C# program for the above approachusing System; public class GFG{ static int calculate(int[] arr, int n) { int cnt = 0; // initialising prevmax as -infinity int prevmax = Int32.MinValue; for (int i = 0; i < n; i++) { // check for condition 2 if (i == n - 1) { if (arr[i] > prevmax) cnt++; } // check for condition 1 else if (arr[i] > prevmax && arr[i] > arr[i + 1]) { cnt++; } // update prevmax prevmax = Math.Max(prevmax, arr[i]); } return cnt; } // Driver Code static public void Main () { int t = 1; // Taking the input for every test case while (t-- != 0) { int n = 9; int[] arr = { 3, 1, 4, 1, 5, 9, 2, 6, 5 }; Console.Write(calculate(arr, n)); } }} // This code is contributed by shubhamsingh10 <script> // Javascript program for the above approachfunction calculate(arr, n){ var cnt = 0; // Initialising prevmax as -infinity var prevmax = Number.MIN_VALUE; for(var i = 0; i < n; i++) { // Check for condition 2 if (i == n - 1) { if (arr[i] > prevmax) cnt++; } // Check for condition 1 else if (arr[i] > prevmax && arr[i] > arr[i + 1]) { cnt++; } // Update prevmax prevmax = Math.max(prevmax, arr[i]); } return cnt;} // Driver Codevar t = 1; // Taking the input for every test casewhile (t-- != 0){ var n = 9; var arr = [ 3, 1, 4, 1, 5, 9, 2, 6, 5 ]; document.write(calculate(arr, n));} // This code is contributed by shivanisinghss2110 </script> 3 Google Interview Experiences Google Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n05 Dec, 2021" }, { "code": null, "e": 259, "s": 52, "text": "Isyana is given the number of visitors at her local theme park on N consecutive days. The number of visitors on the i-th day is VI. A day is record-breaking if it satisfies both of the following conditions:" }, { "code": null, "e": 502, "s": 259, "text": "The number of visitors on the day is strictly larger than the number of visitors on each of the previous days.Either it is the last day, or the number of visitors on the day is strictly larger than the number of visitors on the following day." }, { "code": null, "e": 613, "s": 502, "text": "The number of visitors on the day is strictly larger than the number of visitors on each of the previous days." }, { "code": null, "e": 746, "s": 613, "text": "Either it is the last day, or the number of visitors on the day is strictly larger than the number of visitors on the following day." }, { "code": null, "e": 871, "s": 746, "text": "Note that the very first day could be a record-breaking day. Please help Isyana find out the number of record-breaking days." }, { "code": null, "e": 1083, "s": 871, "text": "Input: The first line of the input gives the number of test cases, T. T test cases follow. Each test case begins with a line containing the integer N. The second line contains N integers. The i-th integer is Vi." }, { "code": null, "e": 1245, "s": 1083, "text": "Output: For each test case, output one line containing Case #x: y, where x is the test case number (starting from 1) and y is the number of record-breaking days." }, { "code": null, "e": 1252, "s": 1245, "text": "Limits" }, { "code": null, "e": 1289, "s": 1252, "text": "Time limit: 20 seconds per test set." }, { "code": null, "e": 1308, "s": 1289, "text": "Memory limit: 1GB." }, { "code": null, "e": 1457, "s": 1308, "text": "1 ≤ T ≤ 100.\n0 ≤ Vi ≤ 2 × 105.\nTest set 1\n1 ≤ N ≤ 1000.\nTest set 2\n1 ≤ N ≤ 2 × 105 for at most 10 test cases.\nFor the remaining cases, 1 ≤ N ≤ 1000." }, { "code": null, "e": 1464, "s": 1457, "text": "Sample" }, { "code": null, "e": 1549, "s": 1464, "text": "Input\nOutput\n4\n8\n1 2 0 7 2 0 2 0\n6\n4 8 15 16 23 42\n9\n3 1 4 1 5 9 2 6 5\n6\n9 9 9 9 9 9" }, { "code": null, "e": 1593, "s": 1549, "text": "Case #1: 2\nCase #2: 1\nCase #3: 3\nCase #4: 0" }, { "code": null, "e": 1714, "s": 1593, "text": "In Sample Case #1: The bold and underlined numbers in the following represent the record-breaking days: 1 2 0 7 2 0 2 0." }, { "code": null, "e": 1777, "s": 1714, "text": "In Sample Case #2: only the last day is a record-breaking day." }, { "code": null, "e": 1863, "s": 1777, "text": "In Sample Case #3: The first, the third, and the sixth days are record-breaking days." }, { "code": null, "e": 1915, "s": 1863, "text": "In Sample Case #4: there is no record-breaking day." }, { "code": null, "e": 1919, "s": 1915, "text": "C++" }, { "code": null, "e": 1922, "s": 1919, "text": "C#" }, { "code": null, "e": 1933, "s": 1922, "text": "Javascript" }, { "code": "#include<iostream>using namespace std; int main(){ int n; cin>>n; int a[n]; for(int i=0;i<n;i++) { cin>>a[i]; } int count=0; for(int i=1;i<n;i++) { if(a[i]>a[i-1]&&a[i]>a[i+1]) { count++; } } cout<<count<<endl; return 0;}", "e": 2227, "s": 1933, "text": null }, { "code": "// C# program for the above approachusing System; public class GFG{ static int calculate(int[] arr, int n) { int cnt = 0; // initialising prevmax as -infinity int prevmax = Int32.MinValue; for (int i = 0; i < n; i++) { // check for condition 2 if (i == n - 1) { if (arr[i] > prevmax) cnt++; } // check for condition 1 else if (arr[i] > prevmax && arr[i] > arr[i + 1]) { cnt++; } // update prevmax prevmax = Math.Max(prevmax, arr[i]); } return cnt; } // Driver Code static public void Main () { int t = 1; // Taking the input for every test case while (t-- != 0) { int n = 9; int[] arr = { 3, 1, 4, 1, 5, 9, 2, 6, 5 }; Console.Write(calculate(arr, n)); } }} // This code is contributed by shubhamsingh10", "e": 3257, "s": 2227, "text": null }, { "code": "<script> // Javascript program for the above approachfunction calculate(arr, n){ var cnt = 0; // Initialising prevmax as -infinity var prevmax = Number.MIN_VALUE; for(var i = 0; i < n; i++) { // Check for condition 2 if (i == n - 1) { if (arr[i] > prevmax) cnt++; } // Check for condition 1 else if (arr[i] > prevmax && arr[i] > arr[i + 1]) { cnt++; } // Update prevmax prevmax = Math.max(prevmax, arr[i]); } return cnt;} // Driver Codevar t = 1; // Taking the input for every test casewhile (t-- != 0){ var n = 9; var arr = [ 3, 1, 4, 1, 5, 9, 2, 6, 5 ]; document.write(calculate(arr, n));} // This code is contributed by shivanisinghss2110 </script>", "e": 4100, "s": 3257, "text": null }, { "code": null, "e": 4102, "s": 4100, "text": "3" }, { "code": null, "e": 4109, "s": 4102, "text": "Google" }, { "code": null, "e": 4131, "s": 4109, "text": "Interview Experiences" }, { "code": null, "e": 4138, "s": 4131, "text": "Google" } ]
How to create a transparent histogram using ggplot2 in R?
When we create a histogram using ggplot2 package, the area covered by the histogram is filled with grey color but we can remove that color to make the histogram look transparent. This can be done by using fill="transparent" and color="black" arguments in geom_histogram, we need to use color argument because if we don’t use then the borders of the histogram bars will also be removed and this color is not restricted to black color only. Consider the below data frame − set.seed(987) x<-rnorm(10000,2,1.5) df<-data.frame(x) Loading ggplot2 package and creating histogram of x − library(ggplot2) ggplot(df,aes(x))+geom_histogram(bins=30) Creating the transparent histogram − ggplot(df,aes(x))+geom_histogram(bins=30,fill="transparent",color="black")
[ { "code": null, "e": 1501, "s": 1062, "text": "When we create a histogram using ggplot2 package, the area covered by the histogram is filled with grey color but we can remove that color to make the histogram look transparent. This can be done by using fill=\"transparent\" and color=\"black\" arguments in geom_histogram, we need to use color argument because if we don’t use then the borders of the histogram bars will also be removed and this color is not restricted to black color only." }, { "code": null, "e": 1533, "s": 1501, "text": "Consider the below data frame −" }, { "code": null, "e": 1587, "s": 1533, "text": "set.seed(987)\nx<-rnorm(10000,2,1.5)\ndf<-data.frame(x)" }, { "code": null, "e": 1641, "s": 1587, "text": "Loading ggplot2 package and creating histogram of x −" }, { "code": null, "e": 1700, "s": 1641, "text": "library(ggplot2) ggplot(df,aes(x))+geom_histogram(bins=30)" }, { "code": null, "e": 1737, "s": 1700, "text": "Creating the transparent histogram −" }, { "code": null, "e": 1812, "s": 1737, "text": "ggplot(df,aes(x))+geom_histogram(bins=30,fill=\"transparent\",color=\"black\")" } ]
How to change column names to capital letters from lower case or vice versa in R?
Mostly, we get data that contain column names in lowercase or just first letter is in upper case. If we want to convert those column names to all capital letter words or uppercase then toupper function can be used to the names of the columns. This can be done by using the below syntax − names(“data_frame_name”)<-toupper(names(“data_frame_name”)) Consider the below data frame − Live Demo set.seed(101) Age<-sample(21:50,20) Experience<-sample(0:10,20,replace=TRUE) BP<-sample(60:140,20) Employees<-data.frame(Age,Experience,BP) Employees Age Experience BP 1 32 7 95 2 22 10 140 3 40 2 120 4 38 7 85 5 27 10 90 6 28 8 77 7 35 0 65 8 45 4 127 9 34 4 116 10 50 7 67 11 47 4 134 12 42 3 136 13 39 2 106 14 36 1 109 15 43 5 129 16 29 10 111 17 41 2 104 18 23 8 93 19 25 0 103 20 21 10 96 Converting Age and Experience to AGE and EXPERIENCE − names(Employees)<-toupper(names(Employees)) Employees AGE EXPERIENCE BP 1 29 4 140 2 45 9 103 3 34 9 85 4 43 10 68 5 37 4 62 6 42 9 133 7 23 4 79 8 44 3 125 9 50 7 124 10 47 7 104 11 41 3 87 12 22 5 81 13 46 7 130 14 48 6 89 15 32 9 84 16 21 9 128 17 33 8 139 18 26 9 77 19 28 8 106 20 30 4 109 Let’s have a look at another example − Group1<-sample(0:20,20) Group2<-sample(0:20,20) Group3<-sample(0:20,20) Group4<-sample(0:20,20) Group5<-sample(0:20,20) Group6<-sample(0:20,20) Group7<-sample(0:20,20) Group8<-sample(0:20,20) Group9<-sample(0:20,20) Group10<-sample(0:20,20) Student<-data.frame(Group1,Group2,Group3,Group4,Group5,Group6,Group7,Group8,Group9,Group10) Student Group1 Group2 Group3 Group4 Group5 Group6 Group7 Group8 Group9 Group10 1 16 3 13 6 12 8 10 20 7 20 2 11 20 15 14 6 18 0 0 11 16 3 1 18 3 18 13 20 6 11 6 0 4 8 8 11 15 19 9 12 14 5 10 5 9 11 2 5 0 11 15 4 4 3 6 4 4 17 0 4 13 13 18 8 19 7 13 12 19 13 10 7 14 19 17 6 8 18 1 4 10 14 4 7 10 13 2 9 17 6 10 3 15 5 1 17 14 17 10 14 17 6 7 11 19 20 3 16 18 11 15 9 1 2 18 3 3 9 10 14 12 2 15 18 11 3 10 9 5 19 9 13 12 7 9 17 16 2 19 8 20 8 14 19 10 16 8 5 1 17 1 12 5 15 5 5 0 4 8 1 5 5 16 3 16 3 0 8 20 20 6 2 13 9 11 17 0 14 14 12 17 14 4 12 15 1 18 4 18 20 2 20 1 7 16 8 7 1 19 7 13 7 9 2 12 18 6 15 7 20 6 16 5 16 9 0 16 15 2 13 Converting column names from Group1 to GROUP1 and so on for all columns − names(Student)<-toupper(names(Student)) Student GROUP1 GROUP2 GROUP3 GROUP4 GROUP5 GROUP6 GROUP7 GROUP8 GROUP9 GROUP10 1 16 3 13 6 12 8 10 20 7 20 2 11 20 15 14 6 18 0 0 11 16 3 1 18 3 18 13 20 6 11 6 0 4 8 8 11 15 19 9 12 14 5 10 5 9 11 2 5 0 11 15 4 4 3 6 4 4 17 0 4 13 13 18 8 19 7 13 12 19 13 10 7 14 19 17 6 8 18 1 4 10 14 4 7 10 13 2 9 17 6 10 3 15 5 1 17 14 17 10 14 17 6 7 11 19 20 3 16 18 11 15 9 1 2 18 3 3 9 10 14 12 2 15 18 11 3 10 9 5 19 9 13 12 7 9 17 16 2 19 8 20 8 14 19 10 16 8 5 1 17 1 12 5 15 5 5 0 4 8 15 5 16 3 1 16 3 0 8 20 20 6 2 13 9 11 17 0 14 14 12 17 14 4 12 7 15 18 4 18 20 2 20 1 7 16 8 7 19 7 13 7 9 2 12 18 6 15 7 20 6 16 5 16 9 0 16 15 2 13
[ { "code": null, "e": 1350, "s": 1062, "text": "Mostly, we get data that contain column names in lowercase or just first letter is in upper case. If we want to convert those column names to all capital letter words or uppercase then toupper function can be used to the names of the columns. This can be done by using the below syntax −" }, { "code": null, "e": 1410, "s": 1350, "text": "names(“data_frame_name”)<-toupper(names(“data_frame_name”))" }, { "code": null, "e": 1442, "s": 1410, "text": "Consider the below data frame −" }, { "code": null, "e": 1453, "s": 1442, "text": " Live Demo" }, { "code": null, "e": 1603, "s": 1453, "text": "set.seed(101)\nAge<-sample(21:50,20)\nExperience<-sample(0:10,20,replace=TRUE)\nBP<-sample(60:140,20)\nEmployees<-data.frame(Age,Experience,BP)\nEmployees" }, { "code": null, "e": 2023, "s": 1603, "text": " Age Experience BP\n1 32 7 95\n2 22 10 140\n3 40 2 120\n4 38 7 85\n5 27 10 90\n6 28 8 77\n7 35 0 65\n8 45 4 127\n9 34 4 116\n10 50 7 67\n11 47 4 134\n12 42 3 136\n13 39 2 106\n14 36 1 109\n15 43 5 129\n16 29 10 111\n17 41 2 104\n18 23 8 93\n19 25 0 103\n20 21 10 96" }, { "code": null, "e": 2077, "s": 2023, "text": "Converting Age and Experience to AGE and EXPERIENCE −" }, { "code": null, "e": 2131, "s": 2077, "text": "names(Employees)<-toupper(names(Employees)) Employees" }, { "code": null, "e": 2539, "s": 2131, "text": " AGE EXPERIENCE BP\n1 29 4 140\n2 45 9 103\n3 34 9 85\n4 43 10 68\n5 37 4 62\n6 42 9 133\n7 23 4 79\n8 44 3 125\n9 50 7 124\n10 47 7 104\n11 41 3 87\n12 22 5 81\n13 46 7 130\n14 48 6 89\n15 32 9 84\n16 21 9 128\n17 33 8 139\n18 26 9 77\n19 28 8 106\n20 30 4 109" }, { "code": null, "e": 2578, "s": 2539, "text": "Let’s have a look at another example −" }, { "code": null, "e": 2819, "s": 2578, "text": "Group1<-sample(0:20,20)\nGroup2<-sample(0:20,20)\nGroup3<-sample(0:20,20)\nGroup4<-sample(0:20,20)\nGroup5<-sample(0:20,20)\nGroup6<-sample(0:20,20)\nGroup7<-sample(0:20,20)\nGroup8<-sample(0:20,20)\nGroup9<-sample(0:20,20)\nGroup10<-sample(0:20,20)" }, { "code": null, "e": 2919, "s": 2819, "text": "Student<-data.frame(Group1,Group2,Group3,Group4,Group5,Group6,Group7,Group8,Group9,Group10)\nStudent" }, { "code": null, "e": 4474, "s": 2919, "text": " Group1 Group2 Group3 Group4 Group5 Group6 Group7 Group8 Group9 Group10\n1 16 3 13 6 12 8 10 20 7 20\n2 11 20 15 14 6 18 0 0 11 16\n3 1 18 3 18 13 20 6 11 6 0\n4 8 8 11 15 19 9 12 14 5 10\n5 9 11 2 5 0 11 15 4 4 3\n6 4 4 17 0 4 13 13 18 8 19\n7 13 12 19 13 10 7 14 19 17 6\n8 18 1 4 10 14 4 7 10 13 2\n9 17 6 10 3 15 5 1 17 14 17\n10 14 17 6 7 11 19 20 3 16 18\n11 15 9 1 2 18 3 3 9 10 14\n12 2 15 18 11 3 10 9 5 19 9\n13 12 7 9 17 16 2 19 8 20 8\n14 19 10 16 8 5 1 17 1 12 5\n15 5 5 0 4 8 1 5 5 16 3\n16 3 0 8 20 20 6 2 13 9 11\n17 0 14 14 12 17 14 4 12 15 1\n18 4 18 20 2 20 1 7 16 8 7 1\n19 7 13 7 9 2 12 18 6 15 7\n20 6 16 5 16 9 0 16 15 2 13" }, { "code": null, "e": 4548, "s": 4474, "text": "Converting column names from Group1 to GROUP1 and so on for all columns −" }, { "code": null, "e": 4596, "s": 4548, "text": "names(Student)<-toupper(names(Student))\nStudent" }, { "code": null, "e": 5993, "s": 4596, "text": "GROUP1 GROUP2 GROUP3 GROUP4 GROUP5 GROUP6 GROUP7 GROUP8 GROUP9 GROUP10\n1 16 3 13 6 12 8 10 20 7 20\n2 11 20 15 14 6 18 0 0 11 16\n3 1 18 3 18 13 20 6 11 6 0\n4 8 8 11 15 19 9 12 14 5 10\n5 9 11 2 5 0 11 15 4 4 3\n6 4 4 17 0 4 13 13 18 8 19\n7 13 12 19 13 10 7 14 19 17 6\n8 18 1 4 10 14 4 7 10 13 2\n9 17 6 10 3 15 5 1 17 14 17\n10 14 17 6 7 11 19 20 3 16 18\n11 15 9 1 2 18 3 3 9 10 14\n12 2 15 18 11 3 10 9 5 19 9\n13 12 7 9 17 16 2 19 8 20 8\n14 19 10 16 8 5 1 17 1 12 5\n15 5 5 0 4 8 15 5 16 3 1\n16 3 0 8 20 20 6 2 13 9 11\n17 0 14 14 12 17 14 4 12 7 15\n18 4 18 20 2 20 1 7 16 8 7\n19 7 13 7 9 2 12 18 6 15 7\n20 6 16 5 16 9 0 16 15 2 13" } ]
Autocmplete ComboBox in Python-Tkinter - GeeksforGeeks
26 Mar, 2020 Prerequisites: Python GUI – tkinter The Listbox widget is used to display a list of items from which a user can select a number of items. But have you ever wondered, how to return the list of possible results when a key is pressed? Let’s see the following approach towards the same. Working of Program List consisting of words is initialized. Entry box and Listbox are created and are added to the root window. Bind function is used for event handling. Key release event is handled for an Entry field. When any key is pressed in the Entry, checkkey() function is called. checkkey() function then compares the entered string with existing list keywords and populates Listbox with matching keywords. Then this data is sent to update function which then updates the Listbox. Below is the approach. from tkinter import * # Function for checking the# key pressed and updating# the listboxdef checkkey(event): value = event.widget.get() print(value) # get data from l if value == '': data = l else: data = [] for item in l: if value.lower() in item.lower(): data.append(item) # update data in listbox update(data) def update(data): # clear previous data lb.delete(0, 'end') # put new data for item in data: lb.insert('end', item) # Driver codel = ('C','C++','Java', 'Python','Perl', 'PHP','ASP','JS' ) root = Tk() #creating text box e = Entry(root)e.pack()e.bind('<KeyRelease>', checkkey) #creating list boxlb = Listbox(root)lb.pack()update(l) root.mainloop() Output: Python-tkinter Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python String | replace() Python program to convert a list to string Create a Pandas DataFrame from Lists Reading and Writing to text files in Python
[ { "code": null, "e": 24380, "s": 24352, "text": "\n26 Mar, 2020" }, { "code": null, "e": 24416, "s": 24380, "text": "Prerequisites: Python GUI – tkinter" }, { "code": null, "e": 24663, "s": 24416, "text": "The Listbox widget is used to display a list of items from which a user can select a number of items. But have you ever wondered, how to return the list of possible results when a key is pressed? Let’s see the following approach towards the same." }, { "code": null, "e": 24682, "s": 24663, "text": "Working of Program" }, { "code": null, "e": 24723, "s": 24682, "text": "List consisting of words is initialized." }, { "code": null, "e": 24791, "s": 24723, "text": "Entry box and Listbox are created and are added to the root window." }, { "code": null, "e": 24882, "s": 24791, "text": "Bind function is used for event handling. Key release event is handled for an Entry field." }, { "code": null, "e": 24951, "s": 24882, "text": "When any key is pressed in the Entry, checkkey() function is called." }, { "code": null, "e": 25078, "s": 24951, "text": "checkkey() function then compares the entered string with existing list keywords and populates Listbox with matching keywords." }, { "code": null, "e": 25152, "s": 25078, "text": "Then this data is sent to update function which then updates the Listbox." }, { "code": null, "e": 25175, "s": 25152, "text": "Below is the approach." }, { "code": "from tkinter import * # Function for checking the# key pressed and updating# the listboxdef checkkey(event): value = event.widget.get() print(value) # get data from l if value == '': data = l else: data = [] for item in l: if value.lower() in item.lower(): data.append(item) # update data in listbox update(data) def update(data): # clear previous data lb.delete(0, 'end') # put new data for item in data: lb.insert('end', item) # Driver codel = ('C','C++','Java', 'Python','Perl', 'PHP','ASP','JS' ) root = Tk() #creating text box e = Entry(root)e.pack()e.bind('<KeyRelease>', checkkey) #creating list boxlb = Listbox(root)lb.pack()update(l) root.mainloop()", "e": 25991, "s": 25175, "text": null }, { "code": null, "e": 25999, "s": 25991, "text": "Output:" }, { "code": null, "e": 26014, "s": 25999, "text": "Python-tkinter" }, { "code": null, "e": 26021, "s": 26014, "text": "Python" }, { "code": null, "e": 26119, "s": 26021, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26128, "s": 26119, "text": "Comments" }, { "code": null, "e": 26141, "s": 26128, "text": "Old Comments" }, { "code": null, "e": 26159, "s": 26141, "text": "Python Dictionary" }, { "code": null, "e": 26194, "s": 26159, "text": "Read a file line by line in Python" }, { "code": null, "e": 26216, "s": 26194, "text": "Enumerate() in Python" }, { "code": null, "e": 26248, "s": 26216, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26278, "s": 26248, "text": "Iterate over a list in Python" }, { "code": null, "e": 26320, "s": 26278, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 26346, "s": 26320, "text": "Python String | replace()" }, { "code": null, "e": 26389, "s": 26346, "text": "Python program to convert a list to string" }, { "code": null, "e": 26426, "s": 26389, "text": "Create a Pandas DataFrame from Lists" } ]
Getting equal or greater than number from the list of numbers in JavaScript
We are required to write a JavaScript function that takes in an array of numbers as the first argument and a single number as the second argument. The function should return an array of all the elements from the input array that are greater than or equal to the number taken as the second argument. Following is the code − const arr = [56, 34, 2, 7, 76, 4, 45, 3, 3, 34, 23, 2, 56, 5]; const threshold = 40; const findGreater = (arr, num) => { const res = []; for(let i = 0; i < arr.length; i++){ if(arr[i] < num){ continue; }; res.push(arr[i]); }; return res; }; console.log(findGreater(arr, threshold)); This will produce the following output in console − [ 56, 76, 45, 56 ]
[ { "code": null, "e": 1361, "s": 1062, "text": "We are required to write a JavaScript function that takes in an array of numbers as the first argument and a single number as the second argument. The function should return an array of all the elements from the input array that are greater than or equal to the number taken as the second argument." }, { "code": null, "e": 1385, "s": 1361, "text": "Following is the code −" }, { "code": null, "e": 1707, "s": 1385, "text": "const arr = [56, 34, 2, 7, 76, 4, 45, 3, 3, 34, 23, 2, 56, 5];\nconst threshold = 40;\nconst findGreater = (arr, num) => {\n const res = [];\n for(let i = 0; i < arr.length; i++){\n if(arr[i] < num){\n continue;\n };\n res.push(arr[i]);\n };\n return res;\n};\nconsole.log(findGreater(arr, threshold));" }, { "code": null, "e": 1759, "s": 1707, "text": "This will produce the following output in console −" }, { "code": null, "e": 1778, "s": 1759, "text": "[ 56, 76, 45, 56 ]" } ]
Python Tweepy – Getting the number of times a tweet has been retweeted - GeeksforGeeks
18 Jun, 2020 In this article we will see how we can get the number of times a tweet/status has been retweeted. The retweet_count attribute of the Status object provides us with the number of times a tweet has been retweeted . Identifying the number of times a tweet has been retweeted in the GUI : The above mentioned status has been retweeted 4 times. In order to get the number of times a status has been retweeted, we have to do the following : Identify the status ID of the status from the GUI.Get the Status object of the status using the get_status() method with the status ID.From this object, fetch the retweet_count attribute present in it. Identify the status ID of the status from the GUI. Get the Status object of the status using the get_status() method with the status ID. From this object, fetch the retweet_count attribute present in it. Example 1 : Consider the following status : We will use the status ID to fetch the status. The status ID of the above mentioned status is 1272771459249844224. # import the moduleimport tweepy # assign the values accordinglyconsumer_key = ""consumer_secret = ""access_token = ""access_token_secret = "" # authorization of consumer key and consumer secretauth = tweepy.OAuthHandler(consumer_key, consumer_secret) # set access to user's access key and access secret auth.set_access_token(access_token, access_token_secret) # calling the api api = tweepy.API(auth) # the ID of the statusid = 1272771459249844224 # fetching the statusstatus = api.get_status(id) # fetching the retweet_count attributeretweet_count = status.retweet_count print("The number of time the status has been retweeted is : " + str(retweet_count)) Output : The number of time the status has been retweeted is : 0 Example 2 : Consider the following status : We will use the status ID to fetch the status. The status ID of the above mentioned status is 1272479136133627905. # the ID of the statusid = 1272479136133627905 # fetching the status with extended tweet_modestatus = api.get_status(id, tweet_mode = "extended") # fetching the retweet_count attributeretweet_count = status.retweet_count print("The number of time the status has been retweeted is : " + str(retweet_count)) Output : The number of time the status has been retweeted is : 22 Python-Tweepy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? How To Convert Python Dictionary To JSON? Check if element exists in list in Python How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | os.path.join() method Create a directory in Python Defaultdict in Python Python | Pandas dataframe.groupby() Python | Get unique values from a list
[ { "code": null, "e": 25647, "s": 25619, "text": "\n18 Jun, 2020" }, { "code": null, "e": 25860, "s": 25647, "text": "In this article we will see how we can get the number of times a tweet/status has been retweeted. The retweet_count attribute of the Status object provides us with the number of times a tweet has been retweeted ." }, { "code": null, "e": 25932, "s": 25860, "text": "Identifying the number of times a tweet has been retweeted in the GUI :" }, { "code": null, "e": 25987, "s": 25932, "text": "The above mentioned status has been retweeted 4 times." }, { "code": null, "e": 26082, "s": 25987, "text": "In order to get the number of times a status has been retweeted, we have to do the following :" }, { "code": null, "e": 26284, "s": 26082, "text": "Identify the status ID of the status from the GUI.Get the Status object of the status using the get_status() method with the status ID.From this object, fetch the retweet_count attribute present in it." }, { "code": null, "e": 26335, "s": 26284, "text": "Identify the status ID of the status from the GUI." }, { "code": null, "e": 26421, "s": 26335, "text": "Get the Status object of the status using the get_status() method with the status ID." }, { "code": null, "e": 26488, "s": 26421, "text": "From this object, fetch the retweet_count attribute present in it." }, { "code": null, "e": 26532, "s": 26488, "text": "Example 1 : Consider the following status :" }, { "code": null, "e": 26647, "s": 26532, "text": "We will use the status ID to fetch the status. The status ID of the above mentioned status is 1272771459249844224." }, { "code": "# import the moduleimport tweepy # assign the values accordinglyconsumer_key = \"\"consumer_secret = \"\"access_token = \"\"access_token_secret = \"\" # authorization of consumer key and consumer secretauth = tweepy.OAuthHandler(consumer_key, consumer_secret) # set access to user's access key and access secret auth.set_access_token(access_token, access_token_secret) # calling the api api = tweepy.API(auth) # the ID of the statusid = 1272771459249844224 # fetching the statusstatus = api.get_status(id) # fetching the retweet_count attributeretweet_count = status.retweet_count print(\"The number of time the status has been retweeted is : \" + str(retweet_count))", "e": 27314, "s": 26647, "text": null }, { "code": null, "e": 27323, "s": 27314, "text": "Output :" }, { "code": null, "e": 27380, "s": 27323, "text": "The number of time the status has been retweeted is : 0\n" }, { "code": null, "e": 27424, "s": 27380, "text": "Example 2 : Consider the following status :" }, { "code": null, "e": 27539, "s": 27424, "text": "We will use the status ID to fetch the status. The status ID of the above mentioned status is 1272479136133627905." }, { "code": "# the ID of the statusid = 1272479136133627905 # fetching the status with extended tweet_modestatus = api.get_status(id, tweet_mode = \"extended\") # fetching the retweet_count attributeretweet_count = status.retweet_count print(\"The number of time the status has been retweeted is : \" + str(retweet_count))", "e": 27849, "s": 27539, "text": null }, { "code": null, "e": 27858, "s": 27849, "text": "Output :" }, { "code": null, "e": 27916, "s": 27858, "text": "The number of time the status has been retweeted is : 22\n" }, { "code": null, "e": 27930, "s": 27916, "text": "Python-Tweepy" }, { "code": null, "e": 27937, "s": 27930, "text": "Python" }, { "code": null, "e": 28035, "s": 27937, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28067, "s": 28035, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28109, "s": 28067, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28151, "s": 28109, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28207, "s": 28151, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28234, "s": 28207, "text": "Python Classes and Objects" }, { "code": null, "e": 28265, "s": 28234, "text": "Python | os.path.join() method" }, { "code": null, "e": 28294, "s": 28265, "text": "Create a directory in Python" }, { "code": null, "e": 28316, "s": 28294, "text": "Defaultdict in Python" }, { "code": null, "e": 28352, "s": 28316, "text": "Python | Pandas dataframe.groupby()" } ]